// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @opengsn/gsn/contracts/interfaces/IRelayRecipient.sol
pragma solidity ^0.6.2;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal virtual view returns (bytes memory);
function versionRecipient() external virtual view returns (string memory);
}
// File: @opengsn/gsn/contracts/BaseRelayRecipient.sol
// solhint-disable no-inline-assembly
pragma solidity ^0.6.2;
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal override virtual view returns (bytes memory ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// we copy the msg.data , except the last 20 bytes (and update the total length)
assembly {
let ptr := mload(0x40)
// copy only size-20 bytes
let size := sub(calldatasize(),20)
// structure RLP data as <offset> <length> <bytes>
mstore(ptr, 0x20)
mstore(add(ptr,32), size)
calldatacopy(add(ptr,64), 0, size)
return(ptr, add(size,64))
}
} else {
return msg.data;
}
}
}
// File: @opengsn/gsn/contracts/interfaces/IKnowForwarderAddress.sol
pragma solidity ^0.6.2;
interface IKnowForwarderAddress {
/**
* return the forwarder we trust to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function getTrustedForwarder() external view returns(address);
}
// File: @opengsn/gsn/contracts/forwarder/IForwarder.sol
pragma solidity ^0.6.2;
pragma experimental ABIEncoderV2;
interface IForwarder {
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
}
function getNonce(address from)
external view
returns(uint256);
/**
* verify the transaction would execute.
* validate the signature and the nonce of the request.
* revert if either signature or nonce are incorrect.
*/
function verify(
ForwardRequest calldata forwardRequest,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata signature
) external view;
/**
* execute a transaction
* @param forwardRequest - all transaction parameters
* @param domainSeparator - domain used when signing this request
* @param requestTypeHash - request type used when signing this request.
* @param suffixData - the extension data used when signing this request.
* @param signature - signature to validate.
*
* the transaction is verified, and then executed.
* the success and ret of "call" are returned.
* This method would revert only verification errors. target errors
* are reported using the returned "success" and ret string
*/
function execute(
ForwardRequest calldata forwardRequest,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata signature
)
external payable
returns (bool success, bytes memory ret);
/**
* Register a new Request typehash.
* @param typeName - the name of the request type.
* @param typeSuffix - anything after the generic params can be empty string (if no extra fields are needed)
* if it does contain a value, then a comma is added first.
*/
function registerRequestType(string calldata typeName, string calldata typeSuffix) external;
/**
* Register a new domain separator.
* The domain separator must have the following fields: name,version,chainId, verifyingContract.
* the chainId is the current network's chainId, and the verifyingContract is this forwarder.
* This method is given the domain name and version to create and register the domain separator value.
* @param name the domain's display name
* @param version the domain/protocol version
*/
function registerDomainSeparator(string calldata name, string calldata version) external;
}
// File: @opengsn/gsn/contracts/interfaces/GsnTypes.sol
pragma solidity ^0.6.2;
interface GsnTypes {
struct RelayData {
uint256 gasPrice;
uint256 pctRelayFee;
uint256 baseRelayFee;
address relayWorker;
address paymaster;
bytes paymasterData;
uint256 clientId;
address forwarder;
}
//note: must start with the ForwardRequest to be an extension of the generic forwarder
struct RelayRequest {
IForwarder.ForwardRequest request;
RelayData relayData;
}
}
// File: @opengsn/gsn/contracts/interfaces/IStakeManager.sol
pragma solidity ^0.6.2;
interface IStakeManager {
/// Emitted when a stake or unstakeDelay are initialized or increased
event StakeAdded(
address indexed relayManager,
address indexed owner,
uint256 stake,
uint256 unstakeDelay
);
/// Emitted once a stake is scheduled for withdrawal
event StakeUnlocked(
address indexed relayManager,
address indexed owner,
uint256 withdrawBlock
);
/// Emitted when owner withdraws relayManager funds
event StakeWithdrawn(
address indexed relayManager,
address indexed owner,
uint256 amount
);
/// Emitted when an authorized Relay Hub penalizes a relayManager
event StakePenalized(
address indexed relayManager,
address indexed beneficiary,
uint256 reward
);
event HubAuthorized(
address indexed relayManager,
address indexed relayHub
);
event HubUnauthorized(
address indexed relayManager,
address indexed relayHub,
uint256 removalBlock
);
/// @param stake - amount of ether staked for this relay
/// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock'
/// @param withdrawBlock - first block number 'withdraw' will be callable, or zero if the unlock has not been called
/// @param owner - address that receives revenue and manages relayManager's stake
struct StakeInfo {
uint256 stake;
uint256 unstakeDelay;
uint256 withdrawBlock;
address payable owner;
}
struct RelayHubInfo {
uint256 removalBlock;
}
/// Put a stake for a relayManager and set its unstake delay.
/// If the entry does not exist, it is created, and the caller of this function becomes its owner.
/// If the entry already exists, only the owner can call this function.
/// @param relayManager - address that represents a stake entry and controls relay registrations on relay hubs
/// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock'
function stakeForAddress(address relayManager, uint256 unstakeDelay) external payable;
function unlockStake(address relayManager) external;
function withdrawStake(address relayManager) external;
function authorizeHubByOwner(address relayManager, address relayHub) external;
function authorizeHubByManager(address relayHub) external;
function unauthorizeHubByOwner(address relayManager, address relayHub) external;
function unauthorizeHubByManager(address relayHub) external;
function isRelayManagerStaked(address relayManager, address relayHub, uint256 minAmount, uint256 minUnstakeDelay)
external
view
returns (bool);
/// Slash the stake of the relay relayManager. In order to prevent stake kidnapping, burns half of stake on the way.
/// @param relayManager - entry to penalize
/// @param beneficiary - address that receives half of the penalty amount
/// @param amount - amount to withdraw from stake
function penalizeRelayManager(address relayManager, address payable beneficiary, uint256 amount) external;
function getStakeInfo(address relayManager) external view returns (StakeInfo memory stakeInfo);
function versionSM() external view returns (string memory);
}
// File: @opengsn/gsn/contracts/interfaces/IRelayHub.sol
pragma solidity ^0.6.2;
interface IRelayHub {
/// Emitted when a relay server registers or updates its details
/// Looking at these events lets a client discover relay servers
event RelayServerRegistered(
address indexed relayManager,
uint256 baseRelayFee,
uint256 pctRelayFee,
string relayUrl);
/// Emitted when relays are added by a relayManager
event RelayWorkersAdded(
address indexed relayManager,
address[] newRelayWorkers,
uint256 workersCount
);
// Emitted when an account withdraws funds from RelayHub.
event Withdrawn(
address indexed account,
address indexed dest,
uint256 amount
);
// Emitted when depositFor is called, including the amount and account that was funded.
event Deposited(
address indexed paymaster,
address indexed from,
uint256 amount
);
/// Emitted when an attempt to relay a call fails and Paymaster does not accept the transaction.
/// The actual relayed call was not executed, and the recipient not charged.
/// @param reason contains a revert reason returned from preRelayedCall or forwarder.
event TransactionRejectedByPaymaster(
address indexed relayManager,
address indexed paymaster,
address indexed from,
address to,
address relayWorker,
bytes4 selector,
uint256 innerGasUsed,
bytes reason);
// Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be
// indicated in the status field.
// Useful when monitoring a relay's operation and relayed calls to a contract.
// Charge is the ether value deducted from the recipient's balance, paid to the relay's manager.
event TransactionRelayed(
address indexed relayManager,
address indexed relayWorker,
address indexed from,
address to,
address paymaster,
bytes4 selector,
RelayCallStatus status,
uint256 charge);
event TransactionResult(
RelayCallStatus status,
bytes returnValue
);
event Penalized(
address indexed relayWorker,
address sender,
uint256 reward
);
/// Reason error codes for the TransactionRelayed event
/// @param OK - the transaction was successfully relayed and execution successful - never included in the event
/// @param RelayedCallFailed - the transaction was relayed, but the relayed call failed
/// @param RejectedByPreRelayed - the transaction was not relayed due to preRelatedCall reverting
/// @param RejectedByForwarder - the transaction was not relayed due to forwarder check (signature,nonce)
/// @param PostRelayedFailed - the transaction was relayed and reverted due to postRelatedCall reverting
/// @param PaymasterBalanceChanged - the transaction was relayed and reverted due to the paymaster balance change
enum RelayCallStatus {
OK,
RelayedCallFailed,
RejectedByPreRelayed,
RejectedByForwarder,
RejectedByRecipientRevert,
PostRelayedFailed,
PaymasterBalanceChanged
}
/// Add new worker addresses controlled by sender who must be a staked Relay Manager address.
/// Emits a RelayWorkersAdded event.
/// This function can be called multiple times, emitting new events
function addRelayWorkers(address[] calldata newRelayWorkers) external;
function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external;
// Balance management
// Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only
// be withdrawn by the contract itself, by calling withdraw.
// Emits a Deposited event.
function depositFor(address target) external payable;
// Withdraws from an account's balance, sending it back to it. Relay managers call this to retrieve their revenue, and
// contracts can also use it to reduce their funding.
// Emits a Withdrawn event.
function withdraw(uint256 amount, address payable dest) external;
// Relaying
/// Relays a transaction. For this to succeed, multiple conditions must be met:
/// - Paymaster's "acceptRelayCall" method must succeed and not revert
/// - the sender must be a registered Relay Worker that the user signed
/// - the transaction's gas price must be equal or larger than the one that was signed by the sender
/// - the transaction must have enough gas to run all internal transactions if they use all gas available to them
/// - the Paymaster must have enough balance to pay the Relay Worker for the scenario when all gas is spent
///
/// If all conditions are met, the call will be relayed and the recipient charged.
///
/// Arguments:
/// @param relayRequest - all details of the requested relayed call
/// @param signature - client's EIP-712 signature over the relayRequest struct
/// @param approvalData: dapp-specific data forwarded to preRelayedCall.
/// This value is *not* verified by the Hub. For example, it can be used to pass a signature to the Paymaster
/// @param externalGasLimit - the value passed as gasLimit to the transaction.
///
/// Emits a TransactionRelayed event.
function relayCall(
uint paymasterMaxAcceptanceBudget,
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint externalGasLimit
)
external
returns (bool paymasterAccepted, bytes memory returnValue);
function penalize(address relayWorker, address payable beneficiary) external;
/// The fee is expressed as a base fee in wei plus percentage on actual charge.
/// E.g. a value of 40 stands for a 40% fee, so the recipient will be
/// charged for 1.4 times the spent amount.
function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) external view returns (uint256);
/* getters */
/// Returns the stake manager of this RelayHub.
function stakeManager() external view returns(IStakeManager);
function penalizer() external view returns(address);
/// Returns an account's deposits. It can be either a deposit of a paymaster, or a revenue of a relay manager.
function balanceOf(address target) external view returns (uint256);
// Minimum stake a relay can have. An attack to the network will never cost less than half this value.
function minimumStake() external view returns (uint256);
// Minimum unstake delay blocks of a relay manager's stake on the StakeManager
function minimumUnstakeDelay() external view returns (uint256);
// Maximum funds that can be deposited at once. Prevents user error by disallowing large deposits.
function maximumRecipientDeposit() external view returns (uint256);
//gas overhead to calculate gasUseWithoutPost
function postOverhead() external view returns (uint256);
// Gas set aside for all relayCall() instructions to prevent unexpected out-of-gas exceptions
function gasReserve() external view returns (uint256);
// maximum number of worker account allowed per manager
function maxWorkerCount() external view returns (uint256);
function workerToManager(address worker) external view returns(address);
function workerCount(address manager) external view returns(uint256);
function isRelayManagerStaked(address relayManager) external view returns(bool);
/**
* @dev the total gas overhead of relayCall(), before the first gasleft() and after the last gasleft().
* Assume that relay has non-zero balance (costs 15'000 more otherwise).
*/
// Gas cost of all relayCall() instructions after actual 'calculateCharge()'
function gasOverhead() external view returns (uint256);
function versionHub() external view returns (string memory);
}
// File: contracts/Stealth.sol
// SPDX-License-Identifier: GPL-3.0
/**
* Stealth.sol
* Implements the StealthSwap core functionnality.
* GSN Placeholders are used to fetch msg.sender until
* Future integration where withdrawals will be processed trough
* GSN.
*/
pragma solidity ^0.6.12;
/// @title StealthSwap Oracle Contract for Broadcasting Payment Notes
contract Stealth is Ownable, BaseRelayRecipient, IKnowForwarderAddress {
using SafeMath for uint256;
/// @dev protocol token (OWL) definition
IERC20 private protocolToken;
uint256 public protocolFee;
uint256 public abyss;
address public feeManager;
address payable public feeTaker;
bool private initialized;
constructor(
IERC20 _protocolToken,
uint256 _protocolFee,
address _feeManager,
address payable _feeTaker,
address _gsnForwarder
) public {
protocolToken = _protocolToken;
protocolFee = _protocolFee;
feeManager = _feeManager;
feeTaker = _feeTaker;
abyss = 1 wei;
trustedForwarder = _gsnForwarder;
}
mapping(address => bool) usedAddrs;
mapping(address => Payment) processedPayments;
/// Ownable Functions : Ownership is set at owner, then changed
/// to Governing Contract.
function setProtocolFee(uint256 _newFee) public onlyOwner {
protocolFee = _newFee;
}
function setFeeManager(address _newFeeManager) public onlyOwner {
feeManager = _newFeeManager;
}
function setFeeTaker(address payable _newFeeTaker) public onlyOwner {
feeTaker = _newFeeTaker;
}
function versionRecipient() external override view returns (string memory) {
return "1.2.0";
}
/// Events are singular blobs broadcasted by the oracle contract.
/// @notice PaymentNote represent a new payment made trough StealthSwap
/// @param receiver receiver's stealth address
/// @param token address of transferred token
/// @param amount amount transferred
/// @param xCoord public key X coordinate used to encrypt the paymentnote
/// @param yCoord public key Y coordinate used to encrypt the paymentnote
/// @param note encrypted scalar used to unlock funds on receiving end
event PaymentNote(
address indexed receiver,
address indexed token,
uint256 indexed amount,
bytes32 xCoord,
bytes32 yCoord,
bytes32 note
);
/// @notice Withdrawal is emitted from the local payment storage
/// @param receiver withdrawal address
/// @param interim address holding funds
/// @param token address
/// @param amount being withdrawn (always full amounts prevent partials)
event Withdrawal(
address indexed receiver,
address indexed interim,
address indexed token,
uint256 amount
);
/// @notice a payment is represented by its token address and amount
struct Payment {
address token;
uint256 amount;
}
/// @dev Checksummed address similar to 0x0000000000000000000000000000000000000000
address constant ETHER_TOKEN = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/// Sending Functions
/// @notice send ether to stealth address
/// @param _receiver receiver's address
/// @param _xCoord public key x coordinate used to encrypt the note
/// @param _yCoord public key y coordinate used to encrypt the note
/// @param _note encrypted scalar
function sendEther(
address payable _receiver,
bytes32 _xCoord,
bytes32 _yCoord,
bytes32 _note
) public payable unusedAddr(_receiver) {
/// enforce against dust attacks for ether transactions
require(msg.value >= protocolFee, "StealthSwap: Must have value higher than the protocol fee");
uint256 feeAllowance = IERC20(protocolToken).allowance(_msgSender(), address(this));
/// insure allowance is sufficient to pay for protocol fee
require(feeAllowance >= protocolFee, "StealthSwap: You must provide allowance to pay the protocol fee");
uint256 amount = msg.value;
/// enforce protocol fee payment
IERC20(protocolToken).transferFrom(_msgSender(), address(this), protocolFee);
/// emit new Payment Note
emit PaymentNote(_receiver, ETHER_TOKEN, amount, _xCoord, _yCoord, _note);
// Tag address as used to prevent stealth address re-use
usedAddrs[_receiver] = true;
// Transfer Ether to receiving stealth address
_receiver.transfer(amount);
}
/// @notice send erc20 token to stealth address
/// @param _receiver receiver's address
/// @param _tokenAddr token transferred address
/// @param _amount amount transferred
/// @param _xCoord public key x coordinate used to encrypt the note
/// @param _yCoord public key y coordinate used to encrypt the note
/// @param _note encrypted payment note
function sendERC20(
address payable _receiver,
address _tokenAddr,
uint256 _amount,
bytes32 _xCoord,
bytes32 _yCoord,
bytes32 _note
) public payable unusedAddr(_receiver) {
/// this prevents the case where attackers mint and send worthless tokens
uint256 feeAllowance = IERC20(protocolToken).allowance(_msgSender(), address(this));
/// insure allowance is sufficient to pay for protocol fee
require(feeAllowance >= protocolFee, "StealthSwap: You must provide allowance to pay the protocol fee");
uint256 tokenAllowance = IERC20(_tokenAddr).allowance(_msgSender(), address(this));
/// insure allowance is higher than protocolFee
require(tokenAllowance >= _amount, "StealthSwap: You must provide allowance to pay the protocol fee");
/// enforce protocol fee payment
IERC20(protocolToken).transferFrom(_msgSender(), address(this), protocolFee);
/// store token payment in our balance sheet
processedPayments[_receiver] = Payment({token: _tokenAddr, amount: _amount});
/// emit payment note
emit PaymentNote(_receiver, _tokenAddr, _amount, _xCoord, _yCoord, _note);
/// transfer tokens to contract control
/// transferFrom(_msgSender(),address(this),_amount)
IERC20(_tokenAddr).transferFrom(_msgSender(), address(this), _amount);
/// tag stealth address as used to prevent re-use
/// hashReceiver = getSHA3Hash(_receiver)
usedAddrs[_receiver] = true;
}
/// Withdrawal Processing
function withdraw(address _receiver) public {
uint256 amount = processedPayments[_msgSender()].amount;
address tokenAddr = processedPayments[_msgSender()].token;
// make sure _msgSender() has proper allocation
require(amount > 0, "StealthSwap: Unavailable tokens for withdrawal");
/// remove token payment from our balance sheet
delete processedPayments[_msgSender()];
emit Withdrawal(_msgSender(), _receiver, tokenAddr, amount);
/// send token to receiver
SafeERC20.safeTransfer(IERC20(tokenAddr), _receiver, amount);
}
/// @notice collect paid fees for redistribituion
/// @dev this should be called by the staking contract
function collectPaidFees() public onlyManager {
feeTaker.transfer(address(this).balance);
uint256 totalFees = IERC20(protocolToken).balanceOf(address(this));
IERC20(protocolToken).approve(feeTaker,totalFees);
IERC20(protocolToken).transfer(feeTaker, totalFees);
}
/// GSN Integration
function getTrustedForwarder() external override view returns(address) {
return trustedForwarder;
}
function setForwarder(address _forwarder) public onlyOwner {
trustedForwarder = _forwarder;
}
/// Modifiers
function _msgSender() internal override(Context, BaseRelayRecipient) view returns (address payable)
{
return BaseRelayRecipient._msgSender();
}
function _msgData() internal view override(Context, BaseRelayRecipient) returns (bytes memory) {
return BaseRelayRecipient._msgData();
}
modifier onlyManager() {
require(_msgSender() == feeManager, "StealthSwap: Wrong Fee Manager");
_;
}
modifier unusedAddr(address _addr) {
require(!usedAddrs[_addr], "StealthSwap: stealth address cannot be reused");
_;
}
/// Utility Functions
function getSHA3Hash(bytes memory input) public pure returns (bytes32 hashedOutput)
{
hashedOutput = keccak256(input);
}
}
{
"compilationTarget": {
"browser/FlatStealth.sol": "Stealth"
},
"evmVersion": "istanbul",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"contract IERC20","name":"_protocolToken","type":"address"},{"internalType":"uint256","name":"_protocolFee","type":"uint256"},{"internalType":"address","name":"_feeManager","type":"address"},{"internalType":"address payable","name":"_feeTaker","type":"address"},{"internalType":"address","name":"_gsnForwarder","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"xCoord","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"yCoord","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"note","type":"bytes32"}],"name":"PaymentNote","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"interim","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdrawal","type":"event"},{"inputs":[],"name":"abyss","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collectPaidFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeTaker","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"input","type":"bytes"}],"name":"getSHA3Hash","outputs":[{"internalType":"bytes32","name":"hashedOutput","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getTrustedForwarder","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"forwarder","type":"address"}],"name":"isTrustedForwarder","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address payable","name":"_receiver","type":"address"},{"internalType":"address","name":"_tokenAddr","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"bytes32","name":"_xCoord","type":"bytes32"},{"internalType":"bytes32","name":"_yCoord","type":"bytes32"},{"internalType":"bytes32","name":"_note","type":"bytes32"}],"name":"sendERC20","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address payable","name":"_receiver","type":"address"},{"internalType":"bytes32","name":"_xCoord","type":"bytes32"},{"internalType":"bytes32","name":"_yCoord","type":"bytes32"},{"internalType":"bytes32","name":"_note","type":"bytes32"}],"name":"sendEther","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"_newFeeManager","type":"address"}],"name":"setFeeManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address payable","name":"_newFeeTaker","type":"address"}],"name":"setFeeTaker","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_forwarder","type":"address"}],"name":"setForwarder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newFee","type":"uint256"}],"name":"setProtocolFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"trustedForwarder","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"versionRecipient","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_receiver","type":"address"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]