Transaction Hash:
Block:
10389696 at Jul-04-2020 12:25:22 AM +UTC
Transaction Fee:
0.0051166 ETH
$10.48
Gas Used:
204,664 Gas / 25 Gwei
Emitted Events:
| 32 |
Dai.Transfer( src=0xdb4ddf47F9be73e1d3E572494cE746bE4694aaCE, dst=0x3cB5Cbf0DE30B516dEce1bA0200725c3927e4889, wad=205210000000000000000 )
|
| 33 |
0xdb4ddf47f9be73e1d3e572494ce746be4694aace.0xbda29dc1242153445159457be3dc12cdc3b4ca777000c536f8a42078b029672d( 0xbda29dc1242153445159457be3dc12cdc3b4ca777000c536f8a42078b029672d, 0x0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f, 0x0000000000000000000000003cb5cbf0de30b516dece1ba0200725c3927e4889, 00000000000000000000000000000000000000000000000b1fdc5fc035e90000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000 )
|
| 34 |
InstaEvent.LogEvent( connectorType=1, connectorID=19, accountID=4024, eventCode=BDA29DC1242153445159457BE3DC12CDC3B4CA777000C536F8A42078B029672D, eventData=0x0000000000000000000000006B175474E89094C44DA98B954EEDEAC495271D0F00000000000000000000000000000000000000000000000B1FDC5FC035E900000000000000000000000000003CB5CBF0DE30B516DECE1BA0200725C3927E488900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 )
|
| 35 |
0xdb4ddf47f9be73e1d3e572494ce746be4694aace.0x88c16fce368c171f39a2eb45acade4f8e2316d6c47b08e53f941ca3f90bc6ef2( 0x88c16fce368c171f39a2eb45acade4f8e2316d6c47b08e53f941ca3f90bc6ef2, 0x000000000000000000000000a7615cd307f323172331865181dc8b80a2834324, 0x0000000000000000000000003cb5cbf0de30b516dece1ba0200725c3927e4889, 0000000000000000000000000000000000000000000000000000000000000000 )
|
| 36 |
0x3cb5cbf0de30b516dece1ba0200725c3927e4889.0x7d2476ab50663f025cff0be85655bcf355f62768615c0c478f3cd5293f807365( 0x7d2476ab50663f025cff0be85655bcf355f62768615c0c478f3cd5293f807365, 0x000000000000000000000000103675510a219bd84ce91d1bcb82ca194d665a09, 0x000000000000000000000000db4ddf47f9be73e1d3e572494ce746be4694aace, 0x0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000020, 00000000000000000000000000000000000000000000000000000000000001c4, e0e90acf00000000000000000000000000000000000000000000000000000000, 0000006000000000000000000000000000000000000000000000000000000000, 000000a0000000000000000000000000a7615cd307f323172331865181dc8b80, a283432400000000000000000000000000000000000000000000000000000000, 000000010000000000000000000000006a31c5982c5bc5533432913cf06a66b6, d3333a9500000000000000000000000000000000000000000000000000000000, 0000000100000000000000000000000000000000000000000000000000000000, 0000002000000000000000000000000000000000000000000000000000000000, 000000a44bd3ab820000000000000000000000006b175474e89094c44da98b95, 4eedeac495271d0fffffffffffffffffffffffffffffffffffffffffffffffff, ffffffffffffffff0000000000000000000000003cb5cbf0de30b516dece1ba0, 200725c3927e4889000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000 )
|
| 37 |
TransferManager.CalledContract( wallet=0x3cB5Cbf0DE30B516dEce1bA0200725c3927e4889, to=0xdb4ddf47F9be73e1d3E572494cE746bE4694aaCE, amount=0, data=0xE0E90ACF000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000A0000000000000000000000000A7615CD307F323172331865181DC8B80A283432400000000000000000000000000000000000000000000000000000000000000010000000000000000000000006A31C5982C5BC5533432913CF06A66B6D3333A950000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000A44BD3AB820000000000000000000000006B175474E89094C44DA98B954EEDEAC495271D0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000003CB5CBF0DE30B516DECE1BA0200725C3927E48890000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 )
|
| 38 |
0x3cb5cbf0de30b516dece1ba0200725c3927e4889.0x7d2476ab50663f025cff0be85655bcf355f62768615c0c478f3cd5293f807365( 0x7d2476ab50663f025cff0be85655bcf355f62768615c0c478f3cd5293f807365, 0x000000000000000000000000103675510a219bd84ce91d1bcb82ca194d665a09, 0x0000000000000000000000000385b3f162a0e001b60ecb84d3cb06199d78f666, 0x000000000000000000000000000000000000000000000000001184dad4158c00, 0000000000000000000000000000000000000000000000000000000000000020, 0000000000000000000000000000000000000000000000000000000000000000 )
|
| 39 |
TransferManager.TransactionExecuted( wallet=0x3cB5Cbf0DE30B516dEce1bA0200725c3927e4889, success=True, signedHash=180EBCE848D0AD069ADB98D43419D9D426E332CBA2DB3E9531557F57E3C22845 )
|
Account State Difference:
| Address | Before | After | State Difference | ||
|---|---|---|---|---|---|
| 0x0385b3F1...99d78f666 | (Argent: Relayer 2) |
3.2726075543 Eth
Nonce: 78632
|
3.2724221043 Eth
Nonce: 78633
| 0.00018545 | |
| 0x10367551...94D665a09 | (Argent: Transfer Manager) | ||||
| 0x3cB5Cbf0...3927e4889 | 0.167505872283741869 Eth | 0.162574722283741869 Eth | 0.00493115 | ||
|
0x5A0b54D5...D3E029c4c
Miner
| (Spark Pool) | 61.754397714859600026 Eth | 61.759514314859600026 Eth | 0.0051166 | |
| 0x6B175474...495271d0F |
Execution Trace
TransferManager.execute( _wallet=0x3cB5Cbf0DE30B516dEce1bA0200725c3927e4889, _data=0xFD6AC3090000000000000000000000003CB5CBF0DE30B516DECE1BA0200725C3927E4889000000000000000000000000DB4DDF47F9BE73E1D3E572494CE746BE4694AACE0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000001C4E0E90ACF000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000A0000000000000000000000000A7615CD307F323172331865181DC8B80A283432400000000000000000000000000000000000000000000000000000000000000010000000000000000000000006A31C5982C5BC5533432913CF06A66B6D3333A950000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000A44BD3AB820000000000000000000000006B175474E89094C44DA98B954EEDEAC495271D0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000003CB5CBF0DE30B516DECE1BA0200725C3927E4889000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, _nonce=3535428985339538986337715451836982734012533813, _signatures=0xF3592F123B31A30740E1CF36EBB450EC388BB81FF1D9F218182507BEA176E34939142E33561A38AFCDA143E253211DA8C7A5BCC3CDDAEA280785FA7C1219F0321B, _gasPrice=25000000000, _gasLimit=299399 ) => ( success=True )
0x3cb5cbf0de30b516dece1ba0200725c3927e4889.d6eb1bbf( )-
BaseWallet.authorised( 0x103675510a219bd84CE91d1bcb82Ca194D665a09 ) => ( True )
-
-
Null: 0x000...001.180ebce8( ) 0x3cb5cbf0de30b516dece1ba0200725c3927e4889.STATICCALL( )-
BaseWallet.DELEGATECALL( )
-
TransferManager.callContract( _wallet=0x3cB5Cbf0DE30B516dEce1bA0200725c3927e4889, _contract=0xdb4ddf47F9be73e1d3E572494cE746bE4694aaCE, _value=0, _data=0xE0E90ACF000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000A0000000000000000000000000A7615CD307F323172331865181DC8B80A283432400000000000000000000000000000000000000000000000000000000000000010000000000000000000000006A31C5982C5BC5533432913CF06A66B6D3333A950000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000A44BD3AB820000000000000000000000006B175474E89094C44DA98B954EEDEAC495271D0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000003CB5CBF0DE30B516DECE1BA0200725C3927E48890000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 )-
0x44da3a8051ba88eab0440db3779cab9d679ae76f.4a4fbeec( ) 0x3cb5cbf0de30b516dece1ba0200725c3927e4889.d6eb1bbf( )-
BaseWallet.authorised( 0xdb4ddf47F9be73e1d3E572494cE746bE4694aaCE ) => ( False )
-
-
TokenPriceProvider.cachedPrices( 0xdb4ddf47F9be73e1d3E572494cE746bE4694aaCE ) => ( 0 ) -
0x391f0e86da951c03b1183c60b195090671adea88.13f4a0ea( ) 0x3cb5cbf0de30b516dece1ba0200725c3927e4889.8f6f0332( )BaseWallet.invoke( _target=0xdb4ddf47F9be73e1d3E572494cE746bE4694aaCE, _value=0, _data=0xE0E90ACF000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000A0000000000000000000000000A7615CD307F323172331865181DC8B80A283432400000000000000000000000000000000000000000000000000000000000000010000000000000000000000006A31C5982C5BC5533432913CF06A66B6D3333A950000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000A44BD3AB820000000000000000000000006B175474E89094C44DA98B954EEDEAC495271D0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000003CB5CBF0DE30B516DECE1BA0200725C3927E48890000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ) => ( _result=0x )0xdb4ddf47f9be73e1d3e572494ce746be4694aace.e0e90acf( )InstaAccount.cast( _targets=[0x6a31c5982C5Bc5533432913cf06a66b6D3333a95], _datas=[S9OrggAAAAAAAAAAAAAAAGsXVHTokJTETamLlU7t6sSVJx0P//////////////////////////////////////////8AAAAAAAAAAAAAAAA8tcvw3jC1Ft7OG6AgByXDkn5IiQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=], _origin=0xa7615CD307F323172331865181DC8b80a2834324 )-
InstaIndex.connectors( 1 ) => ( 0xD6A602C01a023B98Ecfb29Df02FBA380d3B21E0c ) -
InstaConnectors.isConnector( _connectors=[0x6a31c5982C5Bc5533432913cf06a66b6D3333a95] ) => ( isOk=True ) -
ConnectBasic.withdraw( erc20=0x6B175474E89094C44Da98b954EedeAC495271d0F, tokenAmt=115792089237316195423570985008687907853269984665640564039457584007913129639935, to=0x3cB5Cbf0DE30B516dEce1bA0200725c3927e4889, getId=0, setId=0 )
-
InstaIndex.check( 1 ) => ( 0x06cB7C24990cBE6b9F99982f975f9147c000fec6 ) -
InstaPool.STATICCALL( )
-
-
0x3cb5cbf0de30b516dece1ba0200725c3927e4889.8f6f0332( )BaseWallet.invoke( _target=0x0385b3F162a0e001b60Ecb84D3CB06199d78f666, _value=4931150000000000, _data=0x ) => ( _result=0x )- ETH 0.00493115
Argent: Relayer 2.CALL( )
- ETH 0.00493115
execute[RelayerModule (ln:956)]
gasleft[RelayerModule (ln:967)]getSignHash[RelayerModule (ln:968)]checkAndUpdateUniqueness[RelayerModule (ln:969)]verifyData[RelayerModule (ln:970)]getRequiredSignatures[RelayerModule (ln:971)]verifyRefund[RelayerModule (ln:973)]authorised[RelayerModule (ln:1108)]
validateSignatures[RelayerModule (ln:974)]call[RelayerModule (ln:976)]refund[RelayerModule (ln:977)]invokeWallet[RelayerModule (ln:1095)]
gasleft[RelayerModule (ln:977)]TransactionExecuted[RelayerModule (ln:981)]
File 1 of 10: TransferManager
File 2 of 10: Dai
File 3 of 10: InstaEvent
File 4 of 10: BaseWallet
File 5 of 10: TokenPriceProvider
File 6 of 10: InstaAccount
File 7 of 10: InstaIndex
File 8 of 10: InstaConnectors
File 9 of 10: ConnectBasic
File 10 of 10: InstaPool
pragma solidity ^0.5.4;// 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/>.
/**
* @title Module
* @dev Interface for a module.
* A module MUST implement the addModule() method to ensure that a wallet with at least one module
* can never end up in a "frozen" state.
* @author Julien Niset - <julien@argent.xyz>
*/
interface Module {
/**
* @dev Inits a module for a wallet by e.g. setting some wallet specific parameters in storage.
* @param _wallet The wallet.
*/
function init(BaseWallet _wallet) external;
/**
* @dev Adds a module to a wallet.
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(BaseWallet _wallet, Module _module) external;
/**
* @dev Utility method to recover any ERC20 token that was sent to the
* module by mistake.
* @param _token The token to recover.
*/
function recoverToken(address _token) external;
}// 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/>.
/**
* @title BaseWallet
* @dev Simple modular wallet that authorises modules to call its invoke() method.
* @author Julien Niset - <julien@argent.xyz>
*/
contract BaseWallet {
// The implementation of the proxy
address public implementation;
// The owner
address public owner;
// The authorised modules
mapping (address => bool) public authorised;
// The enabled static calls
mapping (bytes4 => address) public enabled;
// The number of modules
uint public modules;
event AuthorisedModule(address indexed module, bool value);
event EnabledStaticCall(address indexed module, bytes4 indexed method);
event Invoked(address indexed module, address indexed target, uint indexed value, bytes data);
event Received(uint indexed value, address indexed sender, bytes data);
event OwnerChanged(address owner);
/**
* @dev Throws if the sender is not an authorised module.
*/
modifier moduleOnly {
require(authorised[msg.sender], "BW: msg.sender not an authorized module");
_;
}
/**
* @dev Inits the wallet by setting the owner and authorising a list of modules.
* @param _owner The owner.
* @param _modules The modules to authorise.
*/
function init(address _owner, address[] calldata _modules) external {
require(owner == address(0) && modules == 0, "BW: wallet already initialised");
require(_modules.length > 0, "BW: construction requires at least 1 module");
owner = _owner;
modules = _modules.length;
for (uint256 i = 0; i < _modules.length; i++) {
require(authorised[_modules[i]] == false, "BW: module is already added");
authorised[_modules[i]] = true;
Module(_modules[i]).init(this);
emit AuthorisedModule(_modules[i], true);
}
if (address(this).balance > 0) {
emit Received(address(this).balance, address(0), "");
}
}
/**
* @dev Enables/Disables a module.
* @param _module The target module.
* @param _value Set to true to authorise the module.
*/
function authoriseModule(address _module, bool _value) external moduleOnly {
if (authorised[_module] != _value) {
emit AuthorisedModule(_module, _value);
if (_value == true) {
modules += 1;
authorised[_module] = true;
Module(_module).init(this);
} else {
modules -= 1;
require(modules > 0, "BW: wallet must have at least one module");
delete authorised[_module];
}
}
}
/**
* @dev Enables a static method by specifying the target module to which the call
* must be delegated.
* @param _module The target module.
* @param _method The static method signature.
*/
function enableStaticCall(address _module, bytes4 _method) external moduleOnly {
require(authorised[_module], "BW: must be an authorised module for static call");
enabled[_method] = _module;
emit EnabledStaticCall(_module, _method);
}
/**
* @dev Sets a new owner for the wallet.
* @param _newOwner The new owner.
*/
function setOwner(address _newOwner) external moduleOnly {
require(_newOwner != address(0), "BW: address cannot be null");
owner = _newOwner;
emit OwnerChanged(_newOwner);
}
/**
* @dev Performs a generic transaction.
* @param _target The address for the transaction.
* @param _value The value of the transaction.
* @param _data The data of the transaction.
*/
function invoke(address _target, uint _value, bytes calldata _data) external moduleOnly returns (bytes memory _result) {
bool success;
// solium-disable-next-line security/no-call-value
(success, _result) = _target.call.value(_value)(_data);
if (!success) {
// solium-disable-next-line security/no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
emit Invoked(msg.sender, _target, _value, _data);
}
/**
* @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to
* implement specific static methods. It delegates the static call to a target contract if the data corresponds
* to an enabled method, or logs the call otherwise.
*/
function() external payable {
if (msg.data.length > 0) {
address module = enabled[msg.sig];
if (module == address(0)) {
emit Received(msg.value, msg.sender, msg.data);
} else {
require(authorised[module], "BW: must be an authorised module for static call");
// solium-disable-next-line security/no-inline-assembly
assembly {
calldatacopy(0, 0, calldatasize())
let result := staticcall(gas, module, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
}
}// 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/>.
/**
* @title Owned
* @dev Basic contract to define an owner.
* @author Julien Niset - <julien@argent.im>
*/
contract Owned {
// The owner
address public owner;
event OwnerChanged(address indexed _newOwner);
/**
* @dev Throws if the sender is not the owner.
*/
modifier onlyOwner {
require(msg.sender == owner, "Must be owner");
_;
}
constructor() public {
owner = msg.sender;
}
/**
* @dev Lets the owner transfer ownership of the contract to a new owner.
* @param _newOwner The new owner.
*/
function changeOwner(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "Address must not be null");
owner = _newOwner;
emit OwnerChanged(_newOwner);
}
}
/**
* ERC20 contract interface.
*/
contract ERC20 {
function totalSupply() public view returns (uint);
function decimals() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
}// 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/>.
/**
* @title ModuleRegistry
* @dev Registry of authorised modules.
* Modules must be registered before they can be authorised on a wallet.
* @author Julien Niset - <julien@argent.im>
*/
contract ModuleRegistry is Owned {
mapping (address => Info) internal modules;
mapping (address => Info) internal upgraders;
event ModuleRegistered(address indexed module, bytes32 name);
event ModuleDeRegistered(address module);
event UpgraderRegistered(address indexed upgrader, bytes32 name);
event UpgraderDeRegistered(address upgrader);
struct Info {
bool exists;
bytes32 name;
}
/**
* @dev Registers a module.
* @param _module The module.
* @param _name The unique name of the module.
*/
function registerModule(address _module, bytes32 _name) external onlyOwner {
require(!modules[_module].exists, "MR: module already exists");
modules[_module] = Info({exists: true, name: _name});
emit ModuleRegistered(_module, _name);
}
/**
* @dev Deregisters a module.
* @param _module The module.
*/
function deregisterModule(address _module) external onlyOwner {
require(modules[_module].exists, "MR: module does not exist");
delete modules[_module];
emit ModuleDeRegistered(_module);
}
/**
* @dev Registers an upgrader.
* @param _upgrader The upgrader.
* @param _name The unique name of the upgrader.
*/
function registerUpgrader(address _upgrader, bytes32 _name) external onlyOwner {
require(!upgraders[_upgrader].exists, "MR: upgrader already exists");
upgraders[_upgrader] = Info({exists: true, name: _name});
emit UpgraderRegistered(_upgrader, _name);
}
/**
* @dev Deregisters an upgrader.
* @param _upgrader The _upgrader.
*/
function deregisterUpgrader(address _upgrader) external onlyOwner {
require(upgraders[_upgrader].exists, "MR: upgrader does not exist");
delete upgraders[_upgrader];
emit UpgraderDeRegistered(_upgrader);
}
/**
* @dev Utility method enbaling the owner of the registry to claim any ERC20 token that was sent to the
* registry.
* @param _token The token to recover.
*/
function recoverToken(address _token) external onlyOwner {
uint total = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(msg.sender, total);
}
/**
* @dev Gets the name of a module from its address.
* @param _module The module address.
* @return the name.
*/
function moduleInfo(address _module) external view returns (bytes32) {
return modules[_module].name;
}
/**
* @dev Gets the name of an upgrader from its address.
* @param _upgrader The upgrader address.
* @return the name.
*/
function upgraderInfo(address _upgrader) external view returns (bytes32) {
return upgraders[_upgrader].name;
}
/**
* @dev Checks if a module is registered.
* @param _module The module address.
* @return true if the module is registered.
*/
function isRegisteredModule(address _module) external view returns (bool) {
return modules[_module].exists;
}
/**
* @dev Checks if a list of modules are registered.
* @param _modules The list of modules address.
* @return true if all the modules are registered.
*/
function isRegisteredModule(address[] calldata _modules) external view returns (bool) {
for (uint i = 0; i < _modules.length; i++) {
if (!modules[_modules[i]].exists) {
return false;
}
}
return true;
}
/**
* @dev Checks if an upgrader is registered.
* @param _upgrader The upgrader address.
* @return true if the upgrader is registered.
*/
function isRegisteredUpgrader(address _upgrader) external view returns (bool) {
return upgraders[_upgrader].exists;
}
}// 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/>.
/**
* @title Storage
* @dev Base contract for the storage of a wallet.
* @author Julien Niset - <julien@argent.im>
*/
contract Storage {
/**
* @dev Throws if the caller is not an authorised module.
*/
modifier onlyModule(BaseWallet _wallet) {
require(_wallet.authorised(msg.sender), "TS: must be an authorized module to call this method");
_;
}
}// 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/>.
interface IGuardianStorage{
/**
* @dev Lets an authorised module add a guardian to a wallet.
* @param _wallet The target wallet.
* @param _guardian The guardian to add.
*/
function addGuardian(BaseWallet _wallet, address _guardian) external;
/**
* @dev Lets an authorised module revoke a guardian from a wallet.
* @param _wallet The target wallet.
* @param _guardian The guardian to revoke.
*/
function revokeGuardian(BaseWallet _wallet, address _guardian) external;
/**
* @dev Checks if an account is a guardian for a wallet.
* @param _wallet The target wallet.
* @param _guardian The account.
* @return true if the account is a guardian for a wallet.
*/
function isGuardian(BaseWallet _wallet, address _guardian) external view returns (bool);
}// 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/>.
/**
* @title GuardianStorage
* @dev Contract storing the state of wallets related to guardians and lock.
* The contract only defines basic setters and getters with no logic. Only modules authorised
* for a wallet can modify its state.
* @author Julien Niset - <julien@argent.im>
* @author Olivier Van Den Biggelaar - <olivier@argent.im>
*/
contract GuardianStorage is IGuardianStorage, Storage {
struct GuardianStorageConfig {
// the list of guardians
address[] guardians;
// the info about guardians
mapping (address => GuardianInfo) info;
// the lock's release timestamp
uint256 lock;
// the module that set the last lock
address locker;
}
struct GuardianInfo {
bool exists;
uint128 index;
}
// wallet specific storage
mapping (address => GuardianStorageConfig) internal configs;
// *************** External Functions ********************* //
/**
* @dev Lets an authorised module add a guardian to a wallet.
* @param _wallet The target wallet.
* @param _guardian The guardian to add.
*/
function addGuardian(BaseWallet _wallet, address _guardian) external onlyModule(_wallet) {
GuardianStorageConfig storage config = configs[address(_wallet)];
config.info[_guardian].exists = true;
config.info[_guardian].index = uint128(config.guardians.push(_guardian) - 1);
}
/**
* @dev Lets an authorised module revoke a guardian from a wallet.
* @param _wallet The target wallet.
* @param _guardian The guardian to revoke.
*/
function revokeGuardian(BaseWallet _wallet, address _guardian) external onlyModule(_wallet) {
GuardianStorageConfig storage config = configs[address(_wallet)];
address lastGuardian = config.guardians[config.guardians.length - 1];
if (_guardian != lastGuardian) {
uint128 targetIndex = config.info[_guardian].index;
config.guardians[targetIndex] = lastGuardian;
config.info[lastGuardian].index = targetIndex;
}
config.guardians.length--;
delete config.info[_guardian];
}
/**
* @dev Returns the number of guardians for a wallet.
* @param _wallet The target wallet.
* @return the number of guardians.
*/
function guardianCount(BaseWallet _wallet) external view returns (uint256) {
return configs[address(_wallet)].guardians.length;
}
/**
* @dev Gets the list of guaridans for a wallet.
* @param _wallet The target wallet.
* @return the list of guardians.
*/
function getGuardians(BaseWallet _wallet) external view returns (address[] memory) {
GuardianStorageConfig storage config = configs[address(_wallet)];
address[] memory guardians = new address[](config.guardians.length);
for (uint256 i = 0; i < config.guardians.length; i++) {
guardians[i] = config.guardians[i];
}
return guardians;
}
/**
* @dev Checks if an account is a guardian for a wallet.
* @param _wallet The target wallet.
* @param _guardian The account.
* @return true if the account is a guardian for a wallet.
*/
function isGuardian(BaseWallet _wallet, address _guardian) external view returns (bool) {
return configs[address(_wallet)].info[_guardian].exists;
}
/**
* @dev Lets an authorised module set the lock for a wallet.
* @param _wallet The target wallet.
* @param _releaseAfter The epoch time at which the lock should automatically release.
*/
function setLock(BaseWallet _wallet, uint256 _releaseAfter) external onlyModule(_wallet) {
configs[address(_wallet)].lock = _releaseAfter;
if (_releaseAfter != 0 && msg.sender != configs[address(_wallet)].locker) {
configs[address(_wallet)].locker = msg.sender;
}
}
/**
* @dev Checks if the lock is set for a wallet.
* @param _wallet The target wallet.
* @return true if the lock is set for the wallet.
*/
function isLocked(BaseWallet _wallet) external view returns (bool) {
return configs[address(_wallet)].lock > now;
}
/**
* @dev Gets the time at which the lock of a wallet will release.
* @param _wallet The target wallet.
* @return the time at which the lock of a wallet will release, or zero if there is no lock set.
*/
function getLock(BaseWallet _wallet) external view returns (uint256) {
return configs[address(_wallet)].lock;
}
/**
* @dev Gets the address of the last module that modified the lock for a wallet.
* @param _wallet The target wallet.
* @return the address of the last module that modified the lock for a wallet.
*/
function getLocker(BaseWallet _wallet) external view returns (address) {
return configs[address(_wallet)].locker;
}
}/* The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
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. */
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
/**
* @dev Returns ceil(a / b).
*/
function ceil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
if(a % b == 0) {
return c;
}
else {
return c + 1;
}
}
// from DSMath - operations on fixed precision floats
uint256 constant WAD = 10 ** 18;
uint256 constant RAY = 10 ** 27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
}
// 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/>.
/**
* @title BaseModule
* @dev Basic module that contains some methods common to all modules.
* @author Julien Niset - <julien@argent.im>
*/
contract BaseModule is Module {
// Empty calldata
bytes constant internal EMPTY_BYTES = "";
// The adddress of the module registry.
ModuleRegistry internal registry;
// The address of the Guardian storage
GuardianStorage internal guardianStorage;
/**
* @dev Throws if the wallet is locked.
*/
modifier onlyWhenUnlocked(BaseWallet _wallet) {
// solium-disable-next-line security/no-block-members
require(!guardianStorage.isLocked(_wallet), "BM: wallet must be unlocked");
_;
}
event ModuleCreated(bytes32 name);
event ModuleInitialised(address wallet);
constructor(ModuleRegistry _registry, GuardianStorage _guardianStorage, bytes32 _name) public {
registry = _registry;
guardianStorage = _guardianStorage;
emit ModuleCreated(_name);
}
/**
* @dev Throws if the sender is not the target wallet of the call.
*/
modifier onlyWallet(BaseWallet _wallet) {
require(msg.sender == address(_wallet), "BM: caller must be wallet");
_;
}
/**
* @dev Throws if the sender is not the owner of the target wallet or the module itself.
*/
modifier onlyWalletOwner(BaseWallet _wallet) {
require(msg.sender == address(this) || isOwner(_wallet, msg.sender), "BM: must be an owner for the wallet");
_;
}
/**
* @dev Throws if the sender is not the owner of the target wallet.
*/
modifier strictOnlyWalletOwner(BaseWallet _wallet) {
require(isOwner(_wallet, msg.sender), "BM: msg.sender must be an owner for the wallet");
_;
}
/**
* @dev Inits the module for a wallet by logging an event.
* The method can only be called by the wallet itself.
* @param _wallet The wallet.
*/
function init(BaseWallet _wallet) public onlyWallet(_wallet) {
emit ModuleInitialised(address(_wallet));
}
/**
* @dev Adds a module to a wallet. First checks that the module is registered.
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(BaseWallet _wallet, Module _module) external strictOnlyWalletOwner(_wallet) {
require(registry.isRegisteredModule(address(_module)), "BM: module is not registered");
_wallet.authoriseModule(address(_module), true);
}
/**
* @dev Utility method enbaling anyone to recover ERC20 token sent to the
* module by mistake and transfer them to the Module Registry.
* @param _token The token to recover.
*/
function recoverToken(address _token) external {
uint total = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(address(registry), total);
}
/**
* @dev Helper method to check if an address is the owner of a target wallet.
* @param _wallet The target wallet.
* @param _addr The address.
*/
function isOwner(BaseWallet _wallet, address _addr) internal view returns (bool) {
return _wallet.owner() == _addr;
}
/**
* @dev Helper method to invoke a wallet.
* @param _wallet The target wallet.
* @param _to The target address for the transaction.
* @param _value The value of the transaction.
* @param _data The data of the transaction.
*/
function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) {
bool success;
// solium-disable-next-line security/no-call-value
(success, _res) = _wallet.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _to, _value, _data));
if (success && _res.length > 0) { //_res is empty if _wallet is an "old" BaseWallet that can't return output values
(_res) = abi.decode(_res, (bytes));
} else if (_res.length > 0) {
// solium-disable-next-line security/no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
} else if (!success) {
revert("BM: wallet invoke reverted");
}
}
}// 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/>.
/**
* @title RelayerModule
* @dev Base module containing logic to execute transactions signed by eth-less accounts and sent by a relayer.
* @author Julien Niset - <julien@argent.im>
*/
contract RelayerModule is BaseModule {
uint256 constant internal BLOCKBOUND = 10000;
mapping (address => RelayerConfig) public relayer;
struct RelayerConfig {
uint256 nonce;
mapping (bytes32 => bool) executedTx;
}
event TransactionExecuted(address indexed wallet, bool indexed success, bytes32 signedHash);
/**
* @dev Throws if the call did not go through the execute() method.
*/
modifier onlyExecute {
require(msg.sender == address(this), "RM: must be called via execute()");
_;
}
/* ***************** Abstract method ************************* */
/**
* @dev Gets the number of valid signatures that must be provided to execute a
* specific relayed transaction.
* @param _wallet The target wallet.
* @param _data The data of the relayed transaction.
* @return The number of required signatures.
*/
function getRequiredSignatures(BaseWallet _wallet, bytes memory _data) internal view returns (uint256);
/**
* @dev Validates the signatures provided with a relayed transaction.
* The method MUST throw if one or more signatures are not valid.
* @param _wallet The target wallet.
* @param _data The data of the relayed transaction.
* @param _signHash The signed hash representing the relayed transaction.
* @param _signatures The signatures as a concatenated byte array.
*/
function validateSignatures(
BaseWallet _wallet,
bytes memory _data,
bytes32 _signHash,
bytes memory _signatures) internal view returns (bool);
/* ************************************************************ */
/**
* @dev Executes a relayed transaction.
* @param _wallet The target wallet.
* @param _data The data for the relayed transaction
* @param _nonce The nonce used to prevent replay attacks.
* @param _signatures The signatures as a concatenated byte array.
* @param _gasPrice The gas price to use for the gas refund.
* @param _gasLimit The gas limit to use for the gas refund.
*/
function execute(
BaseWallet _wallet,
bytes calldata _data,
uint256 _nonce,
bytes calldata _signatures,
uint256 _gasPrice,
uint256 _gasLimit
)
external
returns (bool success)
{
uint startGas = gasleft();
bytes32 signHash = getSignHash(address(this), address(_wallet), 0, _data, _nonce, _gasPrice, _gasLimit);
require(checkAndUpdateUniqueness(_wallet, _nonce, signHash), "RM: Duplicate request");
require(verifyData(address(_wallet), _data), "RM: the wallet authorized is different then the target of the relayed data");
uint256 requiredSignatures = getRequiredSignatures(_wallet, _data);
if ((requiredSignatures * 65) == _signatures.length) {
if (verifyRefund(_wallet, _gasLimit, _gasPrice, requiredSignatures)) {
if (requiredSignatures == 0 || validateSignatures(_wallet, _data, signHash, _signatures)) {
// solium-disable-next-line security/no-call-value
(success,) = address(this).call(_data);
refund(_wallet, startGas - gasleft(), _gasPrice, _gasLimit, requiredSignatures, msg.sender);
}
}
}
emit TransactionExecuted(address(_wallet), success, signHash);
}
/**
* @dev Gets the current nonce for a wallet.
* @param _wallet The target wallet.
*/
function getNonce(BaseWallet _wallet) external view returns (uint256 nonce) {
return relayer[address(_wallet)].nonce;
}
/**
* @dev Generates the signed hash of a relayed transaction according to ERC 1077.
* @param _from The starting address for the relayed transaction (should be the module)
* @param _to The destination address for the relayed transaction (should be the wallet)
* @param _value The value for the relayed transaction
* @param _data The data for the relayed transaction
* @param _nonce The nonce used to prevent replay attacks.
* @param _gasPrice The gas price to use for the gas refund.
* @param _gasLimit The gas limit to use for the gas refund.
*/
function getSignHash(
address _from,
address _to,
uint256 _value,
bytes memory _data,
uint256 _nonce,
uint256 _gasPrice,
uint256 _gasLimit
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(byte(0x19), byte(0), _from, _to, _value, _data, _nonce, _gasPrice, _gasLimit))
));
}
/**
* @dev Checks if the relayed transaction is unique.
* @param _wallet The target wallet.
* @param _signHash The signed hash of the transaction
*/
function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 /* _nonce */, bytes32 _signHash) internal returns (bool) {
if (relayer[address(_wallet)].executedTx[_signHash] == true) {
return false;
}
relayer[address(_wallet)].executedTx[_signHash] = true;
return true;
}
/**
* @dev Checks that a nonce has the correct format and is valid.
* It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes.
* @param _wallet The target wallet.
* @param _nonce The nonce
*/
function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) {
if (_nonce <= relayer[address(_wallet)].nonce) {
return false;
}
uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128;
if (nonceBlock > block.number + BLOCKBOUND) {
return false;
}
relayer[address(_wallet)].nonce = _nonce;
return true;
}
/**
* @dev Recovers the signer at a given position from a list of concatenated signatures.
* @param _signedHash The signed hash
* @param _signatures The concatenated signatures.
* @param _index The index of the signature to recover.
*/
function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) {
uint8 v;
bytes32 r;
bytes32 s;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(_signatures, add(0x20,mul(0x41,_index))))
s := mload(add(_signatures, add(0x40,mul(0x41,_index))))
v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff)
}
require(v == 27 || v == 28); // solium-disable-line error-reason
return ecrecover(_signedHash, v, r, s);
}
/**
* @dev Refunds the gas used to the Relayer.
* For security reasons the default behavior is to not refund calls with 0 or 1 signatures.
* @param _wallet The target wallet.
* @param _gasUsed The gas used.
* @param _gasPrice The gas price for the refund.
* @param _gasLimit The gas limit for the refund.
* @param _signatures The number of signatures used in the call.
* @param _relayer The address of the Relayer.
*/
function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal {
uint256 amount = 29292 + _gasUsed; // 21000 (transaction) + 7620 (execution of refund) + 672 to log the event + _gasUsed
// only refund if gas price not null, more than 1 signatures, gas less than gasLimit
if (_gasPrice > 0 && _signatures > 1 && amount <= _gasLimit) {
if (_gasPrice > tx.gasprice) {
amount = amount * tx.gasprice;
} else {
amount = amount * _gasPrice;
}
invokeWallet(address(_wallet), _relayer, amount, EMPTY_BYTES);
}
}
/**
* @dev Returns false if the refund is expected to fail.
* @param _wallet The target wallet.
* @param _gasUsed The expected gas used.
* @param _gasPrice The expected gas price for the refund.
*/
function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) {
if (_gasPrice > 0 &&
_signatures > 1 &&
(address(_wallet).balance < _gasUsed * _gasPrice || _wallet.authorised(address(this)) == false)) {
return false;
}
return true;
}
/**
* @dev Checks that the wallet address provided as the first parameter of the relayed data is the same
* as the wallet passed as the input of the execute() method.
@return false if the addresses are different.
*/
function verifyData(address _wallet, bytes memory _data) private pure returns (bool) {
require(_data.length >= 36, "RM: Invalid dataWallet");
address dataWallet;
// solium-disable-next-line security/no-inline-assembly
assembly {
//_data = {length:32}{sig:4}{_wallet:32}{...}
dataWallet := mload(add(_data, 0x24))
}
return dataWallet == _wallet;
}
/**
* @dev Parses the data to extract the method signature.
*/
function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) {
require(_data.length >= 4, "RM: Invalid functionPrefix");
// solium-disable-next-line security/no-inline-assembly
assembly {
prefix := mload(add(_data, 0x20))
}
}
}// 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/>.
/**
* @title OnlyOwnerModule
* @dev Module that extends BaseModule and RelayerModule for modules where the execute() method
* must be called with one signature frm the owner.
* @author Julien Niset - <julien@argent.im>
*/
contract OnlyOwnerModule is BaseModule, RelayerModule {
// bytes4 private constant IS_ONLY_OWNER_MODULE = bytes4(keccak256("isOnlyOwnerModule()"));
/**
* @dev Returns a constant that indicates that the module is an OnlyOwnerModule.
* @return The constant bytes4(keccak256("isOnlyOwnerModule()"))
*/
function isOnlyOwnerModule() external pure returns (bytes4) {
// return IS_ONLY_OWNER_MODULE;
return this.isOnlyOwnerModule.selector;
}
/**
* @dev Adds a module to a wallet. First checks that the module is registered.
* Unlike its overrided parent, this method can be called via the RelayerModule's execute()
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(BaseWallet _wallet, Module _module) external onlyWalletOwner(_wallet) {
require(registry.isRegisteredModule(address(_module)), "BM: module is not registered");
_wallet.authoriseModule(address(_module), true);
}
// *************** Implementation of RelayerModule methods ********************* //
// Overrides to use the incremental nonce and save some gas
function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 /* _signHash */) internal returns (bool) {
return checkAndUpdateNonce(_wallet, _nonce);
}
function validateSignatures(
BaseWallet _wallet,
bytes memory /* _data */,
bytes32 _signHash,
bytes memory _signatures
)
internal
view
returns (bool)
{
address signer = recoverSigner(_signHash, _signatures, 0);
return isOwner(_wallet, signer); // "OOM: signer must be owner"
}
function getRequiredSignatures(BaseWallet /* _wallet */, bytes memory /* _data */) internal view returns (uint256) {
return 1;
}
}// 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/>.
/**
* @title BaseTransfer
* @dev Module containing internal methods to execute or approve transfers
* @author Olivier VDB - <olivier@argent.xyz>
*/
contract BaseTransfer is BaseModule {
// Mock token address for ETH
address constant internal ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// *************** Events *************************** //
event Transfer(address indexed wallet, address indexed token, uint256 indexed amount, address to, bytes data);
event Approved(address indexed wallet, address indexed token, uint256 amount, address spender);
event CalledContract(address indexed wallet, address indexed to, uint256 amount, bytes data);
event ApprovedAndCalledContract(
address indexed wallet,
address indexed to,
address spender,
address indexed token,
uint256 amountApproved,
uint256 amountSpent,
bytes data
);
// *************** Internal Functions ********************* //
/**
* @dev Helper method to transfer ETH or ERC20 for a wallet.
* @param _wallet The target wallet.
* @param _token The ERC20 address.
* @param _to The recipient.
* @param _value The amount of ETH to transfer
* @param _data The data to *log* with the transfer.
*/
function doTransfer(BaseWallet _wallet, address _token, address _to, uint256 _value, bytes memory _data) internal {
if (_token == ETH_TOKEN) {
invokeWallet(address(_wallet), _to, _value, EMPTY_BYTES);
} else {
bytes memory methodData = abi.encodeWithSignature("transfer(address,uint256)", _to, _value);
invokeWallet(address(_wallet), _token, 0, methodData);
}
emit Transfer(address(_wallet), _token, _value, _to, _data);
}
/**
* @dev Helper method to approve spending the ERC20 of a wallet.
* @param _wallet The target wallet.
* @param _token The ERC20 address.
* @param _spender The spender address.
* @param _value The amount of token to transfer.
*/
function doApproveToken(BaseWallet _wallet, address _token, address _spender, uint256 _value) internal {
bytes memory methodData = abi.encodeWithSignature("approve(address,uint256)", _spender, _value);
invokeWallet(address(_wallet), _token, 0, methodData);
emit Approved(address(_wallet), _token, _value, _spender);
}
/**
* @dev Helper method to call an external contract.
* @param _wallet The target wallet.
* @param _contract The contract address.
* @param _value The ETH value to transfer.
* @param _data The method data.
*/
function doCallContract(BaseWallet _wallet, address _contract, uint256 _value, bytes memory _data) internal {
invokeWallet(address(_wallet), _contract, _value, _data);
emit CalledContract(address(_wallet), _contract, _value, _data);
}
/**
* @dev Helper method to approve a certain amount of token and call an external contract.
* The address that spends the _token and the address that is called with _data can be different.
* @param _wallet The target wallet.
* @param _token The ERC20 address.
* @param _spender The spender address.
* @param _amount The amount of tokens to transfer.
* @param _contract The contract address.
* @param _data The method data.
*/
function doApproveTokenAndCallContract(
BaseWallet _wallet,
address _token,
address _spender,
uint256 _amount,
address _contract,
bytes memory _data
)
internal
{
uint256 existingAllowance = ERC20(_token).allowance(address(_wallet), _spender);
uint256 totalAllowance = SafeMath.add(existingAllowance, _amount);
// Approve the desired amount plus existing amount. This logic allows for potential gas saving later
// when restoring the original approved amount, in cases where the _spender uses the exact approved _amount.
bytes memory methodData = abi.encodeWithSignature("approve(address,uint256)", _spender, totalAllowance);
invokeWallet(address(_wallet), _token, 0, methodData);
invokeWallet(address(_wallet), _contract, 0, _data);
// Calculate the approved amount that was spent after the call
uint256 unusedAllowance = ERC20(_token).allowance(address(_wallet), _spender);
uint256 usedAllowance = SafeMath.sub(totalAllowance, unusedAllowance);
// Ensure the amount spent does not exceed the amount approved for this call
require(usedAllowance <= _amount, "BT: insufficient amount for call");
if (unusedAllowance != existingAllowance) {
// Restore the original allowance amount if the amount spent was different (can be lower).
methodData = abi.encodeWithSignature("approve(address,uint256)", _spender, existingAllowance);
invokeWallet(address(_wallet), _token, 0, methodData);
}
emit ApprovedAndCalledContract(
address(_wallet),
_contract,
_spender,
_token,
_amount,
usedAllowance,
_data);
}
}
// 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/>.
/**
* @title LimitManager
* @dev Module to manage a daily spending limit
* @author Julien Niset - <julien@argent.im>
*/
contract LimitManager is BaseModule {
// large limit when the limit can be considered disabled
uint128 constant private LIMIT_DISABLED = uint128(-1); // 3.40282366920938463463374607431768211455e+38
using SafeMath for uint256;
struct LimitManagerConfig {
// The daily limit
Limit limit;
// The current usage
DailySpent dailySpent;
}
struct Limit {
// the current limit
uint128 current;
// the pending limit if any
uint128 pending;
// when the pending limit becomes the current limit
uint64 changeAfter;
}
struct DailySpent {
// The amount already spent during the current period
uint128 alreadySpent;
// The end of the current period
uint64 periodEnd;
}
// wallet specific storage
mapping (address => LimitManagerConfig) internal limits;
// The default limit
uint256 public defaultLimit;
// *************** Events *************************** //
event LimitChanged(address indexed wallet, uint indexed newLimit, uint64 indexed startAfter);
// *************** Constructor ********************** //
constructor(uint256 _defaultLimit) public {
defaultLimit = _defaultLimit;
}
// *************** External/Public Functions ********************* //
/**
* @dev Inits the module for a wallet by setting the limit to the default value.
* @param _wallet The target wallet.
*/
function init(BaseWallet _wallet) public onlyWallet(_wallet) {
Limit storage limit = limits[address(_wallet)].limit;
if (limit.current == 0 && limit.changeAfter == 0) {
limit.current = uint128(defaultLimit);
}
}
// *************** Internal Functions ********************* //
/**
* @dev Changes the daily limit.
* The limit is expressed in ETH and the change is pending for the security period.
* @param _wallet The target wallet.
* @param _newLimit The new limit.
* @param _securityPeriod The security period.
*/
function changeLimit(BaseWallet _wallet, uint256 _newLimit, uint256 _securityPeriod) internal {
Limit storage limit = limits[address(_wallet)].limit;
// solium-disable-next-line security/no-block-members
uint128 current = (limit.changeAfter > 0 && limit.changeAfter < now) ? limit.pending : limit.current;
limit.current = current;
limit.pending = uint128(_newLimit);
// solium-disable-next-line security/no-block-members
limit.changeAfter = uint64(now.add(_securityPeriod));
// solium-disable-next-line security/no-block-members
emit LimitChanged(address(_wallet), _newLimit, uint64(now.add(_securityPeriod)));
}
/**
* @dev Disable the daily limit.
* The change is pending for the security period.
* @param _wallet The target wallet.
* @param _securityPeriod The security period.
*/
function disableLimit(BaseWallet _wallet, uint256 _securityPeriod) internal {
changeLimit(_wallet, LIMIT_DISABLED, _securityPeriod);
}
/**
* @dev Gets the current daily limit for a wallet.
* @param _wallet The target wallet.
* @return the current limit expressed in ETH.
*/
function getCurrentLimit(BaseWallet _wallet) public view returns (uint256 _currentLimit) {
Limit storage limit = limits[address(_wallet)].limit;
_currentLimit = uint256(currentLimit(limit.current, limit.pending, limit.changeAfter));
}
/**
* @dev Returns whether the daily limit is disabled for a wallet.
* @param _wallet The target wallet.
* @return true if the daily limit is disabled, false otherwise.
*/
function isLimitDisabled(BaseWallet _wallet) public view returns (bool _limitDisabled) {
uint256 currentLimit = getCurrentLimit(_wallet);
_limitDisabled = currentLimit == LIMIT_DISABLED;
}
/**
* @dev Gets a pending limit for a wallet if any.
* @param _wallet The target wallet.
* @return the pending limit (in ETH) and the time at chich it will become effective.
*/
function getPendingLimit(BaseWallet _wallet) external view returns (uint256 _pendingLimit, uint64 _changeAfter) {
Limit storage limit = limits[address(_wallet)].limit;
// solium-disable-next-line security/no-block-members
return ((now < limit.changeAfter)? (uint256(limit.pending), limit.changeAfter) : (0,0));
}
/**
* @dev Gets the amount of tokens that has not yet been spent during the current period.
* @param _wallet The target wallet.
* @return the amount of tokens (in ETH) that has not been spent yet and the end of the period.
*/
function getDailyUnspent(BaseWallet _wallet) external view returns (uint256 _unspent, uint64 _periodEnd) {
uint256 limit = getCurrentLimit(_wallet);
DailySpent storage expense = limits[address(_wallet)].dailySpent;
// solium-disable-next-line security/no-block-members
if (now > expense.periodEnd) {
_unspent = limit;
// solium-disable-next-line security/no-block-members
_periodEnd = uint64(now + 24 hours);
} else {
_periodEnd = expense.periodEnd;
if (expense.alreadySpent < limit) {
_unspent = limit - expense.alreadySpent;
}
}
}
/**
* @dev Helper method to check if a transfer is within the limit.
* If yes the daily unspent for the current period is updated.
* @param _wallet The target wallet.
* @param _amount The amount for the transfer
*/
function checkAndUpdateDailySpent(BaseWallet _wallet, uint _amount) internal returns (bool) {
if (_amount == 0)
return true;
Limit storage limit = limits[address(_wallet)].limit;
uint128 current = currentLimit(limit.current, limit.pending, limit.changeAfter);
if (isWithinDailyLimit(_wallet, current, _amount)) {
updateDailySpent(_wallet, current, _amount);
return true;
}
return false;
}
/**
* @dev Helper method to update the daily spent for the current period.
* @param _wallet The target wallet.
* @param _limit The current limit for the wallet.
* @param _amount The amount to add to the daily spent.
*/
function updateDailySpent(BaseWallet _wallet, uint128 _limit, uint _amount) internal {
if (_limit != LIMIT_DISABLED) {
DailySpent storage expense = limits[address(_wallet)].dailySpent;
// solium-disable-next-line security/no-block-members
if (expense.periodEnd < now) {
// solium-disable-next-line security/no-block-members
expense.periodEnd = uint64(now + 24 hours);
expense.alreadySpent = uint128(_amount);
} else {
expense.alreadySpent += uint128(_amount);
}
}
}
/**
* @dev Checks if a transfer amount is withing the daily limit for a wallet.
* @param _wallet The target wallet.
* @param _limit The current limit for the wallet.
* @param _amount The transfer amount.
* @return true if the transfer amount is withing the daily limit.
*/
function isWithinDailyLimit(BaseWallet _wallet, uint _limit, uint _amount) internal view returns (bool) {
if (_limit == LIMIT_DISABLED) {
return true;
}
DailySpent storage expense = limits[address(_wallet)].dailySpent;
// solium-disable-next-line security/no-block-members
if (expense.periodEnd < now) {
return (_amount <= _limit);
} else {
return (expense.alreadySpent + _amount <= _limit && expense.alreadySpent + _amount >= expense.alreadySpent);
}
}
/**
* @dev Helper method to get the current limit from a Limit struct.
* @param _current The value of the current parameter
* @param _pending The value of the pending parameter
* @param _changeAfter The value of the changeAfter parameter
*/
function currentLimit(uint128 _current, uint128 _pending, uint64 _changeAfter) internal view returns (uint128) {
// solium-disable-next-line security/no-block-members
if (_changeAfter > 0 && _changeAfter < now) {
return _pending;
}
return _current;
}
}// 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/>.
/**
* @title TransferStorage
* @dev Contract storing the state of wallets related to transfers (limit and whitelist).
* The contract only defines basic setters and getters with no logic. Only modules authorised
* for a wallet can modify its state.
* @author Julien Niset - <julien@argent.im>
*/
contract TransferStorage is Storage {
// wallet specific storage
mapping (address => mapping (address => uint256)) internal whitelist;
// *************** External Functions ********************* //
/**
* @dev Lets an authorised module add or remove an account from the whitelist of a wallet.
* @param _wallet The target wallet.
* @param _target The account to add/remove.
* @param _value True for addition, false for revokation.
*/
function setWhitelist(BaseWallet _wallet, address _target, uint256 _value) external onlyModule(_wallet) {
whitelist[address(_wallet)][_target] = _value;
}
/**
* @dev Gets the whitelist state of an account for a wallet.
* @param _wallet The target wallet.
* @param _target The account.
* @return the epoch time at which an account strats to be whitelisted, or zero if the account is not whitelisted.
*/
function getWhitelist(BaseWallet _wallet, address _target) external view returns (uint256) {
return whitelist[address(_wallet)][_target];
}
}// 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/>.
/**
* @title Managed
* @dev Basic contract that defines a set of managers. Only the owner can add/remove managers.
* @author Julien Niset - <julien@argent.im>
*/
contract Managed is Owned {
// The managers
mapping (address => bool) public managers;
/**
* @dev Throws if the sender is not a manager.
*/
modifier onlyManager {
require(managers[msg.sender] == true, "M: Must be manager");
_;
}
event ManagerAdded(address indexed _manager);
event ManagerRevoked(address indexed _manager);
/**
* @dev Adds a manager.
* @param _manager The address of the manager.
*/
function addManager(address _manager) external onlyOwner {
require(_manager != address(0), "M: Address must not be null");
if (managers[_manager] == false) {
managers[_manager] = true;
emit ManagerAdded(_manager);
}
}
/**
* @dev Revokes a manager.
* @param _manager The address of the manager.
*/
function revokeManager(address _manager) external onlyOwner {
require(managers[_manager] == true, "M: Target must be an existing manager");
delete managers[_manager];
emit ManagerRevoked(_manager);
}
}
contract KyberNetwork {
function getExpectedRate(
ERC20 src,
ERC20 dest,
uint srcQty
)
public
view
returns (uint expectedRate, uint slippageRate);
function trade(
ERC20 src,
uint srcAmount,
ERC20 dest,
address payable destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint);
}
// 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/>.
contract TokenPriceProvider is Managed {
// Mock token address for ETH
address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
using SafeMath for uint256;
mapping(address => uint256) public cachedPrices;
// Address of the KyberNetwork contract
KyberNetwork public kyberNetwork;
constructor(KyberNetwork _kyberNetwork) public {
kyberNetwork = _kyberNetwork;
}
function setPrice(ERC20 _token, uint256 _price) public onlyManager {
cachedPrices[address(_token)] = _price;
}
function setPriceForTokenList(ERC20[] calldata _tokens, uint256[] calldata _prices) external onlyManager {
for (uint16 i = 0; i < _tokens.length; i++) {
setPrice(_tokens[i], _prices[i]);
}
}
/**
* @dev Converts the value of _amount tokens in ether.
* @param _amount the amount of tokens to convert (in 'token wei' twei)
* @param _token the ERC20 token contract
* @return the ether value (in wei) of _amount tokens with contract _token
*/
function getEtherValue(uint256 _amount, address _token) external view returns (uint256) {
uint256 decimals = ERC20(_token).decimals();
uint256 price = cachedPrices[_token];
return price.mul(_amount).div(10**decimals);
}
//
// The following is added to be backward-compatible with Argent's old backend
//
function setKyberNetwork(KyberNetwork _kyberNetwork) external onlyManager {
kyberNetwork = _kyberNetwork;
}
function syncPrice(ERC20 _token) external {
require(address(kyberNetwork) != address(0), "Kyber sync is disabled");
(uint256 expectedRate,) = kyberNetwork.getExpectedRate(_token, ERC20(ETH_TOKEN_ADDRESS), 10000);
cachedPrices[address(_token)] = expectedRate;
}
function syncPriceForTokenList(ERC20[] calldata _tokens) external {
require(address(kyberNetwork) != address(0), "Kyber sync is disabled");
for (uint16 i = 0; i < _tokens.length; i++) {
(uint256 expectedRate,) = kyberNetwork.getExpectedRate(_tokens[i], ERC20(ETH_TOKEN_ADDRESS), 10000);
cachedPrices[address(_tokens[i])] = expectedRate;
}
}
}// 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/>.
/**
* @title TransferManager
* @dev Module to transfer and approve tokens (ETH or ERC20) or data (contract call) based on a security context (daily limit, whitelist, etc).
* This module is the V2 of TokenTransfer.
* @author Julien Niset - <julien@argent.xyz>
*/
contract TransferManager is BaseModule, RelayerModule, OnlyOwnerModule, BaseTransfer, LimitManager {
bytes32 constant NAME = "TransferManager";
bytes4 private constant ERC1271_ISVALIDSIGNATURE_BYTES = bytes4(keccak256("isValidSignature(bytes,bytes)"));
bytes4 private constant ERC1271_ISVALIDSIGNATURE_BYTES32 = bytes4(keccak256("isValidSignature(bytes32,bytes)"));
enum ActionType { Transfer }
using SafeMath for uint256;
struct TokenManagerConfig {
// Mapping between pending action hash and their timestamp
mapping (bytes32 => uint256) pendingActions;
}
// wallet specific storage
mapping (address => TokenManagerConfig) internal configs;
// The security period
uint256 public securityPeriod;
// The execution window
uint256 public securityWindow;
// The Token storage
TransferStorage public transferStorage;
// The Token price provider
TokenPriceProvider public priceProvider;
// The previous limit manager needed to migrate the limits
LimitManager public oldLimitManager;
// *************** Events *************************** //
event AddedToWhitelist(address indexed wallet, address indexed target, uint64 whitelistAfter);
event RemovedFromWhitelist(address indexed wallet, address indexed target);
event PendingTransferCreated(address indexed wallet, bytes32 indexed id, uint256 indexed executeAfter,
address token, address to, uint256 amount, bytes data);
event PendingTransferExecuted(address indexed wallet, bytes32 indexed id);
event PendingTransferCanceled(address indexed wallet, bytes32 indexed id);
// *************** Constructor ********************** //
constructor(
ModuleRegistry _registry,
TransferStorage _transferStorage,
GuardianStorage _guardianStorage,
address _priceProvider,
uint256 _securityPeriod,
uint256 _securityWindow,
uint256 _defaultLimit,
LimitManager _oldLimitManager
)
BaseModule(_registry, _guardianStorage, NAME)
LimitManager(_defaultLimit)
public
{
transferStorage = _transferStorage;
priceProvider = TokenPriceProvider(_priceProvider);
securityPeriod = _securityPeriod;
securityWindow = _securityWindow;
oldLimitManager = _oldLimitManager;
}
/**
* @dev Inits the module for a wallet by setting up the isValidSignature (EIP 1271)
* static call redirection from the wallet to the module and copying all the parameters
* of the daily limit from the previous implementation of the LimitManager module.
* @param _wallet The target wallet.
*/
function init(BaseWallet _wallet) public onlyWallet(_wallet) {
// setup static calls
_wallet.enableStaticCall(address(this), ERC1271_ISVALIDSIGNATURE_BYTES);
_wallet.enableStaticCall(address(this), ERC1271_ISVALIDSIGNATURE_BYTES32);
// setup default limit for new deployment
if (address(oldLimitManager) == address(0)) {
super.init(_wallet);
return;
}
// get limit from previous LimitManager
uint256 current = oldLimitManager.getCurrentLimit(_wallet);
(uint256 pending, uint64 changeAfter) = oldLimitManager.getPendingLimit(_wallet);
// setup default limit for new wallets
if (current == 0 && changeAfter == 0) {
super.init(_wallet);
return;
}
// migrate existing limit for existing wallets
if (current == pending) {
limits[address(_wallet)].limit.current = uint128(current);
} else {
limits[address(_wallet)].limit = Limit(uint128(current), uint128(pending), changeAfter);
}
// migrate daily pending if we are within a rolling period
(uint256 unspent, uint64 periodEnd) = oldLimitManager.getDailyUnspent(_wallet);
// solium-disable-next-line security/no-block-members
if (periodEnd > now) {
limits[address(_wallet)].dailySpent = DailySpent(uint128(current.sub(unspent)), periodEnd);
}
}
// *************** External/Public Functions ********************* //
/**
* @dev lets the owner transfer tokens (ETH or ERC20) from a wallet.
* @param _wallet The target wallet.
* @param _token The address of the token to transfer.
* @param _to The destination address
* @param _amount The amoutn of token to transfer
* @param _data The data for the transaction
*/
function transferToken(
BaseWallet _wallet,
address _token,
address _to,
uint256 _amount,
bytes calldata _data
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
if (isWhitelisted(_wallet, _to)) {
// transfer to whitelist
doTransfer(_wallet, _token, _to, _amount, _data);
} else {
uint256 etherAmount = (_token == ETH_TOKEN) ? _amount : priceProvider.getEtherValue(_amount, _token);
if (checkAndUpdateDailySpent(_wallet, etherAmount)) {
// transfer under the limit
doTransfer(_wallet, _token, _to, _amount, _data);
} else {
// transfer above the limit
(bytes32 id, uint256 executeAfter) = addPendingAction(ActionType.Transfer, _wallet, _token, _to, _amount, _data);
emit PendingTransferCreated(address(_wallet), id, executeAfter, _token, _to, _amount, _data);
}
}
}
/**
* @dev lets the owner approve an allowance of ERC20 tokens for a spender (dApp).
* @param _wallet The target wallet.
* @param _token The address of the token to transfer.
* @param _spender The address of the spender
* @param _amount The amount of tokens to approve
*/
function approveToken(
BaseWallet _wallet,
address _token,
address _spender,
uint256 _amount
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
if (isWhitelisted(_wallet, _spender)) {
// approve to whitelist
doApproveToken(_wallet, _token, _spender, _amount);
} else {
// get current alowance
uint256 currentAllowance = ERC20(_token).allowance(address(_wallet), _spender);
if (_amount <= currentAllowance) {
// approve if we reduce the allowance
doApproveToken(_wallet, _token, _spender, _amount);
} else {
// check if delta is under the limit
uint delta = _amount - currentAllowance;
uint256 deltaInEth = priceProvider.getEtherValue(delta, _token);
require(checkAndUpdateDailySpent(_wallet, deltaInEth), "TM: Approve above daily limit");
// approve if under the limit
doApproveToken(_wallet, _token, _spender, _amount);
}
}
}
/**
* @dev lets the owner call a contract.
* @param _wallet The target wallet.
* @param _contract The address of the contract.
* @param _value The amount of ETH to transfer as part of call
* @param _data The encoded method data
*/
function callContract(
BaseWallet _wallet,
address _contract,
uint256 _value,
bytes calldata _data
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
// Make sure we don't call a module, the wallet itself, or a supported ERC20
authoriseContractCall(_wallet, _contract);
if (isWhitelisted(_wallet, _contract)) {
// call to whitelist
doCallContract(_wallet, _contract, _value, _data);
} else {
require(checkAndUpdateDailySpent(_wallet, _value), "TM: Call contract above daily limit");
// call under the limit
doCallContract(_wallet, _contract, _value, _data);
}
}
/**
* @dev lets the owner do an ERC20 approve followed by a call to a contract.
* We assume that the contract will pull the tokens and does not require ETH.
* @param _wallet The target wallet.
* @param _token The token to approve.
* @param _spender The address to approve.
* @param _amount The amount of ERC20 tokens to approve.
* @param _contract The address of the contract.
* @param _data The encoded method data
*/
function approveTokenAndCallContract(
BaseWallet _wallet,
address _token,
address _spender,
uint256 _amount,
address _contract,
bytes calldata _data
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
// Make sure we don't call a module, the wallet itself, or a supported ERC20
authoriseContractCall(_wallet, _contract);
if (!isWhitelisted(_wallet, _spender)) {
// check if the amount is under the daily limit
// check the entire amount because the currently approved amount will be restored and should still count towards the daily limit
uint256 valueInEth = priceProvider.getEtherValue(_amount, _token);
require(checkAndUpdateDailySpent(_wallet, valueInEth), "TM: Approve above daily limit");
}
doApproveTokenAndCallContract(_wallet, _token, _spender, _amount, _contract, _data);
}
/**
* @dev Adds an address to the whitelist of a wallet.
* @param _wallet The target wallet.
* @param _target The address to add.
*/
function addToWhitelist(
BaseWallet _wallet,
address _target
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
require(!isWhitelisted(_wallet, _target), "TT: target already whitelisted");
// solium-disable-next-line security/no-block-members
uint256 whitelistAfter = now.add(securityPeriod);
transferStorage.setWhitelist(_wallet, _target, whitelistAfter);
emit AddedToWhitelist(address(_wallet), _target, uint64(whitelistAfter));
}
/**
* @dev Removes an address from the whitelist of a wallet.
* @param _wallet The target wallet.
* @param _target The address to remove.
*/
function removeFromWhitelist(
BaseWallet _wallet,
address _target
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
require(isWhitelisted(_wallet, _target), "TT: target not whitelisted");
transferStorage.setWhitelist(_wallet, _target, 0);
emit RemovedFromWhitelist(address(_wallet), _target);
}
/**
* @dev Executes a pending transfer for a wallet.
* The method can be called by anyone to enable orchestration.
* @param _wallet The target wallet.
* @param _token The token of the pending transfer.
* @param _to The destination address of the pending transfer.
* @param _amount The amount of token to transfer of the pending transfer.
* @param _data The data associated to the pending transfer.
* @param _block The block at which the pending transfer was created.
*/
function executePendingTransfer(
BaseWallet _wallet,
address _token,
address _to,
uint _amount,
bytes calldata _data,
uint _block
)
external
onlyWhenUnlocked(_wallet)
{
bytes32 id = keccak256(abi.encodePacked(ActionType.Transfer, _token, _to, _amount, _data, _block));
uint executeAfter = configs[address(_wallet)].pendingActions[id];
require(executeAfter > 0, "TT: unknown pending transfer");
uint executeBefore = executeAfter.add(securityWindow);
// solium-disable-next-line security/no-block-members
require(executeAfter <= now && now <= executeBefore, "TT: transfer outside of the execution window");
delete configs[address(_wallet)].pendingActions[id];
doTransfer(_wallet, _token, _to, _amount, _data);
emit PendingTransferExecuted(address(_wallet), id);
}
function cancelPendingTransfer(
BaseWallet _wallet,
bytes32 _id
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
require(configs[address(_wallet)].pendingActions[_id] > 0, "TT: unknown pending action");
delete configs[address(_wallet)].pendingActions[_id];
emit PendingTransferCanceled(address(_wallet), _id);
}
/**
* @dev Lets the owner of a wallet change its daily limit.
* The limit is expressed in ETH. Changes to the limit take 24 hours.
* @param _wallet The target wallet.
* @param _newLimit The new limit.
*/
function changeLimit(BaseWallet _wallet, uint256 _newLimit) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) {
changeLimit(_wallet, _newLimit, securityPeriod);
}
/**
* @dev Convenience method to disable the limit
* The limit is disabled by setting it to an arbitrary large value.
* @param _wallet The target wallet.
*/
function disableLimit(BaseWallet _wallet) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) {
disableLimit(_wallet, securityPeriod);
}
/**
* @dev Checks if an address is whitelisted for a wallet.
* @param _wallet The target wallet.
* @param _target The address.
* @return true if the address is whitelisted.
*/
function isWhitelisted(BaseWallet _wallet, address _target) public view returns (bool _isWhitelisted) {
uint whitelistAfter = transferStorage.getWhitelist(_wallet, _target);
// solium-disable-next-line security/no-block-members
return whitelistAfter > 0 && whitelistAfter < now;
}
/**
* @dev Gets the info of a pending transfer for a wallet.
* @param _wallet The target wallet.
* @param _id The pending transfer ID.
* @return the epoch time at which the pending transfer can be executed.
*/
function getPendingTransfer(BaseWallet _wallet, bytes32 _id) external view returns (uint64 _executeAfter) {
_executeAfter = uint64(configs[address(_wallet)].pendingActions[_id]);
}
/**
* @dev Implementation of EIP 1271.
* Should return whether the signature provided is valid for the provided data.
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
*/
function isValidSignature(bytes calldata _data, bytes calldata _signature) external view returns (bytes4) {
bytes32 msgHash = keccak256(abi.encodePacked(_data));
isValidSignature(msgHash, _signature);
return ERC1271_ISVALIDSIGNATURE_BYTES;
}
/**
* @dev Implementation of EIP 1271.
* Should return whether the signature provided is valid for the provided data.
* @param _msgHash Hash of a message signed on the behalf of address(this)
* @param _signature Signature byte array associated with _msgHash
*/
function isValidSignature(bytes32 _msgHash, bytes memory _signature) public view returns (bytes4) {
require(_signature.length == 65, "TM: invalid signature length");
address signer = recoverSigner(_msgHash, _signature, 0);
require(isOwner(BaseWallet(msg.sender), signer), "TM: Invalid signer");
return ERC1271_ISVALIDSIGNATURE_BYTES32;
}
// *************** Internal Functions ********************* //
/**
* @dev Creates a new pending action for a wallet.
* @param _action The target action.
* @param _wallet The target wallet.
* @param _token The target token for the action.
* @param _to The recipient of the action.
* @param _amount The amount of token associated to the action.
* @param _data The data associated to the action.
* @return the identifier for the new pending action and the time when the action can be executed
*/
function addPendingAction(
ActionType _action,
BaseWallet _wallet,
address _token,
address _to,
uint _amount,
bytes memory _data
)
internal
returns (bytes32 id, uint256 executeAfter)
{
id = keccak256(abi.encodePacked(_action, _token, _to, _amount, _data, block.number));
require(configs[address(_wallet)].pendingActions[id] == 0, "TM: duplicate pending action");
// solium-disable-next-line security/no-block-members
executeAfter = now.add(securityPeriod);
configs[address(_wallet)].pendingActions[id] = executeAfter;
}
/**
* @dev Make sure a contract call is not trying to call a module, the wallet itself, or a supported ERC20.
* @param _wallet The target wallet.
* @param _contract The address of the contract.
*/
function authoriseContractCall(BaseWallet _wallet, address _contract) internal view {
require(
_contract != address(_wallet) && // not the wallet itself
!_wallet.authorised(_contract) && // not an authorised module
(priceProvider.cachedPrices(_contract) == 0 || isLimitDisabled(_wallet)), // not an ERC20 listed in the provider (or limit disabled)
"TM: Forbidden contract");
}
// *************** Implementation of RelayerModule methods ********************* //
// Overrides refund to add the refund in the daily limit.
function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal {
// 21000 (transaction) + 7620 (execution of refund) + 7324 (execution of updateDailySpent) + 672 to log the event + _gasUsed
uint256 amount = 36616 + _gasUsed;
if (_gasPrice > 0 && _signatures > 0 && amount <= _gasLimit) {
if (_gasPrice > tx.gasprice) {
amount = amount * tx.gasprice;
} else {
amount = amount * _gasPrice;
}
checkAndUpdateDailySpent(_wallet, amount);
invokeWallet(address(_wallet), _relayer, amount, EMPTY_BYTES);
}
}
// Overrides verifyRefund to add the refund in the daily limit.
function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) {
if (_gasPrice > 0 && _signatures > 0 && (
address(_wallet).balance < _gasUsed * _gasPrice ||
isWithinDailyLimit(_wallet, getCurrentLimit(_wallet), _gasUsed * _gasPrice) == false ||
_wallet.authorised(address(this)) == false
))
{
return false;
}
return true;
}
}File 2 of 10: Dai
// hevm: flattened sources of /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol
pragma solidity =0.5.12;
////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/lib.sol
// 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.5.12; */
contract LibNote {
event LogNote(
bytes4 indexed sig,
address indexed usr,
bytes32 indexed arg1,
bytes32 indexed arg2,
bytes data
) anonymous;
modifier note {
_;
assembly {
// log an 'anonymous' event with a constant 6 words of calldata
// and four indexed topics: selector, caller, arg1 and arg2
let mark := msize // end of memory ensures zero
mstore(0x40, add(mark, 288)) // update free memory pointer
mstore(mark, 0x20) // bytes type data offset
mstore(add(mark, 0x20), 224) // bytes size (padded)
calldatacopy(add(mark, 0x40), 0, 224) // bytes payload
log4(mark, 288, // calldata
shl(224, shr(224, calldataload(0))), // msg.sig
caller, // msg.sender
calldataload(4), // arg1
calldataload(36) // arg2
)
}
}
}
////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol
// Copyright (C) 2017, 2018, 2019 dbrock, rain, mrchico
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity 0.5.12; */
/* import "./lib.sol"; */
contract Dai is LibNote {
// --- Auth ---
mapping (address => uint) public wards;
function rely(address guy) external note auth { wards[guy] = 1; }
function deny(address guy) external note auth { wards[guy] = 0; }
modifier auth {
require(wards[msg.sender] == 1, "Dai/not-authorized");
_;
}
// --- ERC20 Data ---
string public constant name = "Dai Stablecoin";
string public constant symbol = "DAI";
string public constant version = "1";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
mapping (address => uint) public nonces;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
// --- Math ---
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
constructor(uint256 chainId_) public {
wards[msg.sender] = 1;
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId_,
address(this)
));
}
// --- Token ---
function transfer(address dst, uint wad) external returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public returns (bool)
{
require(balanceOf[src] >= wad, "Dai/insufficient-balance");
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad, "Dai/insufficient-allowance");
allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad);
}
balanceOf[src] = sub(balanceOf[src], wad);
balanceOf[dst] = add(balanceOf[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function mint(address usr, uint wad) external auth {
balanceOf[usr] = add(balanceOf[usr], wad);
totalSupply = add(totalSupply, wad);
emit Transfer(address(0), usr, wad);
}
function burn(address usr, uint wad) external {
require(balanceOf[usr] >= wad, "Dai/insufficient-balance");
if (usr != msg.sender && allowance[usr][msg.sender] != uint(-1)) {
require(allowance[usr][msg.sender] >= wad, "Dai/insufficient-allowance");
allowance[usr][msg.sender] = sub(allowance[usr][msg.sender], wad);
}
balanceOf[usr] = sub(balanceOf[usr], wad);
totalSupply = sub(totalSupply, wad);
emit Transfer(usr, address(0), wad);
}
function approve(address usr, uint wad) external returns (bool) {
allowance[msg.sender][usr] = wad;
emit Approval(msg.sender, usr, wad);
return true;
}
// --- Alias ---
function push(address usr, uint wad) external {
transferFrom(msg.sender, usr, wad);
}
function pull(address usr, uint wad) external {
transferFrom(usr, msg.sender, wad);
}
function move(address src, address dst, uint wad) external {
transferFrom(src, dst, wad);
}
// --- Approve by signature ---
function permit(address holder, address spender, uint256 nonce, uint256 expiry,
bool allowed, uint8 v, bytes32 r, bytes32 s) external
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed))
));
require(holder != address(0), "Dai/invalid-address-0");
require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit");
require(expiry == 0 || now <= expiry, "Dai/permit-expired");
require(nonce == nonces[holder]++, "Dai/invalid-nonce");
uint wad = allowed ? uint(-1) : 0;
allowance[holder][spender] = wad;
emit Approval(holder, spender, wad);
}
}File 3 of 10: InstaEvent
pragma solidity ^0.6.0;
interface ListInterface {
function accountID(address) external view returns (uint64);
}
contract InstaEvent {
address public constant instaList = 0x4c8a1BEb8a87765788946D6B19C6C6355194AbEb;
event LogEvent(uint64 connectorType, uint64 indexed connectorID, uint64 indexed accountID, bytes32 indexed eventCode, bytes eventData);
function emitEvent(uint _connectorType, uint _connectorID, bytes32 _eventCode, bytes calldata _eventData) external {
uint64 _ID = ListInterface(instaList).accountID(msg.sender);
require(_ID != 0, "not-SA");
emit LogEvent(uint64(_connectorType), uint64(_connectorID), _ID, _eventCode, _eventData);
}
}File 4 of 10: BaseWallet
// 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/>.
pragma solidity ^0.5.4;
/**
* @title Module
* @dev Interface for a module.
* A module MUST implement the addModule() method to ensure that a wallet with at least one module
* can never end up in a "frozen" state.
* @author Julien Niset - <julien@argent.xyz>
*/
interface Module {
/**
* @dev Inits a module for a wallet by e.g. setting some wallet specific parameters in storage.
* @param _wallet The wallet.
*/
function init(BaseWallet _wallet) external;
/**
* @dev Adds a module to a wallet.
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(BaseWallet _wallet, Module _module) external;
/**
* @dev Utility method to recover any ERC20 token that was sent to the
* module by mistake.
* @param _token The token to recover.
*/
function recoverToken(address _token) external;
}
/**
* @title BaseWallet
* @dev Simple modular wallet that authorises modules to call its invoke() method.
* @author Julien Niset - <julien@argent.xyz>
*/
contract BaseWallet {
// The implementation of the proxy
address public implementation;
// The owner
address public owner;
// The authorised modules
mapping (address => bool) public authorised;
// The enabled static calls
mapping (bytes4 => address) public enabled;
// The number of modules
uint public modules;
event AuthorisedModule(address indexed module, bool value);
event EnabledStaticCall(address indexed module, bytes4 indexed method);
event Invoked(address indexed module, address indexed target, uint indexed value, bytes data);
event Received(uint indexed value, address indexed sender, bytes data);
event OwnerChanged(address owner);
/**
* @dev Throws if the sender is not an authorised module.
*/
modifier moduleOnly {
require(authorised[msg.sender], "BW: msg.sender not an authorized module");
_;
}
/**
* @dev Inits the wallet by setting the owner and authorising a list of modules.
* @param _owner The owner.
* @param _modules The modules to authorise.
*/
function init(address _owner, address[] calldata _modules) external {
require(owner == address(0) && modules == 0, "BW: wallet already initialised");
require(_modules.length > 0, "BW: construction requires at least 1 module");
owner = _owner;
modules = _modules.length;
for (uint256 i = 0; i < _modules.length; i++) {
require(authorised[_modules[i]] == false, "BW: module is already added");
authorised[_modules[i]] = true;
Module(_modules[i]).init(this);
emit AuthorisedModule(_modules[i], true);
}
if (address(this).balance > 0) {
emit Received(address(this).balance, address(0), "");
}
}
/**
* @dev Enables/Disables a module.
* @param _module The target module.
* @param _value Set to true to authorise the module.
*/
function authoriseModule(address _module, bool _value) external moduleOnly {
if (authorised[_module] != _value) {
emit AuthorisedModule(_module, _value);
if (_value == true) {
modules += 1;
authorised[_module] = true;
Module(_module).init(this);
} else {
modules -= 1;
require(modules > 0, "BW: wallet must have at least one module");
delete authorised[_module];
}
}
}
/**
* @dev Enables a static method by specifying the target module to which the call
* must be delegated.
* @param _module The target module.
* @param _method The static method signature.
*/
function enableStaticCall(address _module, bytes4 _method) external moduleOnly {
require(authorised[_module], "BW: must be an authorised module for static call");
enabled[_method] = _module;
emit EnabledStaticCall(_module, _method);
}
/**
* @dev Sets a new owner for the wallet.
* @param _newOwner The new owner.
*/
function setOwner(address _newOwner) external moduleOnly {
require(_newOwner != address(0), "BW: address cannot be null");
owner = _newOwner;
emit OwnerChanged(_newOwner);
}
/**
* @dev Performs a generic transaction.
* @param _target The address for the transaction.
* @param _value The value of the transaction.
* @param _data The data of the transaction.
*/
function invoke(address _target, uint _value, bytes calldata _data) external moduleOnly returns (bytes memory _result) {
bool success;
// solium-disable-next-line security/no-call-value
(success, _result) = _target.call.value(_value)(_data);
if (!success) {
// solium-disable-next-line security/no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
emit Invoked(msg.sender, _target, _value, _data);
}
/**
* @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to
* implement specific static methods. It delegates the static call to a target contract if the data corresponds
* to an enabled method, or logs the call otherwise.
*/
function() external payable {
if (msg.data.length > 0) {
address module = enabled[msg.sig];
if (module == address(0)) {
emit Received(msg.value, msg.sender, msg.data);
} else {
require(authorised[module], "BW: must be an authorised module for static call");
// solium-disable-next-line security/no-inline-assembly
assembly {
calldatacopy(0, 0, calldatasize())
let result := staticcall(gas, module, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
}
}File 5 of 10: TokenPriceProvider
pragma solidity ^0.5.4;
/**
* ERC20 contract interface.
*/
contract ERC20 {
function totalSupply() public view returns (uint);
function decimals() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
}
contract KyberNetwork {
function getExpectedRate(
ERC20 src,
ERC20 dest,
uint srcQty
)
public
view
returns (uint expectedRate, uint slippageRate);
function trade(
ERC20 src,
uint srcAmount,
ERC20 dest,
address payable destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
/**
* @dev Returns ceil(a / b).
*/
function ceil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
if(a % b == 0) {
return c;
}
else {
return c + 1;
}
}
}
/**
* @title Owned
* @dev Basic contract to define an owner.
* @author Julien Niset - <julien@argent.im>
*/
contract Owned {
// The owner
address public owner;
event OwnerChanged(address indexed _newOwner);
/**
* @dev Throws if the sender is not the owner.
*/
modifier onlyOwner {
require(msg.sender == owner, "Must be owner");
_;
}
constructor() public {
owner = msg.sender;
}
/**
* @dev Lets the owner transfer ownership of the contract to a new owner.
* @param _newOwner The new owner.
*/
function changeOwner(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "Address must not be null");
owner = _newOwner;
emit OwnerChanged(_newOwner);
}
}
/**
* @title Managed
* @dev Basic contract that defines a set of managers. Only the owner can add/remove managers.
* @author Julien Niset - <julien@argent.im>
*/
contract Managed is Owned {
// The managers
mapping (address => bool) public managers;
/**
* @dev Throws if the sender is not a manager.
*/
modifier onlyManager {
require(managers[msg.sender] == true, "M: Must be manager");
_;
}
event ManagerAdded(address indexed _manager);
event ManagerRevoked(address indexed _manager);
/**
* @dev Adds a manager.
* @param _manager The address of the manager.
*/
function addManager(address _manager) external onlyOwner {
require(_manager != address(0), "M: Address must not be null");
if(managers[_manager] == false) {
managers[_manager] = true;
emit ManagerAdded(_manager);
}
}
/**
* @dev Revokes a manager.
* @param _manager The address of the manager.
*/
function revokeManager(address _manager) external onlyOwner {
require(managers[_manager] == true, "M: Target must be an existing manager");
delete managers[_manager];
emit ManagerRevoked(_manager);
}
}
contract TokenPriceProvider is Managed {
// Mock token address for ETH
address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
using SafeMath for uint256;
mapping(address => uint256) public cachedPrices;
// Address of the KyberNetwork contract
KyberNetwork public kyberNetwork;
constructor(KyberNetwork _kyberNetwork) public {
kyberNetwork = _kyberNetwork;
}
function setPrice(ERC20 _token, uint256 _price) public onlyManager {
cachedPrices[address(_token)] = _price;
}
function setPriceForTokenList(ERC20[] calldata _tokens, uint256[] calldata _prices) external onlyManager {
for(uint16 i = 0; i < _tokens.length; i++) {
setPrice(_tokens[i], _prices[i]);
}
}
/**
* @dev Converts the value of _amount tokens in ether.
* @param _amount the amount of tokens to convert (in 'token wei' twei)
* @param _token the ERC20 token contract
* @return the ether value (in wei) of _amount tokens with contract _token
*/
function getEtherValue(uint256 _amount, address _token) external view returns (uint256) {
uint256 decimals = ERC20(_token).decimals();
uint256 price = cachedPrices[_token];
return price.mul(_amount).div(10**decimals);
}
//
// The following is added to be backward-compatible with Argent's old backend
//
function setKyberNetwork(KyberNetwork _kyberNetwork) external onlyManager {
kyberNetwork = _kyberNetwork;
}
function syncPrice(ERC20 _token) external {
require(address(kyberNetwork) != address(0), "Kyber sync is disabled");
(uint256 expectedRate,) = kyberNetwork.getExpectedRate(_token, ERC20(ETH_TOKEN_ADDRESS), 10000);
cachedPrices[address(_token)] = expectedRate;
}
function syncPriceForTokenList(ERC20[] calldata _tokens) external {
require(address(kyberNetwork) != address(0), "Kyber sync is disabled");
for(uint16 i = 0; i < _tokens.length; i++) {
(uint256 expectedRate,) = kyberNetwork.getExpectedRate(_tokens[i], ERC20(ETH_TOKEN_ADDRESS), 10000);
cachedPrices[address(_tokens[i])] = expectedRate;
}
}
}File 6 of 10: InstaAccount
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);
}
}File 7 of 10: InstaIndex
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title InstaIndex
* @dev Main Contract For DeFi Smart Accounts. This is also a factory contract, Which deploys new Smart Account.
* Also Registry for DeFi Smart Accounts.
*/
interface AccountInterface {
function version() external view returns (uint);
function enable(address authority) external;
function cast(address[] calldata _targets, bytes[] calldata _datas, address _origin) external payable returns (bytes32[] memory responses);
}
interface ListInterface {
function init(address _account) external;
}
contract AddressIndex {
event LogNewMaster(address indexed master);
event LogUpdateMaster(address indexed master);
event LogNewCheck(uint indexed accountVersion, address indexed check);
event LogNewAccount(address indexed _newAccount, address indexed _connectors, address indexed _check);
// New Master Address.
address private newMaster;
// Master Address.
address public master;
// List Registry Address.
address public list;
// Connectors Modules(Account Module Version => Connectors Registry Module Address).
mapping (uint => address) public connectors;
// Check Modules(Account Module Version => Check Module Address).
mapping (uint => address) public check;
// Account Modules(Account Module Version => Account Module Address).
mapping (uint => address) public account;
// Version Count of Account Modules.
uint public versionCount;
/**
* @dev Throws if the sender not is Master Address.
*/
modifier isMaster() {
require(msg.sender == master, "not-master");
_;
}
/**
* @dev Change the Master Address.
* @param _newMaster New Master Address.
*/
function changeMaster(address _newMaster) external isMaster {
require(_newMaster != master, "already-a-master");
require(_newMaster != address(0), "not-valid-address");
require(newMaster != _newMaster, "already-a-new-master");
newMaster = _newMaster;
emit LogNewMaster(_newMaster);
}
function updateMaster() external {
require(newMaster != address(0), "not-valid-address");
require(msg.sender == newMaster, "not-master");
master = newMaster;
newMaster = address(0);
emit LogUpdateMaster(master);
}
/**
* @dev Change the Check Address of a specific Account Module version.
* @param accountVersion Account Module version.
* @param _newCheck The New Check Address.
*/
function changeCheck(uint accountVersion, address _newCheck) external isMaster {
require(_newCheck != check[accountVersion], "already-a-check");
check[accountVersion] = _newCheck;
emit LogNewCheck(accountVersion, _newCheck);
}
/**
* @dev Add New Account Module.
* @param _newAccount The New Account Module Address.
* @param _connectors Connectors Registry Module Address.
* @param _check Check Module Address.
*/
function addNewAccount(address _newAccount, address _connectors, address _check) external isMaster {
require(_newAccount != address(0), "not-valid-address");
versionCount++;
require(AccountInterface(_newAccount).version() == versionCount, "not-valid-version");
account[versionCount] = _newAccount;
if (_connectors != address(0)) connectors[versionCount] = _connectors;
if (_check != address(0)) check[versionCount] = _check;
emit LogNewAccount(_newAccount, _connectors, _check);
}
}
contract CloneFactory is AddressIndex {
/**
* @dev Clone a new Account Module.
* @param version Account Module version to clone.
*/
function createClone(uint version) internal returns (address result) {
bytes20 targetBytes = bytes20(account[version]);
// solium-disable-next-line security/no-inline-assembly
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
/**
* @dev Check if Account Module is a clone.
* @param version Account Module version.
* @param query Account Module Address.
*/
function isClone(uint version, address query) external view returns (bool result) {
bytes20 targetBytes = bytes20(account[version]);
// solium-disable-next-line security/no-inline-assembly
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)))
)
}
}
}
contract InstaIndex is CloneFactory {
event LogAccountCreated(address sender, address indexed owner, address indexed account, address indexed origin);
/**
* @dev Create a new DeFi Smart Account for a user and run cast function in the new Smart Account.
* @param _owner Owner of the Smart Account.
* @param accountVersion Account Module version.
* @param _targets Array of Target to run cast function.
* @param _datas Array of Data(callData) to run cast function.
* @param _origin Where Smart Account is created.
*/
function buildWithCast(
address _owner,
uint accountVersion,
address[] calldata _targets,
bytes[] calldata _datas,
address _origin
) external payable returns (address _account) {
_account = build(_owner, accountVersion, _origin);
if (_targets.length > 0) AccountInterface(_account).cast.value(msg.value)(_targets, _datas, _origin);
}
/**
* @dev Create a new DeFi Smart Account for a user.
* @param _owner Owner of the Smart Account.
* @param accountVersion Account Module version.
* @param _origin Where Smart Account is created.
*/
function build(
address _owner,
uint accountVersion,
address _origin
) public returns (address _account) {
require(accountVersion != 0 && accountVersion <= versionCount, "not-valid-account");
_account = createClone(accountVersion);
ListInterface(list).init(_account);
AccountInterface(_account).enable(_owner);
emit LogAccountCreated(msg.sender, _owner, _account, _origin);
}
/**
* @dev Setup Initial things for InstaIndex, after its been deployed and can be only run once.
* @param _master The Master Address.
* @param _list The List Address.
* @param _account The Account Module Address.
* @param _connectors The Connectors Registry Module Address.
*/
function setBasics(
address _master,
address _list,
address _account,
address _connectors
) external {
require(
master == address(0) &&
list == address(0) &&
account[1] == address(0) &&
connectors[1] == address(0) &&
versionCount == 0,
"already-defined"
);
master = _master;
list = _list;
versionCount++;
account[versionCount] = _account;
connectors[versionCount] = _connectors;
}
}File 8 of 10: InstaConnectors
pragma solidity ^0.6.0;
/**
* @title InstaConnectors
* @dev Registry for Connectors.
*/
interface IndexInterface {
function master() external view returns (address);
}
interface ConnectorInterface {
function connectorID() external view returns(uint _type, uint _id);
function name() external view returns (string memory);
}
contract DSMath {
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");
}
}
contract Controllers is DSMath {
event LogAddController(address indexed addr);
event LogRemoveController(address indexed addr);
// InstaIndex Address.
address public constant instaIndex = 0x2971AdFa57b20E5a416aE5a708A8655A9c74f723;
// Enabled Chief(Address of Chief => bool).
mapping(address => bool) public chief;
// Enabled Connectors(Connector Address => bool).
mapping(address => bool) public connectors;
// Enabled Static Connectors(Connector Address => bool).
mapping(address => bool) public staticConnectors;
/**
* @dev Throws if the sender not is Master Address from InstaIndex
* or Enabled Chief.
*/
modifier isChief {
require(chief[msg.sender] || msg.sender == IndexInterface(instaIndex).master(), "not-an-chief");
_;
}
/**
* @dev Enable a Chief.
* @param _userAddress Chief Address.
*/
function enableChief(address _userAddress) external isChief {
chief[_userAddress] = true;
emit LogAddController(_userAddress);
}
/**
* @dev Disables a Chief.
* @param _userAddress Chief Address.
*/
function disableChief(address _userAddress) external isChief {
delete chief[_userAddress];
emit LogRemoveController(_userAddress);
}
}
contract Listings is Controllers {
// Connectors Array.
address[] public connectorArray;
// Count of Connector's Enabled.
uint public connectorCount;
/**
* @dev Add Connector to Connector's array.
* @param _connector Connector Address.
**/
function addToArr(address _connector) internal {
require(_connector != address(0), "Not-valid-connector");
(, uint _id) = ConnectorInterface(_connector).connectorID();
require(_id == (connectorArray.length+1),"ConnectorID-doesnt-match");
ConnectorInterface(_connector).name(); // Checking if connector has function name()
connectorArray.push(_connector);
}
// Static Connectors Array.
address[] public staticConnectorArray;
/**
* @dev Add Connector to Static Connector's array.
* @param _connector Static Connector Address.
**/
function addToArrStatic(address _connector) internal {
require(_connector != address(0), "Not-valid-connector");
(, uint _id) = ConnectorInterface(_connector).connectorID();
require(_id == (staticConnectorArray.length+1),"ConnectorID-doesnt-match");
ConnectorInterface(_connector).name(); // Checking if connector has function name()
staticConnectorArray.push(_connector);
}
}
contract InstaConnectors is Listings {
event LogEnable(address indexed connector);
event LogDisable(address indexed connector);
event LogEnableStatic(address indexed connector);
/**
* @dev Enable Connector.
* @param _connector Connector Address.
*/
function enable(address _connector) external isChief {
require(!connectors[_connector], "already-enabled");
addToArr(_connector);
connectors[_connector] = true;
connectorCount++;
emit LogEnable(_connector);
}
/**
* @dev Disable Connector.
* @param _connector Connector Address.
*/
function disable(address _connector) external isChief {
require(connectors[_connector], "already-disabled");
delete connectors[_connector];
connectorCount--;
emit LogDisable(_connector);
}
/**
* @dev Enable Static Connector.
* @param _connector Static Connector Address.
*/
function enableStatic(address _connector) external isChief {
require(!staticConnectors[_connector], "already-enabled");
addToArrStatic(_connector);
staticConnectors[_connector] = true;
emit LogEnableStatic(_connector);
}
/**
* @dev Check if Connector addresses are enabled.
* @param _connectors Array of Connector Addresses.
*/
function isConnector(address[] calldata _connectors) external view returns (bool isOk) {
isOk = true;
for (uint i = 0; i < _connectors.length; i++) {
if (!connectors[_connectors[i]]) {
isOk = false;
break;
}
}
}
/**
* @dev Check if Connector addresses are static enabled.
* @param _connectors Array of Connector Addresses.
*/
function isStaticConnector(address[] calldata _connectors) external view returns (bool isOk) {
isOk = true;
for (uint i = 0; i < _connectors.length; i++) {
if (!staticConnectors[_connectors[i]]) {
isOk = false;
break;
}
}
}
/**
* @dev get Connector's Array length.
*/
function connectorLength() external view returns (uint) {
return connectorArray.length;
}
/**
* @dev get Static Connector's Array length.
*/
function staticConnectorLength() external view returns (uint) {
return staticConnectorArray.length;
}
}File 9 of 10: ConnectBasic
pragma solidity ^0.6.0;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint) external;
function transferFrom(address, address, uint) external;
function deposit() external payable;
function withdraw(uint) external;
function balanceOf(address) external view returns (uint);
function decimals() external view returns (uint);
}
interface MemoryInterface {
function getUint(uint id) external returns (uint num);
function setUint(uint id, uint val) external;
}
interface EventInterface {
function emitEvent(uint connectorType, uint connectorID, bytes32 eventCode, bytes calldata eventData) external;
}
contract Stores {
/**
* @dev Return ethereum address
*/
function getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
/**
* @dev Return memory variable address
*/
function getMemoryAddr() internal pure returns (address) {
return 0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F; // InstaMemory Address
}
/**
* @dev Return InstaEvent Address.
*/
function getEventAddr() internal pure returns (address) {
return 0x2af7ea6Cb911035f3eb1ED895Cb6692C39ecbA97; // InstaEvent Address
}
/**
* @dev Get Uint value from InstaMemory Contract.
*/
function getUint(uint getId, uint val) internal returns (uint returnVal) {
returnVal = getId == 0 ? val : MemoryInterface(getMemoryAddr()).getUint(getId);
}
/**
* @dev Set Uint value in InstaMemory Contract.
*/
function setUint(uint setId, uint val) internal {
if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val);
}
/**
* @dev emit event on event contract
*/
function emitEvent(bytes32 eventCode, bytes memory eventData) internal {
(uint model, uint id) = connectorID();
EventInterface(getEventAddr()).emitEvent(model, id, eventCode, eventData);
}
/**
* @dev Connector Details.
*/
function connectorID() public pure returns(uint model, uint id) {
(model, id) = (1, 19);
}
}
contract DSMath {
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "math-not-safe");
}
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, "math-not-safe");
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
}
interface AccountInterface {
function isAuth(address _user) external view returns (bool);
}
contract BasicResolver is Stores {
event LogDeposit(address indexed erc20, uint256 tokenAmt, uint256 getId, uint256 setId);
event LogWithdraw(address indexed erc20, uint256 tokenAmt, address indexed to, uint256 getId, uint256 setId);
using SafeERC20 for IERC20;
/**
* @dev Deposit Assets To Smart Account.
* @param erc20 Token Address.
* @param tokenAmt Token Amount.
* @param getId Get Storage ID.
* @param setId Set Storage ID.
*/
function deposit(address erc20, uint tokenAmt, uint getId, uint setId) public payable {
uint amt = getUint(getId, tokenAmt);
if (erc20 != getEthAddr()) {
IERC20 token = IERC20(erc20);
amt = amt == uint(-1) ? token.balanceOf(msg.sender) : amt;
token.safeTransferFrom(msg.sender, address(this), amt);
} else {
require(msg.value == amt || amt == uint(-1), "invalid-ether-amount");
amt = msg.value;
}
setUint(setId, amt);
emit LogDeposit(erc20, amt, getId, setId);
bytes32 _eventCode = keccak256("LogDeposit(address,uint256,uint256,uint256)");
bytes memory _eventParam = abi.encode(erc20, amt, getId, setId);
emitEvent(_eventCode, _eventParam);
}
/**
* @dev Withdraw Assets To Smart Account.
* @param erc20 Token Address.
* @param tokenAmt Token Amount.
* @param to Withdraw token address.
* @param getId Get Storage ID.
* @param setId Set Storage ID.
*/
function withdraw(
address erc20,
uint tokenAmt,
address payable to,
uint getId,
uint setId
) public payable {
require(AccountInterface(address(this)).isAuth(to), "invalid-to-address");
uint amt = getUint(getId, tokenAmt);
if (erc20 == getEthAddr()) {
amt = amt == uint(-1) ? address(this).balance : amt;
to.transfer(amt);
} else {
IERC20 token = IERC20(erc20);
amt = amt == uint(-1) ? token.balanceOf(address(this)) : amt;
token.safeTransfer(to, amt);
}
setUint(setId, amt);
emit LogWithdraw(erc20, amt, to, getId, setId);
bytes32 _eventCode = keccak256("LogWithdraw(address,uint256,address,uint256,uint256)");
bytes memory _eventParam = abi.encode(erc20, amt, to, getId, setId);
emitEvent(_eventCode, _eventParam);
}
}
contract ConnectBasic is BasicResolver {
string public constant name = "Basic-v1.1";
}File 10 of 10: InstaPool
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call.value(weiValue)(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface CTokenInterface {
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function borrowBalanceCurrent(address) external returns (uint);
function redeemUnderlying(uint) external returns (uint);
function borrow(uint) external returns (uint);
function underlying() external view returns (address);
function borrowBalanceStored(address) external view returns (uint);
}
interface CETHInterface {
function mint() external payable;
function repayBorrow() external payable;
}
interface ComptrollerInterface {
function getAssetsIn(address account) external view returns (address[] memory);
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cTokenAddress) external returns (uint);
}
interface AccountInterface {
function version() external view returns (uint);
}
interface ListInterface {
function accountID(address) external view returns (uint64);
}
interface IndexInterface {
function master() external view returns (address);
function list() external view returns (address);
function isClone(uint, address) external view returns (bool);
}
interface CheckInterface {
function isOk() external view returns (bool);
}
contract DSMath {
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "sub-overflow");
}
}
contract Helpers is DSMath {
using SafeERC20 for IERC20;
address constant internal instaIndex = 0x2971AdFa57b20E5a416aE5a708A8655A9c74f723;
address constant internal oldInstaPool = 0x1879BEE186BFfBA9A8b1cAD8181bBFb218A5Aa61;
address constant internal comptrollerAddr = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address constant internal ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address constant internal cEth = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
mapping (address => bool) public isTknAllowed;
mapping (address => address) public tknToCTkn;
mapping (address => uint) public borrowedToken;
address[] public tokensAllowed;
bool public checkOldPool = true;
IndexInterface indexContract = IndexInterface(instaIndex);
ListInterface listContract = ListInterface(indexContract.list());
CheckInterface oldInstaPoolContract = CheckInterface(oldInstaPool);
/**
* FOR SECURITY PURPOSE
* only Smart DEFI Account can access the liquidity pool contract
*/
modifier isDSA {
uint64 id = listContract.accountID(msg.sender);
require(id != 0, "not-dsa-id");
require(indexContract.isClone(AccountInterface(msg.sender).version(), msg.sender), "not-dsa-clone");
_;
}
function tokenBal(address token) internal view returns (uint _bal) {
_bal = token == ethAddr ? address(this).balance : IERC20(token).balanceOf(address(this));
}
function _transfer(address token, uint _amt) internal {
token == ethAddr ?
msg.sender.transfer(_amt) :
IERC20(token).safeTransfer(msg.sender, _amt);
}
}
contract CompoundResolver is Helpers {
function borrowAndSend(address[] memory tokens, uint[] memory tknAmt) internal {
if (tokens.length > 0) {
for (uint i = 0; i < tokens.length; i++) {
address token = tokens[i];
address cToken = tknToCTkn[token];
require(isTknAllowed[token], "token-not-listed");
if (cToken != address(0) && tknAmt[i] > 0) {
require(CTokenInterface(cToken).borrow(tknAmt[i]) == 0, "borrow-failed");
borrowedToken[token] += tknAmt[i];
_transfer(token, tknAmt[i]);
}
}
}
}
function payback(address[] memory tokens) internal {
if (tokens.length > 0) {
for (uint i = 0; i < tokens.length; i++) {
address token = tokens[i];
address cToken = tknToCTkn[token];
if (cToken != address(0)) {
CTokenInterface ctknContract = CTokenInterface(cToken);
if(token != ethAddr) {
require(ctknContract.repayBorrow(uint(-1)) == 0, "payback-failed");
} else {
CETHInterface(cToken).repayBorrow.value(ctknContract.borrowBalanceCurrent(address(this)))();
require(ctknContract.borrowBalanceCurrent(address(this)) == 0, "ETH-flashloan-not-paid");
}
delete borrowedToken[token];
}
}
}
}
}
contract AccessLiquidity is CompoundResolver {
event LogPoolBorrow(address indexed user, address[] tknAddr, uint[] amt);
event LogPoolPayback(address indexed user, address[] tknAddr);
/**
* @dev borrow tokens and use them on DSA.
* @param tokens Array of tokens.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param amounts Array of tokens amount.
*/
function accessLiquidity(address[] calldata tokens, uint[] calldata amounts) external isDSA {
require(tokens.length == amounts.length, "length-not-equal");
borrowAndSend(tokens, amounts);
emit LogPoolBorrow(
msg.sender,
tokens,
amounts
);
}
/**
* @dev Payback borrowed tokens.
* @param tokens Array of tokens.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
*/
function returnLiquidity(address[] calldata tokens) external payable isDSA {
payback(tokens);
emit LogPoolPayback(msg.sender, tokens);
}
function isOk() public view returns(bool ok) {
ok = true;
for (uint i = 0; i < tokensAllowed.length; i++) {
uint tknBorrowed = borrowedToken[tokensAllowed[i]];
if(tknBorrowed > 0){
ok = false;
break;
}
}
if(checkOldPool && ok) {
bool isOldPoolOk = oldInstaPoolContract.isOk();
ok = isOldPoolOk;
}
}
}
contract ProvideLiquidity is AccessLiquidity {
event LogDeposit(address indexed user, address indexed token, uint amount, uint cAmount);
event LogWithdraw(address indexed user, address indexed token, uint amount, uint cAmount);
mapping (address => mapping (address => uint)) public liquidityBalance;
/**
* @dev Deposit Liquidity.
* @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param amt token amount.
*/
function deposit(address token, uint amt) external payable returns (uint _amt) {
require(isTknAllowed[token], "token-not-listed");
require(amt > 0 || msg.value > 0, "amt-not-valid");
if (msg.value > 0) require(token == ethAddr, "not-eth-addr");
address cErc20 = tknToCTkn[token];
uint initalBal = tokenBal(cErc20);
if (token == ethAddr) {
_amt = msg.value;
CETHInterface(cErc20).mint.value(_amt)();
} else {
_amt = amt == (uint(-1)) ? IERC20(token).balanceOf(msg.sender) : amt;
IERC20(token).safeTransferFrom(msg.sender, address(this), _amt);
require(CTokenInterface(cErc20).mint(_amt) == 0, "mint-failed");
}
uint finalBal = tokenBal(cErc20);
uint ctokenAmt = sub(finalBal, initalBal);
liquidityBalance[token][msg.sender] += ctokenAmt;
emit LogDeposit(msg.sender, token, _amt, ctokenAmt);
}
/**
* @dev Withdraw Liquidity.
* @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param amt token amount.
*/
function withdraw(address token, uint amt) external returns (uint _amt) {
uint _userLiq = liquidityBalance[token][msg.sender];
require(_userLiq > 0, "nothing-to-withdraw");
uint _cAmt;
address ctoken = tknToCTkn[token];
if (amt == uint(-1)) {
uint initknBal = tokenBal(token);
require(CTokenInterface(ctoken).redeem(_userLiq) == 0, "redeem-failed");
uint finTknBal = tokenBal(token);
_cAmt = _userLiq;
delete liquidityBalance[token][msg.sender];
_amt = sub(finTknBal, initknBal);
} else {
uint iniCtknBal = tokenBal(ctoken);
require(CTokenInterface(ctoken).redeemUnderlying(amt) == 0, "redeemUnderlying-failed");
uint finCtknBal = tokenBal(ctoken);
_cAmt = sub(iniCtknBal, finCtknBal);
require(_cAmt <= _userLiq, "not-enough-to-withdraw");
liquidityBalance[token][msg.sender] -= _cAmt;
_amt = amt;
}
_transfer(token, _amt);
emit LogWithdraw(msg.sender, token, _amt, _cAmt);
}
}
contract Controllers is ProvideLiquidity {
event LogEnterMarket(address[] token, address[] ctoken);
event LogExitMarket(address indexed token, address indexed ctoken);
event LogWithdrawMaster(address indexed user, address indexed token, uint amount);
modifier isMaster {
require(msg.sender == indexContract.master(), "not-master");
_;
}
function switchOldPoolCheck() external isMaster {
checkOldPool = !checkOldPool;
}
function _enterMarket(address[] memory cTknAddrs) internal {
ComptrollerInterface(comptrollerAddr).enterMarkets(cTknAddrs);
address[] memory tknAddrs = new address[](cTknAddrs.length);
for (uint i = 0; i < cTknAddrs.length; i++) {
if (cTknAddrs[i] != cEth) {
tknAddrs[i] = CTokenInterface(cTknAddrs[i]).underlying();
IERC20(tknAddrs[i]).safeApprove(cTknAddrs[i], uint(-1));
} else {
tknAddrs[i] = ethAddr;
}
tknToCTkn[tknAddrs[i]] = cTknAddrs[i];
require(!isTknAllowed[tknAddrs[i]], "tkn-already-allowed");
isTknAllowed[tknAddrs[i]] = true;
tokensAllowed.push(tknAddrs[i]);
}
emit LogEnterMarket(tknAddrs, cTknAddrs);
}
/**
* @dev Enter compound market to enable borrowing.
* @param cTknAddrs Array Ctoken addresses.
*/
function enterMarket(address[] calldata cTknAddrs) external isMaster {
_enterMarket(cTknAddrs);
}
/**
* @dev Exit compound market to disable borrowing.
* @param cTkn Ctoken address.
*/
function exitMarket(address cTkn) external isMaster {
address tkn;
if (cTkn != cEth) {
tkn = CTokenInterface(cTkn).underlying();
IERC20(tkn).safeApprove(cTkn, 0);
} else {
tkn = ethAddr;
}
require(isTknAllowed[tkn], "tkn-not-allowed");
ComptrollerInterface(comptrollerAddr).exitMarket(cTkn);
delete isTknAllowed[tkn];
bool isFound = false;
uint _length = tokensAllowed.length;
uint _id;
for (uint i = 0; i < _length; i++) {
if (tkn == tokensAllowed[i]) {
isFound = true;
_id = i;
break;
}
}
if (isFound) {
address _last = tokensAllowed[_length - 1];
tokensAllowed[_length - 1] = tokensAllowed[_id];
tokensAllowed[_id] = _last;
tokensAllowed.pop();
}
emit LogExitMarket(tkn, cTkn);
}
/**
* @dev Withdraw Liquidity.
* @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param amt token amount.
*/
function withdrawMaster(address token, uint amt) external isMaster {
_transfer(token, amt);
emit LogWithdrawMaster(msg.sender, token, amt);
}
function spell(address _target, bytes calldata _data) external isMaster {
require(_target != address(0), "target-invalid");
bytes memory _callData = _data;
assembly {
let succeeded := delegatecall(gas(), _target, add(_callData, 0x20), mload(_callData), 0, 0)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
let size := returndatasize()
returndatacopy(0x00, 0x00, size)
revert(0x00, size)
}
}
}
}
contract InstaPool is Controllers {
constructor (address[] memory ctkns) public {
_enterMarket(ctkns);
}
receive() external payable {}
}