Verified contractExactMIT
Redemption
Address0xc003be0faf0b06f66fdf8264540b6a1e2e93faa3
- Balance
0 ETH
- Transactions
824
- Compiler
solc 0.8.19
- Same code
Only this contract
Details
- Compiler
- solc 0.8.19+commit.7dd6d404
- Language
- solidity
- Optimization
- No
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 21,584,505
- Creation transaction
- 0xc94c4bd787…5d0017394e
7 files
- contracts/Redemption.solmain7.64 KB
- @openzeppelin/contracts/access/Ownable.sol2.62 KB
- @openzeppelin/contracts/security/Pausable.sol2.55 KB
- @openzeppelin/contracts/security/ReentrancyGuard.sol2.84 KB
- @openzeppelin/contracts/utils/Context.sol844 B
- contracts/interfaces/IERC20.sol2.39 KB
- contracts/libraries/BoringERC20.sol5.11 KB
contracts/Redemption.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./libraries/BoringERC20.sol";
/**
* @title Redemption
* @notice Allows users to redeem a specific ERC20 token (`fromToken`) for multiple other ERC20 tokens (`toTokens`) based on predefined exchange rates.
* @dev Inherits from Ownable, Pausable, and ReentrancyGuard for access control, pausing functionality, and security against reentrancy attacks.
*/
contract Redemption is Ownable, Pausable, ReentrancyGuard {
using BoringERC20 for IERC20;
/// @dev The ERC20 token users can redeem from.
IERC20 public fromToken;
/// @dev List of ERC20 tokens users can redeem to.
address[] public toTokens;
/// @dev Denominator based on the decimals of `fromToken` used for exchange rate calculations.
uint256 public immutable fromDenominator;
/// @dev Mapping from target token address to its exchange rate.
mapping(address => uint256) public exchangeRates;
/**
* @dev Emitted when a user redeems `fromToken` for a `toToken`.
* @param user The address of the user who performed the redemption.
* @param toToken The address of the token that was redeemed to.
* @param amount The amount of `toToken` redeemed.
*/
event Redeemed(
address indexed user,
address indexed toToken,
uint256 amount
);
/**
* @dev Emitted when a new token is added to the redemption list.
* @param token The address of the token that was added.
* @param exchangeRate The exchange rate set for the new token.
*/
event TokenAdded(address indexed token, uint256 exchangeRate);
/**
* @dev Emitted when a token is removed from the redemption list.
* @param token The address of the token that was removed.
*/
event TokenRemoved(address indexed token);
/**
* @dev Emitted when the exchange rate of a token is updated.
* @param token The address of the token whose exchange rate was changed.
* @param exchangeRate The new exchange rate of the token.
*/
event ExchangeRateChanged(address indexed token, uint256 exchangeRate);
/**
* @notice Initializes the Redemption contract with the specified tokens and their exchange rates.
* @param _fromToken The ERC20 token that users will redeem from.
* @param _toTokens An array of ERC20 token addresses that users can redeem to.
* @param _exchangeRates An array of exchange rates corresponding to each `toToken`.
*/
constructor(
IERC20 _fromToken,
address[] memory _toTokens,
uint256[] memory _exchangeRates
) {
require(
_toTokens.length == _exchangeRates.length,
"Array lengths must be equal"
);
fromToken = _fromToken;
fromDenominator = 10 ** fromToken.safeDecimals();
toTokens = _toTokens;
for (uint256 i = 0; i < toTokens.length; i++) {
require(_exchangeRates[i] > 0, "Invalid exchange rate");
exchangeRates[toTokens[i]] = _exchangeRates[i];
}
}
/**
* @notice Redeems a specified amount of `fromToken` for each supported `toToken`.
* @param amount The amount of `fromToken` to be redeemed.
* @dev Transfers `amount` of `fromToken` from the caller to the contract, then distributes equivalent `toTokens` based on exchange rates.
*/
function redeem(uint256 amount) public whenNotPaused nonReentrant {
require(
fromToken.safeBalanceOf(msg.sender) >= amount,
"Insufficient balance"
);
fromToken.safeTransferFrom(msg.sender, address(this), amount);
for (uint256 i = 0; i < toTokens.length; i++) {
uint256 toAmount = (amount * exchangeRates[toTokens[i]]) / fromDenominator;
require(toAmount > 0, "Amount not enough");
require(
IERC20(toTokens[i]).safeBalanceOf(address(this)) >= toAmount,
"Insufficient balance of contract"
);
IERC20(toTokens[i]).safeTransfer(msg.sender, toAmount);
emit Redeemed(msg.sender, toTokens[i], toAmount);
}
}
/**
* @notice Adds a new supported ERC20 token with its exchange rate.
* @param token The address of the token being added.
* @param exchangeRate The exchange rate of the new token.
* @dev Ensures the token is not already added and sets its exchange rate based on its decimals.
*/
function addToken(address token, uint256 exchangeRate) public onlyOwner {
require(token != address(0), "Token address cannot be zero");
require(exchangeRate > 0, "ExchangeRate cannot be 0");
require(exchangeRates[token] == 0, "Token already exists");
toTokens.push(token);
exchangeRates[token] = exchangeRate;
emit TokenAdded(token, exchangeRate);
}
/**
* @notice Removes a supported ERC20 token by its index.
* @param index The index of the token being removed.
* @dev Deletes the exchange rate and removes the token from the `toTokens` array.
*/
function removeToken(uint256 index) public onlyOwner {
address _token = toTokens[index];
delete exchangeRates[_token];
toTokens[index] = toTokens[toTokens.length - 1];
toTokens.pop();
emit TokenRemoved(_token);
}
/**
* @notice Sets the exchange rate for a supported ERC20 token.
* @param token The address of the token for which the exchange rate is being set.
* @param exchangeRate The new exchange rate of the token.
* @dev Updates the exchange rate based on the token's decimals.
*/
function setExchangeRate(
address token,
uint256 exchangeRate
) public onlyOwner {
require(exchangeRate > 0, "Token rate cannot be zero");
require(exchangeRates[token] > 0, "Token does not exist");
exchangeRates[token] = exchangeRate;
emit ExchangeRateChanged(token, exchangeRate);
}
/**
* @notice Toggles the paused state of the contract.
* @dev If the contract is paused, it will be unpaused and vice versa.
*/
function pause() public onlyOwner {
paused() ? _unpause() : _pause();
}
/**
* @notice Withdraws all of a specific ERC20 token to the owner in case of emergency.
* @param token The ERC20 token to withdraw.
* @dev Transfers the entire balance of the specified `token` to the contract owner.
*/
function emergencyWithdraw(IERC20 token) external onlyOwner {
token.safeTransfer(owner(), token.safeBalanceOf(address(this)));
}
/**
* @notice Calculates the amounts of each `toToken` that can be redeemed for a given `fromToken` amount.
* @param amount The amount of `fromToken` to be redeemed.
* @return address[] An array of `toToken` addresses.
* @return uint256[] An array of redeemable amounts for each `toToken`.
* @dev Ensures that each calculated redeemable amount is greater than zero.
*/
function calculateRedeem(
uint256 amount
) external view returns (address[] memory, uint256[] memory) {
uint[] memory toAmount = new uint[](toTokens.length);
for (uint256 i = 0; i < toTokens.length; i++) {
toAmount[i] = (amount * exchangeRates[toTokens[i]]) / fromDenominator;
require(toAmount[i] > 0, "Amount not enough");
}
return (toTokens, toAmount);
}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
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/security/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
@openzeppelin/contracts/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
@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;
}
}
contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC20 {
// transfer and tranferFrom have been removed, because they don't work on all tokens (some aren't ERC20 complaint).
// By removing them you can't accidentally use them.
// name, symbol and decimals have been removed, because they are optional and sometimes wrongly implemented (MKR).
// Use BoringERC20 with `using BoringERC20 for IERC20` and call `safeTransfer`, `safeTransferFrom`, etc instead.
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
interface IStrictERC20 {
// This is the strict ERC20 interface. Don't use this, certainly not if you don't control the ERC20 token you're calling.
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
contracts/libraries/BoringERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interfaces/IERC20.sol";
// solhint-disable avoid-low-level-calls
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_BALANCE_OF = 0x70a08231; // balanceOf(address)
bytes4 private constant SIG_TOTALSUPPLY = 0x18160ddd; // balanceOf(address)
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
function returnDataToString(bytes memory data) internal pure returns (string memory) {
if (data.length >= 64) {
return abi.decode(data, (string));
} else if (data.length == 32) {
uint8 i = 0;
while (i < 32 && data[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && data[i] != 0; i++) {
bytesArray[i] = data[i];
}
return string(bytesArray);
} else {
return "???";
}
}
/// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token symbol.
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.name version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token name.
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
/// @param token The address of the ERC-20 token contract.
/// @return (uint8) Token decimals.
function safeDecimals(IERC20 token) internal view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
/// @notice Provides a gas-optimized balance check to avoid a redundant extcodesize check in addition to the returndatasize check.
/// @param token The address of the ERC-20 token.
/// @param to The address of the user to check.
/// @return amount The token amount.
function safeBalanceOf(IERC20 token, address to) internal view returns (uint256 amount) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_BALANCE_OF, to));
require(success && data.length >= 32, "BoringERC20: BalanceOf failed");
amount = abi.decode(data, (uint256));
}
/// @notice Provides a gas-optimized totalSupply to avoid a redundant extcodesize check in addition to the returndatasize check.
/// @param token The address of the ERC-20 token.
/// @return totalSupply The token totalSupply.
function safeTotalSupply(IERC20 token) internal view returns (uint256 totalSupply) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_TOTALSUPPLY));
require(success && data.length >= 32, "BoringERC20: totalSupply failed");
totalSupply = abi.decode(data, (uint256));
}
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed");
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed");
}
}
Compiler settingsShow
{
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": false
}
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.