Verified contractExactMIT
SymBtc
Address0x839da7208cb8a551e47172cbfae9d685c8f37121
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.19
- Same code
Only this contract
Details
- Compiler
- solc 0.8.19+commit.7dd6d404
- Language
- solidity
- Optimization
- Yes, 2,000 runs
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,349,794
- Creation transaction
- 0x59d3fa6ed4…cb1890aace
34 files
- contracts/periphery/SymBtc.solmain4.25 KB
- @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol2.77 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol3.14 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol6.97 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.12 KB
- @openzeppelin/contracts/access/Ownable.sol2.46 KB
- @openzeppelin/contracts/interfaces/IERC1271.sol666 B
- @openzeppelin/contracts/token/ERC20/ERC20.sol11.81 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol2.96 KB
- @openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol2.25 KB
- @openzeppelin/contracts/utils/Address.sol7.91 KB
- @openzeppelin/contracts/utils/Context.sol844 B
- @openzeppelin/contracts/utils/Counters.sol1.4 KB
- @openzeppelin/contracts/utils/Strings.sol2.03 KB
- @openzeppelin/contracts/utils/cryptography/ECDSA.sol9.32 KB
- @openzeppelin/contracts/utils/cryptography/SignatureChecker.sol1.43 KB
- @openzeppelin/contracts/utils/cryptography/draft-EIP712.sol4.51 KB
- @uniswap/lib/contracts/libraries/TransferHelper.sol1.81 KB
- contracts/emergency/ISafeMode.sol450 B
- contracts/emergency/SafeModeGuarded.sol1.75 KB
- contracts/synth-core/SyntERC20.sol830 B
- contracts/synth-core/SyntFabric.sol5.99 KB
- contracts/synth-core/SynthesisBTC.sol14.88 KB
- contracts/synth-core/bridge/BridgeV2.sol7.18 KB
- contracts/synth-core/interfaces/IBridge.sol499 B
- contracts/synth-core/interfaces/ISyntFabric.sol563 B
- contracts/synth-core/metarouter/MetaRouteStructs.sol2.19 KB
- contracts/synth-core/metarouter/interfaces/IMetaRouter.sol876 B
- contracts/synth-core/types/BtcSerial.sol366 B
- contracts/utils/AdminableUpgradeable.sol849 B
- contracts/utils/RelayRecipientUpgradeable.sol1.36 KB
- contracts/utils/RevertMessageParser.sol533 B
contracts/periphery/SymBtc.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "../synth-core/bridge/BridgeV2.sol";
import "../synth-core/SynthesisBTC.sol";
import "../synth-core/SyntFabric.sol";
import "../synth-core/SyntERC20.sol";
/**
* @notice Reads a BTC portal's mint requests for the relayers: the request hash that the
* bridge's MPC signs, and that MPC
* @dev Constant: nothing in it changes after deployment, so it has no proxy and no owner.
* A portal moved to another bridge gets a new SymBtc on that bridge
*/
contract SymBtc {
/// ** TYPES **
type BtcInputIndex is uint32;
/// ** STRUCTS **
struct FromBTCTransactionTail {
address receiveSide;
bytes receiveSideCalldata;
uint256 receiveSideOffset;
}
/// ** FIELDS **
SynthesisBTC public immutable synthesis;
BridgeV2 public immutable bridge;
address public immutable btcTokenAddress; // address mock for token from btc
uint256 public immutable btcChainId; // chainId mock for BTC network
constructor(
address _bridgeAddress,
address _synthesisAddress,
address _tokenAddress,
uint256 _chainId
) {
bridge = BridgeV2(_bridgeAddress);
synthesis = SynthesisBTC(_synthesisAddress);
btcTokenAddress = _tokenAddress;
btcChainId = _chainId;
}
function getSyntToken() external view returns (SyntERC20) {
address _sToken = ISyntFabric(synthesis.fabric()).getSyntRepresentation(
btcTokenAddress,
btcChainId
);
return SyntERC20(_sToken);
}
function getBtcTotalSupply() external view returns (uint256) {
return this.getSyntToken().totalSupply();
}
function getHashBTC(
bytes32 _btcTxId,
BtcInputIndex _inputIndex,
BtcSerial _wrapSerial,
uint256 _stableBridgingFee,
uint256 _amount,
address _to,
FromBTCTransactionTail memory _transactionTail) external view returns (bytes32) {
return bridge.getRequestHash(this.getBTCCalldata(
_btcTxId,
_inputIndex,
_wrapSerial,
_stableBridgingFee,
_amount,
_to,
_transactionTail
), address(synthesis));
}
function mpc() external view returns (address) {
return bridge.mpc();
}
function unpackBTCTransactionTail(bytes memory _transactionTail) public pure returns (FromBTCTransactionTail memory) {
return abi.decode(_transactionTail, (FromBTCTransactionTail));
}
function packBTCTransactionTail(FromBTCTransactionTail memory _transactionTail) public pure returns (bytes memory) {
return abi.encode(_transactionTail);
}
function getBTCInternalID(
bytes32 _btcTxId,
BtcInputIndex _inputIndex
) external pure returns (bytes32) {
return keccak256(abi.encodePacked(_btcTxId, _inputIndex));
}
function getBTCExternalID(
bytes32 _btcTxId,
BtcInputIndex _inputIndex,
address _receiveSide
) external view returns (bytes32) {
return keccak256(abi.encodePacked(this.getBTCInternalID(_btcTxId, _inputIndex), _receiveSide, btcChainId));
}
function getBTCCalldata(
bytes32 _btcTxId, // reveal tx id
BtcInputIndex _inputIndex, // input index in the reveal tx
BtcSerial _wrapSerial,
uint256 _stableBridgingFee, // fee passed by reveal tx
uint256 _amount, // input size
address _to, // receiver address
FromBTCTransactionTail memory _tail
) external view returns (bytes memory) {
MetaRouteStructs.MetaMintTransactionBTC
memory _metaMintTransactionBTC = MetaRouteStructs.MetaMintTransactionBTC(
_stableBridgingFee,
_amount,
_wrapSerial,
this.getBTCInternalID(_btcTxId, _inputIndex),
this.getBTCExternalID(_btcTxId, _inputIndex, address(synthesis)),
btcTokenAddress,
btcChainId,
_to,
_tail.receiveSide,
_tail.receiveSideCalldata,
_tail.receiveSideOffset
);
return abi.encodeCall(SynthesisBTC.metaMintSyntheticTokenBTC, (_metaMintTransactionBTC));
}
}
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
@openzeppelin/contracts/utils/Counters.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
@uniswap/lib/contracts/libraries/TransferHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
contracts/emergency/ISafeMode.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
/**
* @title ISafeMode
* @notice Read interface of the Pauser
*/
interface ISafeMode {
/**
* @notice Returns true while the protocol is paused on this chain
*/
function isPaused() external view returns (bool);
/**
* @notice Pause expiry; stays in the past once it lapses, 0 after unpause
*/
function pausedUntil() external view returns (uint64);
}
contracts/emergency/SafeModeGuarded.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.10;
import "./ISafeMode.sol";
/**
* @title SafeModeGuarded
* @notice Lets a contract be stopped by the chain's Pauser.
* @dev The read fails open: an unset, non-contract or reverting Pauser leaves the contract
* running, so every new address goes through `_requireUsablePauser`. Holds no storage, so it can be added to deployed
* upgradeable contracts; consumers append the pauser slot to their own layout.
*/
abstract contract SafeModeGuarded {
event SetPauser(address pauser);
modifier whenNotSafeMode() {
require(!safeMode(), "Symb: safe mode");
_;
}
/**
* @notice Returns true while the chain's Pauser reports safe mode
*/
function safeMode() public view returns (bool) {
address pauser = _pauser();
if (pauser == address(0)) {
return false;
}
(bool success, bytes memory data) = pauser.staticcall(
abi.encodeWithSelector(ISafeMode.isPaused.selector)
);
if (!success || data.length < 32) {
return false;
}
return abi.decode(data, (bool));
}
/**
* @dev Pauser this contract obeys, zero when safe mode is not wired up
*/
function _pauser() internal view virtual returns (address);
/**
* @dev Accepts zero, which disables safe mode, or a contract answering the Pauser reads
*/
function _requireUsablePauser(address _newPauser) internal view {
if (_newPauser == address(0)) {
return;
}
require(_newPauser.code.length > 0, "Symb: pauser is not a contract");
ISafeMode(_newPauser).isPaused();
ISafeMode(_newPauser).pausedUntil();
}
}
contracts/synth-core/SyntERC20.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
// Synthesis must be owner of this contract
contract SyntERC20 is Ownable, ERC20Permit {
uint8 private immutable _decimals;
function mint(address account, uint256 amount) external onlyOwner {
_mint(account, amount);
}
function burn(address account, uint256 amount) external onlyOwner {
_burn(account, amount);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
constructor(string memory name_, string memory symbol_, uint8 decimals_)
ERC20Permit("Symbiosis")
ERC20(name_, symbol_) {
_decimals = decimals_;
}
}contracts/synth-core/SyntFabric.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
pragma abicoder v1;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./SyntERC20.sol";
import "./interfaces/ISyntFabric.sol";
/**
* @title A contract that keeps correspondences between the addresses of real assets of their synthetic representations
* @dev All function calls are currently implemented without side effects
* @dev New synth representations can be created by both the factory admin and the creators of the original tokens
*/
contract SyntFabric is OwnableUpgradeable, ISyntFabric {
/// ** PUBLIC states **
address public synthesis;
mapping(bytes32 => address) internal representationSynt;
mapping(address => address) internal representationReal;
/// ** EVENTS **
event RepresentationCreated(
address rToken,
uint256 chainID,
address sToken
);
event RepresentationDeleted(
address sToken
);
event RepresentationSet(
address sToken,
address rToken
);
/// ** MODIFIERs **
modifier onlySynthesis() {
require(msg.sender == synthesis, "Symb: caller is not the synthesis");
_;
}
/// ** INITIALIZER **
function initialize(address _synthesis) public virtual initializer {
__Context_init();
__Ownable_init();
synthesis = _synthesis;
}
/// ** PUBLIC functions **
/**
* @return address of synt representation
* @param _key of hashed realTokenAdr and chainID
*/
function getSyntRepresentationByKey(bytes32 _key)
public
view
returns (address)
{
return representationSynt[_key];
}
/**
* @return address of synt representation
* @param _realTokenAdr address of real token
* @param _chainID Chain id of the network
*/
function getSyntRepresentation(address _realTokenAdr, uint256 _chainID)
public
view
override
returns (address)
{
return
representationSynt[
keccak256(abi.encodePacked(_realTokenAdr, _chainID))
];
}
/**
* @return address of real representation
* @param _syntTokenAdr address of synt token
*/
function getRealRepresentation(address _syntTokenAdr)
public
view
override
returns (address)
{
return representationReal[_syntTokenAdr];
}
/// ** EXTERNAL functions **
/**
* @notice Burns synthetic tokens
*/
function unsynthesize(
address _to,
uint256 _amount,
address _stoken
) external override onlySynthesis {
SyntERC20(_stoken).burn(_to, _amount);
}
/**
* @notice Mints synthetic tokens
*/
function synthesize(
address _to,
uint256 _amount,
address _stoken
) external override onlySynthesis {
SyntERC20(_stoken).mint(_to, _amount);
}
/// ** ONLYOWNER functions **
/**
* @notice function for creation representation by admin
* @param _rtoken address of real token
* @param _chainID Chain id of the network
* @param _stokenName Name of synthetic token
* @param _stokenSymbol Symbol for synthetic token
* @param _decimals Decimals value for synthetic token
*/
function createRepresentationByAdmin(
address _rtoken,
uint256 _chainID,
string memory _stokenName,
string memory _stokenSymbol,
uint8 _decimals
) external onlyOwner {
setRepresentation(
_rtoken,
_chainID,
_stokenName,
_stokenSymbol,
_decimals
);
}
/**
* @notice function for deleting representation by admin
* @param _sToken address of synthetic token
* @param _chainID Chain id of the network
*/
function deleteRepresentationByAdmin(
address _sToken,
uint256 _chainID
) external onlyOwner {
address rtoken = representationReal[_sToken];
representationReal[_sToken] = address(0);
representationSynt[keccak256(abi.encodePacked(rtoken, _chainID))] = address(0);
emit RepresentationDeleted(_sToken);
}
/**
* @notice function for changing representation by admin
* @param _sToken address of synthetic token
* @param _newRtoken address of new real token
* @param _chainID Chain id of the network
*/
function setRepresentationByAdmin(
address _sToken,
address _newRtoken,
uint256 _chainID
) external onlyOwner {
require(_newRtoken != address(0), "Symb: rtoken is the zero address");
require(
representationReal[_sToken] == address(0x0),
"Symb: token representation already set"
);
representationReal[_sToken] = _newRtoken;
representationSynt[keccak256(abi.encodePacked(_newRtoken, _chainID))] = _sToken;
emit RepresentationSet(_sToken, _newRtoken);
}
/// ** INTERNAL functions **
/**
* @dev Sets representation
* @dev Internal function used in createRepresentationByAdmin
*/
function setRepresentation(
address _rtoken,
uint256 _chainID,
string memory _stokenName,
string memory _stokenSymbol,
uint8 _decimals
) internal {
require(_rtoken != address(0), "Symb: rtoken is the zero address");
address stoken = getSyntRepresentation(_rtoken, _chainID);
require(
stoken == address(0x0),
"Symb: token representation already exists"
);
SyntERC20 syntToken = new SyntERC20(
_stokenName,
_stokenSymbol,
_decimals
);
representationReal[address(syntToken)] = _rtoken;
representationSynt[
keccak256(abi.encodePacked(_rtoken, _chainID))
] = address(syntToken);
emit RepresentationCreated(_rtoken, _chainID, address(syntToken));
}
}
contracts/synth-core/SynthesisBTC.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IBridge.sol";
import "./interfaces/ISyntFabric.sol";
import "../utils/RelayRecipientUpgradeable.sol";
import "./metarouter/interfaces/IMetaRouter.sol";
import "./types/BtcSerial.sol";
import "../emergency/SafeModeGuarded.sol";
/**
* @title A contract that mints and burns synthetic representations of BTC
* @dev Split out of Synthesis. BTC requests carry no revert path: a mint is final once its serial
* has been consumed, and a burn is final once the bridge has emitted it. Mints and burns are ordered
* per real token by two serials, one per direction, so the relayer can neither skip nor replay a request.
* The contract mints and burns through its own SyntFabric, deployed with this contract as its synthesis
*/
contract SynthesisBTC is RelayRecipientUpgradeable, SafeModeGuarded {
/// ** PUBLIC states **
bool public paused;
address public bridge;
address public fabric;
IMetaRouter public metaRouter;
mapping(bytes32 => SynthesizeState) public synthesizeStates;
/// @notice minimal amount of a synt a single burn may carry
mapping(address => uint256) public tokenThreshold;
/// @notice minimal bridging fee per synt (satoshi)
mapping(address => uint256) public syntToMinFeeBTC;
/// @notice serial the next mint of a real token must carry
mapping(address => BtcSerial) public realToMintSerialBTC;
/// @notice serial of the last burn of a real token
mapping(address => BtcSerial) public realToBurnSerialBTC;
/// @notice max total supply per synt, 0 disables
mapping(address => uint256) public mintCap;
/// @dev must stay last in the storage layout
address public pauser;
/// ** STRUCTS **
/// @dev same shape as in Synthesis, so the getter keeps its signature; BTC mints never revert,
/// so only Default and Synthesized occur here
enum SynthesizeState {
Default,
Synthesized,
RevertRequest
}
/// ** EVENTS **
event BurnRequestBTC(
BtcSerial burnSerial,
address indexed from,
bytes to,
uint256 amount,
uint256 stableBridgingFee,
address indexed rtoken
);
event ClientIdLogBTC(BtcSerial burnSerial, bytes32 indexed clientId);
event SynthesizeCompleted(
bytes32 indexed id,
address indexed to,
bytes32 indexed crossChainID,
uint256 amount,
uint256 bridgingFee,
address token
);
event BTCSynthesizeCompleted(
bytes32 indexed id,
address indexed to,
uint256 amount,
BtcSerial serial,
uint256 bridgingFee,
address indexed token
);
event Paused(address account);
event Unpaused(address account);
event SetTokenThreshold(address token, uint256 threshold);
event SetMetaRouter(address metaRouter);
event SetFabric(address fabric);
event SetBridge(address bridge);
event SetMinFeeBTC(uint256 minFee);
event SetMintCap(address stoken, uint256 cap);
/// ** MODIFIERs **
modifier onlyBridge() {
require(bridge == msg.sender, "Symb: caller is not the bridge");
_;
}
/// @dev checks both the local `paused` flag and the chain's safe mode
modifier whenRunning() {
require(!paused, "Symb: paused");
require(!safeMode(), "Symb: safe mode");
_;
}
/// ** INITIALIZER **
/**
* init
*/
function initialize(
address _bridge,
address _trustedForwarder,
IMetaRouter _metaRouter
)
public
virtual
initializer
{
__Context_init();
__RelayRecipient_init(_trustedForwarder);
// the same events the setters emit, so the settings' history starts here
bridge = _bridge;
emit SetBridge(_bridge);
metaRouter = _metaRouter;
emit SetMetaRouter(address(_metaRouter));
}
/// ** EXTERNAL PURE functions **
/**
* @notice Returns version
*/
function versionRecipient() external pure returns (string memory) {
return "1.0.0";
}
/// ** EXTERNAL functions **
/**
* @notice Mints the synt for a BTC deposit and runs the final call, if any
* @dev Can called only by bridge after the deposit was observed on the BTC side. Mints are
* sequential per real token: the request must carry the serial this contract expects next
* @param _metaMintTransaction metaMint offchain transaction data
*/
function metaMintSyntheticTokenBTC(
MetaRouteStructs.MetaMintTransactionBTC memory _metaMintTransaction
) external onlyBridge whenRunning {
require(
synthesizeStates[_metaMintTransaction.externalID] ==
SynthesizeState.Default,
"Symb: revertSynthesizedRequest called or tokens have been already synthesized"
);
synthesizeStates[_metaMintTransaction.externalID] = SynthesizeState
.Synthesized;
address syntReprAddr = ISyntFabric(fabric).getSyntRepresentation(
_metaMintTransaction.tokenReal,
_metaMintTransaction.chainID
);
require(syntReprAddr != address(0), "Symb: There is no synt representation for this token");
require(realToMintSerialBTC[_metaMintTransaction.tokenReal] == _metaMintTransaction.serial, "Symb: nonsequential mint serial");
realToMintSerialBTC[_metaMintTransaction.tokenReal] = _metaMintTransaction.serial.inc();
ISyntFabric(fabric).synthesize(
address(this),
_metaMintTransaction.amount - _metaMintTransaction.stableBridgingFee,
syntReprAddr
);
ISyntFabric(fabric).synthesize(
bridge,
_metaMintTransaction.stableBridgingFee,
syntReprAddr
);
// This event should be emitted each time BTC is synthesized
emit BTCSynthesizeCompleted(
_metaMintTransaction.externalID,
_metaMintTransaction.to,
_metaMintTransaction.amount,
_metaMintTransaction.serial,
_metaMintTransaction.stableBridgingFee,
_metaMintTransaction.tokenReal);
_metaMintTransaction.amount = _metaMintTransaction.amount - _metaMintTransaction.stableBridgingFee;
// This event should be emitted each time tokens are synthesized, on both paths below
emit SynthesizeCompleted(
_metaMintTransaction.externalID,
_metaMintTransaction.to,
_metaMintTransaction.crossChainID,
_metaMintTransaction.amount,
_metaMintTransaction.stableBridgingFee,
address(0));
// single exit, so the cap check covers both paths
if (_metaMintTransaction.receiveSideCalldata.length == 0) {
TransferHelper.safeTransfer(
syntReprAddr,
_metaMintTransaction.to,
_metaMintTransaction.amount
);
} else {
// transfer ERC20 tokens to MetaRouter
TransferHelper.safeTransfer(
syntReprAddr,
address(metaRouter),
_metaMintTransaction.amount
);
// metaRouter final call; if it fails, the synt is sent to the recipient as is
try metaRouter.externalCall(
syntReprAddr,
_metaMintTransaction.amount,
_metaMintTransaction.receiveSide,
_metaMintTransaction.receiveSideCalldata,
_metaMintTransaction.receiveSideOffset,
_metaMintTransaction.to
) {
} catch {
metaRouter.sendTransitToken(syntReprAddr, _metaMintTransaction.to, _metaMintTransaction.amount);
}
}
_requireMintCap(syntReprAddr);
}
/**
* @notice Sends burn request to BTC
* @dev sToken -> BTC. The bridging fee is minted to the bridge, the rest is released on the BTC side
* @param _stableBridgingFee Bridging fee (satoshi)
* @param _amount Number of tokens to burn
* @param _to BTC address to which the user wants to receive bitcoins
* @param _stoken SyntERC20 token
* @param _clientID Client id, passed through to the event
*/
function burnSyntheticTokenBTC(
uint256 _stableBridgingFee,
uint256 _amount,
bytes calldata _to,
address _stoken,
bytes32 _clientID
) external whenRunning returns (BtcSerial) {
return _burn(_msgSender(), _stableBridgingFee, _amount, _to, _stoken, _clientID);
}
/**
* @notice Sends burn request to BTC on behalf of a user
* @dev Owner only. Burns the user's synts, the user needs no approval
* @param _user Address whose synts are burned
* @param _stableBridgingFee Bridging fee (satoshi)
* @param _amount Number of tokens to burn
* @param _to BTC address to which the user wants to receive bitcoins
* @param _stoken SyntERC20 token
* @param _clientID Client id, passed through to the event
*/
function burnSyntheticTokenBTCByAdmin(
address _user,
uint256 _stableBridgingFee,
uint256 _amount,
bytes calldata _to,
address _stoken,
bytes32 _clientID
) external whenRunning onlyOwner returns (BtcSerial) {
return _burn(_user, _stableBridgingFee, _amount, _to, _stoken, _clientID);
}
/// ** INTERNAL functions **
/**
* @dev Burns `_from`'s synts and hands the request to the bridge under the next burn serial
*/
function _burn(
address _from,
uint256 _stableBridgingFee,
uint256 _amount,
bytes calldata _to,
address _stoken,
bytes32 _clientID
) internal returns (BtcSerial burnSerial) {
require(_amount >= tokenThreshold[_stoken], "Symb: amount under threshold");
require(syntToMinFeeBTC[_stoken] <= _stableBridgingFee, "Symb: insufficient fee");
ISyntFabric(fabric).unsynthesize(_from, _amount, _stoken);
ISyntFabric(fabric).synthesize(bridge, _stableBridgingFee, _stoken);
address rtoken = ISyntFabric(fabric).getRealRepresentation(_stoken);
require(rtoken != address(0), "Symb: incorrect synt");
burnSerial = realToBurnSerialBTC[rtoken].inc();
realToBurnSerialBTC[rtoken] = burnSerial;
IBridge(bridge).transmitRequestBTC(
_from,
_to,
_amount - _stableBridgingFee,
burnSerial
);
emit BurnRequestBTC(burnSerial, _from, _to, _amount - _stableBridgingFee, _stableBridgingFee, rtoken);
emit ClientIdLogBTC(burnSerial, _clientID);
}
/**
* @dev Reverts if the total supply of `_stoken` exceeds its cap, a zero cap is off. Called at
* the end of the mint path; burns skip it, they never raise the supply
*/
function _requireMintCap(address _stoken) internal view {
uint256 cap = mintCap[_stoken];
require(
cap == 0 || IERC20(_stoken).totalSupply() <= cap,
"Symb: mint cap"
);
}
/// ** ONLYOWNER functions **
/**
* @notice Sets the total supply a synt may never exceed
* @dev Zero disables the cap
* @param _stoken Address of the synt to set the cap for
* @param _cap Cap to set
*/
function setMintCap(address _stoken, uint256 _cap) external onlyOwner {
mintCap[_stoken] = _cap;
emit SetMintCap(_stoken, _cap);
}
/**
* @notice Set paused flag to true
*/
function pause() external onlyOwner {
paused = true;
emit Paused(_msgSender());
}
/**
* @notice Set paused flag to false
*/
function unpause() external onlyOwner {
paused = false;
emit Unpaused(_msgSender());
}
/**
* @notice Sets the Pauser this contract obeys
* @dev Zero disables safe mode, any other address must be a working Pauser
*/
function setPauser(address _newPauser) external onlyOwner {
_requireUsablePauser(_newPauser);
pauser = _newPauser;
emit SetPauser(_newPauser);
}
/**
* @dev Hands the Pauser address to SafeModeGuarded
*/
function _pauser() internal view override returns (address) {
return pauser;
}
/**
* @notice Sets minimal fee for btc burn
* @param _synt to set fee for
* @param _minFee new fee value (satoshi)
*/
function setMinFeeBTC(address _synt, uint256 _minFee) external onlyOwner {
syntToMinFeeBTC[_synt] = _minFee;
emit SetMinFeeBTC(_minFee);
}
/**
* @notice Sets the minimal amount of a synt a single burn may carry
* @param _token Address of token to set threshold
* @param _threshold minimal amount to set
*/
function setTokenThreshold(address _token, uint256 _threshold) external onlyOwner {
tokenThreshold[_token] = _threshold;
emit SetTokenThreshold(_token, _threshold);
}
/**
* @notice Sets MetaRouter address
* @param _metaRouter Address of metaRouter
*/
function setMetaRouter(IMetaRouter _metaRouter) external onlyOwner {
require(address(_metaRouter) != address(0), "Symb: metaRouter cannot be zero address");
metaRouter = _metaRouter;
emit SetMetaRouter(address(_metaRouter));
}
/**
* @notice Sets Fabric address
* @dev Once: the fabric is deployed after this contract, with this contract as its synthesis
* @param _fabric Address of fabric
*/
function setFabric(address _fabric) external onlyOwner {
require(fabric == address(0x0), "Symb: Fabric already set");
fabric = _fabric;
emit SetFabric(_fabric);
}
/**
* @notice Moves this contract to another bridge: the one whose MPC-signed requests mint,
* which takes the bridging fees and hands the burns on to the BTC side
* @dev The serials stay, so a running portal goes on through the new bridge, which must
* make this contract a transmitter. Only while paused: a mint signed for the old bridge
* does not verify on the new one, and a burn in flight was emitted by the old one, so
* both are settled first. An upgrade by the ProxyAdmin's owner could move the bridge too,
* so the two owners must be the same party
* @param _bridge Address of the new bridge
*/
function setBridge(address _bridge) external onlyOwner {
require(paused, "Symb: pause before moving the bridge");
require(_bridge != address(0), "Symb: bridge cannot be zero address");
bridge = _bridge;
emit SetBridge(_bridge);
}
}
contracts/synth-core/bridge/BridgeV2.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "../../utils/AdminableUpgradeable.sol";
import "../../utils/RevertMessageParser.sol";
import "../metarouter/MetaRouteStructs.sol";
import "../../emergency/SafeModeGuarded.sol";
contract BridgeV2 is Initializable, AdminableUpgradeable, SafeModeGuarded {
/// ** PUBLIC states **
address public newMPC;
address public oldMPC;
uint256 public newMPCEffectiveTime;
mapping(address => bool) public isTransmitter;
/// @dev must stay last in the storage layout
address public pauser;
/// ** EVENTS **
event LogChangeMPC(
address indexed oldMPC,
address indexed newMPC,
uint256 indexed effectiveTime,
uint256 chainId
);
event SetTransmitterStatus(address indexed transmitter, bool status);
event OracleRequest(
address bridge,
bytes callData,
address receiveSide,
address oppositeBridge,
uint256 chainId
);
event OracleRequestBTC(
address bridge,
address from,
bytes to,
uint256 amount,
BtcSerial burnSerial
);
/// ** MODIFIERs **
modifier onlyMPC() {
require(msg.sender == mpc(), "BridgeV2: forbidden");
_;
}
modifier onlyTransmitter() {
require(isTransmitter[msg.sender], "BridgeV2: not a transmitter");
_;
}
modifier onlyOwnerOrMPC() {
require(
mpc() == msg.sender || owner() == msg.sender,
"BridgeV2: only owner or MPC can call"
);
_;
}
modifier onlySignedByMPC(bytes32 hash, bytes memory signature) {
require(SignatureChecker.isValidSignatureNow(mpc(), hash, signature), "BridgeV2: invalid signature");
_;
}
/// @dev the bridge has no local `paused` flag, so only safe mode is checked
modifier whenRunning() {
require(!safeMode(), "Symb: safe mode");
_;
}
/// ** INITIALIZER **
function initialize(address _mpc) public virtual initializer {
__Context_init();
__Adminable_init();
newMPC = _mpc;
newMPCEffectiveTime = block.timestamp;
}
/// ** VIEW functions **
function getRequestHash(bytes memory _callData, address _receiveSide) external view returns (bytes32) {
return keccak256(bytes.concat("receiveRequestV2", _callData, bytes20(_receiveSide), bytes32(block.chainid), bytes20(address(this))));
}
function getMpcHash(address _newMPC) external view returns (bytes32) {
return keccak256(bytes.concat("changeMPC", bytes20(_newMPC), bytes32(block.chainid), bytes20(address(this))));
}
/**
* @notice Returns MPC
*/
function mpc() public view returns (address) {
if (block.timestamp >= newMPCEffectiveTime) {
return newMPC;
}
return oldMPC;
}
/**
* @notice Returns chain ID of block
*/
function currentChainId() public view returns (uint256) {
return block.chainid;
}
/// ** MPC functions **
/**
* @notice Receives requests
*/
function receiveRequestV2(bytes memory _callData, address _receiveSide)
external
onlyMPC
whenRunning
{
_processRequest(_callData, _receiveSide);
}
/**
* @notice Receives requests
*/
function receiveRequestV2Signed(bytes memory _callData, address _receiveSide, bytes memory signature)
external
onlySignedByMPC(this.getRequestHash(_callData, _receiveSide), signature)
whenRunning
{
_processRequest(_callData, _receiveSide);
}
/// ** TRANSMITTER functions **
/**
* @notice transmits request
*/
function transmitRequestV2(
bytes memory _callData,
address _receiveSide,
address _oppositeBridge,
uint256 _chainId
) public onlyTransmitter whenRunning {
emit OracleRequest(
address(this),
_callData,
_receiveSide,
_oppositeBridge,
_chainId
);
}
/**
* @notice transmits request
*/
function transmitRequestBTC(
address _from,
bytes calldata _to,
uint256 _amount,
BtcSerial _burnSerial
) public onlyTransmitter whenRunning {
emit OracleRequestBTC(
address(this),
_from,
_to,
_amount,
_burnSerial
);
}
/// ** OWNER functions **
/**
* @notice Sets the Pauser this contract obeys
* @dev Zero disables safe mode, any other address must be a working Pauser
*/
function setPauser(address _newPauser) external onlyOwner {
_requireUsablePauser(_newPauser);
pauser = _newPauser;
emit SetPauser(_newPauser);
}
/**
* @notice Sets transmitter status
*/
function setTransmitterStatus(address _transmitter, bool _status)
external
onlyOwner
{
isTransmitter[_transmitter] = _status;
emit SetTransmitterStatus(_transmitter, _status);
}
/**
* @notice Changes MPC by owner or MPC
*/
function changeMPC(address _newMPC) external onlyOwnerOrMPC returns (bool) {
return _changeMPC(_newMPC);
}
/**
* @notice Changes MPC with signature
*/
function changeMPCSigned(address _newMPC, bytes memory signature)
external
onlySignedByMPC(this.getMpcHash(_newMPC), signature)
returns (bool)
{
return _changeMPC(_newMPC);
}
/**
* @notice Withdraw fee by owner or admin
*/
function withdrawFee(address token, address to, uint256 amount) external onlyOwnerOrAdmin returns (bool) {
TransferHelper.safeTransfer(token, to, amount);
return true;
}
/// ** Internal functions **
/**
* @dev Hands the Pauser address to SafeModeGuarded
*/
function _pauser() internal view override returns (address) {
return pauser;
}
/// ** Private functions **
/**
* @notice Private function that handles request processing
*/
function _processRequest(bytes memory _callData, address _receiveSide)
private
{
require(isTransmitter[_receiveSide], "BridgeV2: untrusted transmitter");
(bool success, bytes memory data) = _receiveSide.call(_callData);
if (!success) {
revert(RevertMessageParser.getRevertMessage(data, "BridgeV2: call failed"));
}
}
/**
* @notice Private function that changes MPC
*/
function _changeMPC(address _newMPC) private returns (bool) {
require(_newMPC != address(0), "BridgeV2: address(0x0)");
oldMPC = mpc();
newMPC = _newMPC;
newMPCEffectiveTime = block.timestamp;
emit LogChangeMPC(
oldMPC,
newMPC,
newMPCEffectiveTime,
currentChainId()
);
return true;
}
}
contracts/synth-core/interfaces/IBridge.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "../types/BtcSerial.sol";
interface IBridge {
function transmitRequestV2(
bytes memory _callData,
address _receiveSide,
address _oppositeBridge,
uint256 _chainId
) external;
function transmitRequestBTC(
address _from,
bytes calldata _to,
uint256 _amount,
BtcSerial _burnSerial
) external;
function receiveRequestV2(
bytes memory _callData,
address _receiveSide
) external;
}
contracts/synth-core/interfaces/ISyntFabric.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
interface ISyntFabric {
function getRealRepresentation(address _syntTokenAdr)
external
view
returns (address);
function getSyntRepresentation(address _realTokenAdr, uint256 _chainID)
external
view
returns (address);
function synthesize(
address _to,
uint256 _amount,
address _stoken
) external;
function unsynthesize(
address _to,
uint256 _amount,
address _stoken
) external;
}
contracts/synth-core/metarouter/MetaRouteStructs.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "../types/BtcSerial.sol";
library MetaRouteStructs {
struct MetaBurnTransaction {
uint256 stableBridgingFee;
uint256 amount;
bytes32 crossChainID;
address syntCaller;
address finalReceiveSide;
address sToken;
bytes finalCallData;
uint256 finalOffset;
address chain2address;
address receiveSide;
address oppositeBridge;
address revertableAddress;
uint256 chainID;
bytes32 clientID;
}
struct MetaMintTransaction {
uint256 stableBridgingFee;
uint256 amount;
bytes32 crossChainID;
bytes32 externalID;
address tokenReal;
uint256 chainID;
address to;
address[] swapTokens;
address secondDexRouter;
bytes secondSwapCalldata;
address finalReceiveSide;
bytes finalCalldata;
uint256 finalOffset;
}
struct MetaMintTransactionBTC {
uint256 stableBridgingFee;
uint256 amount;
BtcSerial serial;
bytes32 crossChainID;
bytes32 externalID;
address tokenReal;
uint256 chainID;
address to;
address receiveSide;
bytes receiveSideCalldata;
uint256 receiveSideOffset;
}
struct MetaRouteTransaction {
bytes firstSwapCalldata;
bytes secondSwapCalldata;
address[] approvedTokens;
address firstDexRouter;
address secondDexRouter;
uint256 amount;
bool nativeIn;
address relayRecipient;
bytes otherSideCalldata;
}
struct MetaSynthesizeTransaction {
uint256 stableBridgingFee;
uint256 amount;
address rtoken;
address chain2address;
address receiveSide;
address oppositeBridge;
address syntCaller;
uint256 chainID;
address[] swapTokens;
address secondDexRouter;
bytes secondSwapCalldata;
address finalReceiveSide;
bytes finalCalldata;
uint256 finalOffset;
address revertableAddress;
bytes32 clientID;
}}
contracts/synth-core/metarouter/interfaces/IMetaRouter.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "../MetaRouteStructs.sol";
interface IMetaRouter {
function metaRoute(
MetaRouteStructs.MetaRouteTransaction calldata _metarouteTransaction
) external payable;
function externalCall(
address _token,
uint256 _amount,
address _receiveSide,
bytes calldata _calldata,
uint256 _offset,
address _revertableAddress
) external;
function metaMintSwap(
MetaRouteStructs.MetaMintTransaction calldata _metaMintTransaction
) external;
function metaMintCallBTC(
address _token,
uint256 _amount,
address _receiveSide,
bytes calldata _calldata,
uint256 _offset,
address _to
) external;
function sendTransitToken(address _token, address _to, uint256 _amount) external;
}
contracts/synth-core/types/BtcSerial.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;
type BtcSerial is uint64;
using {inc, equal as ==} for BtcSerial global;
function inc(BtcSerial a) pure returns (BtcSerial) {
return BtcSerial.wrap(BtcSerial.unwrap(a) + 1);
}
function equal(BtcSerial a, BtcSerial b) pure returns (bool) {
return BtcSerial.unwrap(a) == BtcSerial.unwrap(b);
}
contracts/utils/AdminableUpgradeable.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
abstract contract AdminableUpgradeable is OwnableUpgradeable {
mapping(address => bool) public isAdmin;
event SetAdminPermission(address indexed admin, bool permission);
modifier onlyAdmin {
require(isAdmin[msg.sender], "Only admin can call");
_;
}
modifier onlyOwnerOrAdmin {
require((owner() == msg.sender) || isAdmin[msg.sender], "Only owner or admin can call");
_;
}
function __Adminable_init() internal onlyInitializing {
__Ownable_init();
}
function setAdminPermission(address _user, bool _permission) external onlyOwner {
isAdmin[_user] = _permission;
emit SetAdminPermission(_user, _permission);
}
}contracts/utils/RelayRecipientUpgradeable.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
abstract contract RelayRecipientUpgradeable is OwnableUpgradeable {
address private _trustedForwarder;
function __RelayRecipient_init(address trustedForwarder)
internal
onlyInitializing
{
__Ownable_init();
_trustedForwarder = trustedForwarder;
}
function isTrustedForwarder(address forwarder)
public
view
virtual
returns (bool)
{
return forwarder == _trustedForwarder;
}
function _msgSender()
internal
view
virtual
override
returns (address sender)
{
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData()
internal
view
virtual
override
returns (bytes calldata)
{
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
} else {
return super._msgData();
}
}
}
contracts/utils/RevertMessageParser.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
library RevertMessageParser {
function getRevertMessage(bytes memory _data, string memory _defaultMessage) internal pure returns (string memory) {
// If the _data length is less than 68, then the transaction failed silently (without a revert message)
if (_data.length < 68) return _defaultMessage;
assembly {
// Slice the sighash
_data := add(_data, 0x04)
}
return abi.decode(_data, (string));
}
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 2000,
"enabled": true
}
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.