// SPDX-License-Identifier: AGPL-3.0-or-laterpragmasolidity ^0.8.20;import"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import"@openzeppelin/contracts/access/Ownable.sol";
import"@openzeppelin/contracts/utils/Address.sol";
/**
* @notice This contract handles the adjustable swap of the ABI ERC20 token for the USDC ERC20 token.
*/contractAbachiRedemptionisOwnable{
usingAddressforaddress;
IERC20 public ABI;
IERC20 public USDC;
boolpublic paused =false;
uint256public swapRatio =23; // Default to 1 ABI = 1.7 USDCuint256publicconstant RATIO_DIVISOR =10;
uint8publicconstant USDC_DECIMALS =6; // USDC uses 6 decimalsuint8publicconstant ABI_DECIMALS =18; // ABI uses 18 decimalseventSwap(addressindexed sender, addressindexed recipient, uint256 amountABI, uint256 amountUSDC);
eventRatioUpdated(uint256 newRatio);
eventRecoveredUSDC(addressindexed recipient, uint256 amount);
constructor(address _ABI, address _USDC) Ownable(msg.sender) {
ABI = IERC20(_ABI);
USDC = IERC20(_USDC);
}
/**
* @notice Pauses swapping, preventing any further calls to swap() from succeeding until
* unpause() is called.
*/functionpause() externalonlyOwner{
require(!paused, "Contract already paused");
paused =true;
}
/**
* @notice Unpauses swapping if it was paused previously.
*/functionunpause() externalonlyOwner{
require(paused, "Contract is not paused");
paused =false;
}
/**
* @notice Updates the swap ratio. Only callable by the contract owner.
* @param _newRatio The new swap ratio, where the ratio is (_newRatio / RATIO_DIVISOR).
* For example, 17 means 1 ABI = 1.7 USDC.
*/functionsetSwapRatio(uint256 _newRatio) externalonlyOwner{
require(_newRatio >0, "Ratio must be greater than zero");
swapRatio = _newRatio;
emit RatioUpdated(_newRatio);
}
/**
* @notice Swaps all the ABI held by the caller to USDC.
* Emits Swap event if the swap is successful.
*/functionswap() external{
uint256 balance = ABI.balanceOf(msg.sender);
_swapFor(msg.sender, balance);
}
/**
* @notice Deducts some ABI from the caller and transfers the corresponding amount of USDC to another account.
* @param _recipient Account that will receive the USDC tokens.
* @param _amount Amount of ABI tokens to swap.
*/functionswapFor(address _recipient, uint256 _amount) external{
_swapFor(_recipient, _amount);
}
/**
* @notice Transfers some ABI from the contract to another account.
* @param _recipient Account that will receive the ABI tokens.
* @param _amount Amount of ABI tokens to transfer.
*/functionwithdrawTo(address _recipient, uint256 _amount) externalonlyOwner{
require(ABI.transfer(_recipient, _amount), "Failed to transfer ABI");
}
/**
* @notice Recovers a specified amount of USDC from the contract. Only callable by the owner.
* @param _amount Amount of USDC to recover.
*/functionrecoverUSDC(uint256 _amount) externalonlyOwner{
require(_amount >0, "Amount must be greater than zero");
require(USDC.balanceOf(address(this)) >= _amount, "Insufficient USDC balance");
require(USDC.transfer(msg.sender, _amount), "Failed to transfer USDC");
emit RecoveredUSDC(msg.sender, _amount);
}
/**
* @notice View function to calculate how much USDC is given per ABI.
* @return The amount of USDC per ABI based on the current swap ratio.
*/functioncalculateUSDC(uint256 _amount) externalviewreturns (uint256) {
return (_amount * swapRatio *10**USDC_DECIMALS) / (10**ABI_DECIMALS * RATIO_DIVISOR);
}
functionsetUSDC(address _usdc) externalonlyOwner{
USDC = IERC20(_usdc);
}
functionsetABI(address _abi) externalonlyOwner{
ABI = IERC20(_abi);
}
function_swapFor(address _recipient, uint256 _amount) private{
require(!paused, "Contract is paused");
require(_amount >0, "Invalid ABI amount");
// Calculate the USDC amount based on the swap ratio, scaling for decimal differencesuint256 usdcAmount = (_amount * swapRatio *10**USDC_DECIMALS) / (10**ABI_DECIMALS * RATIO_DIVISOR);
// Perform the swaprequire(ABI.transferFrom(msg.sender, address(this), _amount), "Failed to transfer ABI");
require(USDC.transfer(_recipient, usdcAmount), "Failed to transfer USDC");
emit Swap(msg.sender, _recipient, _amount, usdcAmount);
}
}
Contract Source Code
File 2 of 6: Address.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)pragmasolidity ^0.8.20;import {Errors} from"./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev There's no code at `target` (it is not a contract).
*/errorAddressEmptyCode(address target);
/**
* @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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
if (address(this).balance< amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* 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.
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
if (address(this).balance< value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata
) internalviewreturns (bytesmemory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty// otherwise we already know that it was a contractif (returndata.length==0&& target.code.length==0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/functionverifyCallResult(bool success, bytesmemory returndata) internalpurereturns (bytesmemory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/function_revert(bytesmemory returndata) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assemblyassembly ("memory-safe") {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
Contract Source Code
File 3 of 6: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)pragmasolidity ^0.8.20;/**
* @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.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
function_contextSuffixLength() internalviewvirtualreturns (uint256) {
return0;
}
}
Contract Source Code
File 4 of 6: Errors.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)pragmasolidity ^0.8.20;/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/libraryErrors{
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/errorInsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/errorFailedCall();
/**
* @dev The deployment failed.
*/errorFailedDeployment();
/**
* @dev A necessary precompile is missing.
*/errorMissingPrecompile(address);
}
Contract Source Code
File 5 of 6: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.20;/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, uint256 value) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (uint256);
/**
* @dev Sets a `value` amount of tokens 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.
*/functionapprove(address spender, uint256 value) externalreturns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom, address to, uint256 value) externalreturns (bool);
}
Contract Source Code
File 6 of 6: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)pragmasolidity ^0.8.20;import {Context} from"../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.
*
* The initial owner is set to the address provided by the deployer. 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.
*/abstractcontractOwnableisContext{
addressprivate _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/errorOwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/errorOwnableInvalidOwner(address owner);
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/constructor(address initialOwner) {
if (initialOwner ==address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
if (newOwner ==address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}