SimpleSwap

1. Overview

SimpleSwap is an example project for swapping tokens using Uniswap V3.

The contract structure is broken down into individual contracts, each inherited from the previous contract. This was done as an exercise to better understand smart contract inheritance and to highlight reusable code sections.

ImportsVariablesGettersModifiersAndChecksUpdatesCoreSimpleSwap

This project builds on knowledge from the AavePM project.

The TokenSwap contract is a pure logic contract that can be used to swap ETH <-> USDC. It has no owner and is immutable. To upgrade the TokenSwap contract, a new contract must be deployed and the SimpleSwap contract must be updated to point to the new contract.

2. Usage

  1. Send ETH directly to the contract address to receive USDC on the sender address.
  2. Send USDC to the swapUsdc function to receive ETH on the sender address.

3. Functions

3.1. Swap Functions

FunctionRestrictionsDescription
receiveN/AReceive ETH and swap for USDC.
swapUsdcN/ASwap specified amount of USDC for ETH.

3.2. Withdraw Functions

FunctionRestrictionsDescription
withdrawEthOnly To Owner AddressWithdraw any ETH in the contract to an owner address.
withdrawTokensOnly To Owner AddressWithdraw specified token in the contract to an owner address.

3.3. Contract Upgrade Functions

FunctionRestrictionsDescription
upgradeContractOWNER_ROLEUpgrade the contract to the specified implementation.

3.4. Contract Update Functions

FunctionRestrictionsDescription
updateContractAddressOWNER_ROLEUpdate the specified contract address.
updateTokenAddressOWNER_ROLEUpdate the specified token address.
updateUniswapV3PoolOWNER_ROLEUpdate the specified Uniswap V3 pool.
updateSlippageToleranceOWNER_ROLEUpdate the specified slippage tolerance.

3.5. Role Management Functions

FunctionRestrictionsDescription
grantRoleRole AdminGrant a role to an address.
revokeRoleRole AdminRevoke a role from an address.
getRoleAdminN/AGet the admin of a role for the identifier.
getRoleMemberN/AGet the member of a role for the identifier.
getRoleMembersN/AGet the members of a role for the identifier.
getRoleMemberCountN/AGet the member count of a role for the identifier.
hasRoleN/ACheck if an address has a role.
renounceRoleRole MemberRenounce a role from an address.

3.6. Getter Functions

FunctionRestrictionsDescription
getCreatorN/AGet the creator address of the contract.
getEventBlockNumbersN/AGet the block numbers of all previous contract events.
getVersionN/AGet the current contract version.
getBalanceN/AGet the balance of the contract.
getContractAddressN/AGet the contract address of the identifier.
getTokenAddressN/AGet the token address of the identifier.
getUniswapV3PoolN/AGet the Uniswap V3 pool address of the identifier.
getSlippageToleranceN/AGet the slippage tolerance of the contract.
getSlippageToleranceMaximumN/AGet the maximum slippage tolerance of the contract.

4. Installation

4.1. Clone repository

git clone https://github.com/EridianAlpha/simple-swap.git

4.2. Install Dependencies

This should happen automatically when first running a command, but the installation can be manually triggered with the following commands:

git submodule init
git submodule update
make install

4.3. Create the .env file

Use the .env.example file as a template to create a .env file.

5. Testing

5.1. Tests (Fork)

make test
make test-v
make test-summary

5.2. Coverage (Fork)

make coverage
make coverage-report

6. Deployment

Deploys the SimpleSwap contract and all module contracts.

ChainCommand
Anvilmake deploy anvil
Holeskymake deploy holesky
Base Sepoliamake deploy base-sepolia
Base Mainnetmake deploy base-mainnet

7. Interactions

Interactions are defined in ./script/Interactions.s.sol

If DEPLOYED_CONTRACT_ADDRESS is set in the .env file, that contract address will be used for interactions. If that variable is not set, the latest deployment on the specified chain will be used.

Deployed Contracts:

7.1. Force Send ETH

Send ETH to the contract using a intermediate selfdestruct contract. This does not call the receive function on the contract. Input value in ETH e.g. 0.15.

ChainCommand
Anvilmake forceSendEth anvil
Holeskymake forceSendEth holesky
Base Sepoliamake forceSendEth base-sepolia
Base Mainnetmake forceSendEth base-mainnet

7.2. Swap Functions

7.2.1. Send ETH

Send ETH to the contract to receive USDC. Input value in ETH e.g. 0.15.

ChainCommand
Anvilmake sendEth anvil
Holeskymake sendEth holesky
Base Sepoliamake sendEth base-sepolia
Base Mainnetmake sendEth base-mainnet

7.2.2. Swap USDC

Swap USDC for ETH. Input value in USD e.g. 200.

ChainCommand
Anvilmake swapUsdc anvil
Holeskymake swapUsdc holesky
Base Sepoliamake swapUsdc base-sepolia
Base Mainnetmake swapUsdc base-mainnet

7.3. Withdraw Functions

7.3.1. Withdraw ETH

Withdraw all ETH in the contract to an owner address. Requires the specified withdrawal address to have the OWNER_ROLE. Input value as an address e.g. 0x123....

ChainCommand
Anvilmake withdrawEth anvil
Holeskymake withdrawEth holesky
Base Sepoliamake withdrawEth base-sepolia
Base Mainnetmake withdrawEth base-mainnet

7.3.2. Withdraw Tokens

Withdraw all of the specified token in the contract to an owner address. Requires the specified withdrawal address to have the OWNER_ROLE. Input value 1 as a token identifier e.g. USDC. Input value 2 as an address e.g. 0x123.... Combined input value e.g. USDC,0x123....

ChainCommand
Anvilmake withdrawTokens anvil
Holeskymake withdrawTokens holesky
Base Sepoliamake withdrawTokens base-sepolia
Base Mainnetmake withdrawTokens base-mainnet

7.4. Upgrades

Upgrade the contract to the latest logic implementation while maintaining the same proxy address. This also redeploys all modules and updates their contract addresses on SimpleSwap.

ChainCommand
Anvilmake upgrade anvil
Holeskymake upgrade holesky
Base Sepoliamake upgrade base-sepolia
Base Mainnetmake upgrade base-mainnet

7.5. Updates

7.5.1. Update Contract Address

Update the specified contract identifier to a new address. Input value 1 as a contract identifier e.g. uniswapV3Router. Input value 2 as an address e.g. 0x123.... Combined input value e.g. uniswapV3Router,0x123....

ChainCommand
Anvilmake updateContractAddress anvil
Holeskymake updateContractAddress holesky
Base Sepoliamake updateContractAddress base-sepolia
Base Mainnetmake updateContractAddress base-mainnet

7.5.2. Update Token Address

Update the specified token identifier to a new address. Input value 1 as a token identifier e.g. USDC. Input value 2 as an address e.g. 0x123.... Combined input value e.g. USDC,0x123....

ChainCommand
Anvilmake updateTokenAddress anvil
Holeskymake updateTokenAddress holesky
Base Sepoliamake updateTokenAddress base-sepolia
Base Mainnetmake updateTokenAddress base-mainnet

7.5.3. Update UniswapV3Pool Address

Update the specified token identifier to a new address and fee. Input value 1 as a UniswapV3Pool identifier e.g. USDC/ETH. Input value 2 as an address e.g. 0x123.... Input value 3 as a fee e.g. 500 for a fee of 0.05%. Combined input value e.g. USDC/ETH,0x123...,500.

ChainCommand
Anvilmake updateUniswapV3PoolAddress anvil
Holeskymake updateUniswapV3PoolAddress holesky
Base Sepoliamake updateUniswapV3PoolAddress base-sepolia
Base Mainnetmake updateUniswapV3PoolAddress base-mainnet

7.5.4. Update Slippage Tolerance

Input value to 2 decimal places e.g. 200 for a Slippage Tolerance of 0.5%.

ChainCommand
Anvilmake updateSlippageTolerance anvil
Holeskymake updateSlippageTolerance holesky
Base Sepoliamake updateSlippageTolerance base-sepolia
Base Mainnetmake updateSlippageTolerance base-mainnet

7.6. Role Management

7.6.1. Grant Role

Grant a role to an address. Requires the caller to be an admin of the role being granted. Input value 1 as a role e.g. OWNER_ROLE. Input value 2 as an address e.g. 0x123.... Combined input value e.g. OWNER_ROLE,0x123....

ChainCommand
Anvilmake grantRole anvil
Holeskymake grantRole holesky
Base Sepoliamake grantRole base-sepolia
Base Mainnetmake grantRole base-mainnet

7.6.2. Revoke Role

Revoke a role from an address. Requires the caller to be an admin of the role being revoked. Input value 1 as a role e.g. OWNER_ROLE. Input value 2 as an address e.g. 0x123.... Combined input value e.g. OWNER_ROLE,0x123....

ChainCommand
Anvilmake revokeRole anvil
Holeskymake revokeRole holesky
Base Sepoliamake revokeRole base-sepolia
Base Mainnetmake revokeRole base-mainnet

7.6.3. Get Role Admin

Get the admin for the specified role. Input value as a role e.g. OWNER_ROLE. Returns keccak256 hash of the admin role.

ChainCommand
Anvilmake getRoleAdmin anvil
Holeskymake getRoleAdmin holesky
Base Sepoliamake getRoleAdmin base-sepolia
Base Mainnetmake getRoleAdmin base-mainnet

7.6.4. Get Role Member

Get the member for the specified role and index. Input value 1 as a role e.g. OWNER_ROLE. Input value 2 as index e.g. 0. Combined input value e.g. OWNER_ROLE,0. Returns address of the member.

ChainCommand
Anvilmake getRoleMember anvil
Holeskymake getRoleMember holesky
Base Sepoliamake getRoleMember base-sepolia
Base Mainnetmake getRoleMember base-mainnet

7.6.5. Get Role Members

Get all members for the specified role. Input value as a role e.g. OWNER_ROLE. Returns array of addresses of the members.

ChainCommand
Anvilmake getRoleMembers anvil
Holeskymake getRoleMembers holesky
Base Sepoliamake getRoleMembers base-sepolia
Base Mainnetmake getRoleMembers base-mainnet

7.6.6. Get Role Member Count

Get the member count for the specified role. Input value as a role e.g. OWNER_ROLE. Returns the number of members in the role.

ChainCommand
Anvilmake getRoleMemberCount anvil
Holeskymake getRoleMemberCount holesky
Base Sepoliamake getRoleMemberCount base-sepolia
Base Mainnetmake getRoleMemberCount base-mainnet

7.6.7. Check Has Role

Check if an address has the specified role. Input value 1 as a role e.g. OWNER_ROLE. Input value 2 as an address e.g. 0x123.... Combined input value e.g. OWNER_ROLE,0x123....

ChainCommand
Anvilmake hasRole anvil
Holeskymake hasRole holesky
Base Sepoliamake hasRole base-sepolia
Base Mainnetmake hasRole base-mainnet

7.6.8. Renounce Role

Renounce the specified role from an address. Any address can renounce a role from themselves. Input value as a role e.g. OWNER_ROLE.

ChainCommand
Anvilmake renounceRole anvil
Holeskymake renounceRole holesky
Base Sepoliamake renounceRole base-sepolia
Base Mainnetmake renounceRole base-mainnet

7.7. Getters

7.7.1. Get Creator

Returns the contract creator address.

ChainCommand
Anvilmake getCreator anvil
Holeskymake getCreator holesky
Base Sepoliamake getCreator base-sepolia
Base Mainnetmake getCreator base-mainnet

7.7.2. Get Version

Returns the current version of the contract.

ChainCommand
Anvilmake getVersion anvil
Holeskymake getVersion holesky
Base Sepoliamake getVersion base-sepolia
Base Mainnetmake getVersion base-mainnet

7.7.3. Get Balance

Input value as token identifier e.g. USDC. Returns the balance of the contract for the specified token.

ChainCommand
Anvilmake getBalance anvil
Holeskymake getBalance holesky
Base Sepoliamake getBalance base-sepolia
Base Mainnetmake getBalance base-mainnet

7.7.4. Get Event Block Numbers

Returns the block numbers of all previous contract events.

ChainCommand
Anvilmake getEventBlockNumbers anvil
Holeskymake getEventBlockNumbers holesky
Base Sepoliamake getEventBlockNumbers base-sepolia
Base Mainnetmake getEventBlockNumbers base-mainnet

7.7.5. Get Contract Address

Input value as a contract identifier e.g. uniswapV3Router. Returns the contract address of the specified identifier.

ChainCommand
Anvilmake getContractAddress anvil
Holeskymake getContractAddress holesky
Base Sepoliamake getContractAddress base-sepolia
Base Mainnetmake getContractAddress base-mainnet

7.7.6. Get Token Address

Input value as a token identifier e.g. USDC. Returns the token address of the specified identifier.

ChainCommand
Anvilmake getTokenAddress anvil
Holeskymake getTokenAddress holesky
Base Sepoliamake getTokenAddress base-sepolia
Base Mainnetmake getTokenAddress base-mainnet

7.7.7. Get Uniswap V3 Pool

Input value as a Uniswap V3 Pool identifier e.g. USDC/ETH. Returns the address and fee of the specified identifier.

ChainCommand
Anvilmake getUniswapV3Pool anvil
Holeskymake getUniswapV3Pool holesky
Base Sepoliamake getUniswapV3Pool base-sepolia
Base Mainnetmake getUniswapV3Pool base-mainnet

7.7.8. Get Module Version

Input value as a module identifier e.g. tokenSwapCalcsModule. Returns the version of the specified module.

ChainCommand
Anvilmake getModuleVersion anvil
Holeskymake getModuleVersion holesky
Base Sepoliamake getModuleVersion base-sepolia
Base Mainnetmake getModuleVersion base-mainnet

8. Build and Deploy Documentation

Instructions on how to build and deploy the documentation book are detailed here: https://docs.eridianalpha.com/ethereum-dev/foundry-notes/docs-and-github-pages

9. License

MIT

Contents

IERC20Extended

Git Source

Inherits: IERC20

This interface extends the ERC20 interface with the decimals function.

Functions

decimals

function decimals() external view returns (uint8);

ISimpleSwap

Git Source

This interface defines the essential structures and functions for the SimpleSwap contract.

Events

EthWithdrawn

event EthWithdrawn(address indexed to, uint256 amount);

TokensWithdrawn

event TokensWithdrawn(address indexed to, string identifier, uint256 amount);

SimpleSwapInitialized

event SimpleSwapInitialized(address indexed creator);

SimpleSwapUpgraded

event SimpleSwapUpgraded(address indexed previousImplementation, address indexed newImplementation);

ContractAddressUpdated

event ContractAddressUpdated(
    string identifier, address indexed previousContractAddress, address indexed newContractAddress
);

TokenAddressUpdated

event TokenAddressUpdated(string identifier, address indexed previousTokenAddress, address indexed newTokenAddress);

UniswapV3PoolUpdated

event UniswapV3PoolUpdated(string identifier, address indexed newUniswapV3PoolAddress, uint24 newUniswapV3PoolFee);

SlippageToleranceUpdated

event SlippageToleranceUpdated(uint16 previousSlippageTolerance, uint16 newSlippageTolerance);

Errors

SimpleSwap__NoEthToWithdraw

error SimpleSwap__NoEthToWithdraw();

SimpleSwap__SwapAmountInZero

error SimpleSwap__SwapAmountInZero();

SimpleSwap__WithdrawEthFailed

error SimpleSwap__WithdrawEthFailed();

SimpleSwap__AddressNotAnOwner

error SimpleSwap__AddressNotAnOwner();

SimpleSwap__NoTokensToWithdraw

error SimpleSwap__NoTokensToWithdraw();

SimpleSwap__FunctionDoesNotExist

error SimpleSwap__FunctionDoesNotExist();

SimpleSwap__ZeroTokensOutFromSwap

error SimpleSwap__ZeroTokensOutFromSwap();

SimpleSwap__SlippageToleranceUnchanged

error SimpleSwap__SlippageToleranceUnchanged();

SimpleSwap__SlippageToleranceAboveMaximum

error SimpleSwap__SlippageToleranceAboveMaximum();

TokenSwap__NotEnoughTokensForSwap

error TokenSwap__NotEnoughTokensForSwap(string tokenInIdentifier);

Structs

ContractAddress

struct ContractAddress {
    string identifier;
    address contractAddress;
}

TokenAddress

struct TokenAddress {
    string identifier;
    address tokenAddress;
}

UniswapV3Pool

struct UniswapV3Pool {
    string identifier;
    address poolAddress;
    uint24 fee;
}

ITokenSwapCalcsModule

Git Source

This interface defines the essential structures and functions for the TokenSwapCalcsModule contract.

Functions

VERSION

function VERSION() external pure returns (string memory version);

uniswapV3CalculateMinOut

function uniswapV3CalculateMinOut(
    uint256 _currentBalance,
    address _uniswapV3PoolAddress,
    address _tokenOutAddress,
    uint16 _slippageTolerance
) external view returns (uint256 minOut);

IWETH9

Git Source

This interface enables the wrapping and unwrapping of ETH to WETH.

Functions

deposit

function deposit() external payable;

withdraw

function withdraw(uint256 wad) external;

Contents

SimpleSwapInternalFunctionsHelper

Git Source

Inherits: SimpleSwap

This contract is used to test the internal functions of the SimpleSwap contract.

Contents

TokenSwapCalcsModule

Git Source

Inherits: ITokenSwapCalcsModule

Author: EridianAlpha

This contract contains the functions for SimpleSwap to swap tokens using UniswapV3.

State Variables

VERSION

The version of the contract.

Contract is upgradeable so the version is a constant set on each implementation contract.

string public constant VERSION = "0.0.1";

Functions

uniswapV3CalculateMinOut

Calculates the minimum amount of tokens to receive from a UniswapV3 swap.

Uses the current pool price ratio and a predefined slippage tolerance to calculate the minimum amount.

function uniswapV3CalculateMinOut(
    uint256 _currentBalance,
    address _uniswapV3PoolAddress,
    address _tokenOutAddress,
    uint16 _slippageTolerance
) external view returns (uint256 minOut);

Parameters

NameTypeDescription
_currentBalanceuint256The current balance of the token to swap.
_uniswapV3PoolAddressaddressThe address of the UniswapV3 pool to use for the swap.
_tokenOutAddressaddressThe address of the token to receive from the swap.
_slippageToleranceuint16The slippage tolerance for the swap.

Returns

NameTypeDescription
minOutuint256The minimum amount of tokens to receive from the swap.

Core

Git Source

Inherits: Updates

This core contract implements all abstract functions from the inherited contracts, initializes the contract, and adds standard functions.

Functions

constructor

Constructor implemented but unused.

Contract is upgradeable and therefore the constructor is not used.

constructor();

initialize

Initializes contract with the owner and relevant addresses and parameters for operation.

This function sets up all necessary state variables for the contract and can only be called once due to the initializer modifier.

function initialize(
    address owner,
    ContractAddress[] memory contractAddresses,
    TokenAddress[] memory tokenAddresses,
    UniswapV3Pool[] memory uniswapV3Pools,
    uint16 initialSlippageTolerance
) external initializer;

Parameters

NameTypeDescription
owneraddressThe address of the owner of the contract.
contractAddressesContractAddress[]An array of ContractAddress structures containing addresses of related contracts.
tokenAddressesTokenAddress[]An array of TokenAddress structures containing addresses of relevant ERC-20 tokens.
uniswapV3PoolsUniswapV3Pool[]An array of UniswapV3Pool structures containing the address and fee of the UniswapV3 pools.
initialSlippageToleranceuint16The initial slippage tolerance for token swaps.

withdrawEth

Withdraw all ETH from the contract.

This function is intended for emergency use. In normal operation, the contract should not hold ETH, This function can be called by anyone. The use of nonReentrant is not required due to the withdrawAddress check for the OWNER_ROLE and it drains 100% of the ETH balance anyway. Throws SimpleSwap__NoEthToWithdraw if there is no ETH to withdraw. Emits an EthWithdrawn event. Stores the block number of the event.

function withdrawEth(address _withdrawAddress) external checkOwner(_withdrawAddress);

Parameters

NameTypeDescription
_withdrawAddressaddressThe address to send the withdrawn ETH to. Must have OWNER_ROLE.

withdrawTokens

Withdraw specified tokens from the contract balance.

The function withdraws the specified tokens from the contract balance to the owner. Throws SimpleSwap__NoTokensToWithdraw if there are no tokens to withdraw. Emits a TokensWithdrawn event. Stores the block number of the event.

function withdrawTokens(string memory _identifier, address _withdrawAddress) external checkOwner(_withdrawAddress);

Parameters

NameTypeDescription
_identifierstringThe identifier of the token to withdraw.
_withdrawAddressaddressThe address to send the withdrawn tokens to. Must have OWNER_ROLE.

_authorizeUpgrade

Internal function to authorize an upgrade.

Caller must have OWNER_ROLE.

function _authorizeUpgrade(address _newImplementation) internal override onlyRole(OWNER_ROLE);

Parameters

NameTypeDescription
_newImplementationaddressAddress of the new contract implementation.

upgradeContract

Upgrade the contract to a new implementation.

Caller must have OWNER_ROLE.

function upgradeContract(address newImplementation, bytes memory data) external payable;

Parameters

NameTypeDescription
newImplementationaddressAddress of the new contract implementation.
databytesData to send to the new implementation.

Getters

Git Source

Inherits: Variables

This getters contract has all the custom getter functions for the SimpleSwap contract.

Functions

getCreator

Public getter function to get the address of the contract creator.

function getCreator() public view returns (address creator);

Returns

NameTypeDescription
creatoraddressThe address of the creator.

getVersion

Public getter function to get the contract version.

function getVersion() public pure returns (string memory version);

Returns

NameTypeDescription
versionstringThe contract version.

getBalance

Public getter function to get the balance of the provided identifier.

function getBalance(string memory _identifier) public view returns (uint256 balance);

Parameters

NameTypeDescription
_identifierstringThe identifier for the token address.

Returns

NameTypeDescription
balanceuint256The balance of the specified token identifier.

getEventBlockNumbers

Public getter function to get the block numbers of all the contract events.

function getEventBlockNumbers() public view returns (uint64[] memory eventBlockNumbers);

Returns

NameTypeDescription
eventBlockNumbersuint64[]The array of event block numbers.

getContractAddress

Public getter function to get the contract address for a given identifier.

function getContractAddress(string memory _identifier) public view returns (address contractAddress);

Parameters

NameTypeDescription
_identifierstringThe identifier for the contract address.

Returns

NameTypeDescription
contractAddressaddressThe contract address corresponding to the given identifier.

getTokenAddress

Public getter function to get the token address for a given identifier.

function getTokenAddress(string memory _identifier) public view returns (address tokenAddress);

Parameters

NameTypeDescription
_identifierstringThe identifier for the contract address.

Returns

NameTypeDescription
tokenAddressaddressThe token address corresponding to the given identifier.

getUniswapV3Pool

Public getter function to get the UniswapV3 pool address and fee.

function getUniswapV3Pool(string memory _identifier)
    public
    view
    returns (address uniswapV3PoolAddress, uint24 uniswapV3PoolFee);

Parameters

NameTypeDescription
_identifierstringThe identifier for the UniswapV3 pool.

Returns

NameTypeDescription
uniswapV3PoolAddressaddressThe UniswapV3 pool address.
uniswapV3PoolFeeuint24The UniswapV3 pool fee.

getSlippageTolerance

Getter function to get the Slippage Tolerance.

Public function to allow anyone to view the Slippage Tolerance value.

function getSlippageTolerance() public view returns (uint16 slippageTolerance);

Returns

NameTypeDescription
slippageToleranceuint16The Slippage Tolerance value.

getSlippageToleranceMaximum

Getter function to get the Slippage Tolerance maximum.

Public function to allow anyone to view the Slippage Tolerance maximum value.

function getSlippageToleranceMaximum() public pure returns (uint16 slippageToleranceMaximum);

Returns

NameTypeDescription
slippageToleranceMaximumuint16The Slippage Tolerance maximum value.

getRoleMembers

Public getter function to get all the members of a role.

function getRoleMembers(string memory _roleString) public view returns (address[] memory members);

Parameters

NameTypeDescription
_roleStringstringThe identifier for the role.

Returns

NameTypeDescription
membersaddress[]The array of addresses that are members of the role.

Imports

Git Source

Inherits: ISimpleSwap, Initializable, AccessControlEnumerableUpgradeable, UUPSUpgradeable

This imports contract has all the inherited contracts for the SimpleSwap contract.

ModifiersAndChecks

Git Source

Inherits: Getters

This modifiers and checks contract has all the custom modifiers and checks for the SimpleSwap contract.

Functions

checkOwner

Modifier to check if the caller has the OWNER_ROLE.

modifier checkOwner(address _owner);

Parameters

NameTypeDescription
_owneraddressThe address to check if it has the OWNER_ROLE.

SimpleSwap

Git Source

Inherits: Core

This logic contract has all the custom logic for the SimpleSwap contract.

This contract accepts ETH, swaps it to USDC using UniswapV3 and returns the USDC to the sender.

Functions

receive

Function to receive ETH when no msg.data is sent.

Calls the swapTokens function with ETH as the input token and automatically swaps it to USDC. Ignores ETH sent from the WETH contract to avoid loops when unwrapping WETH.

receive() external payable;

fallback

Revert calls to functions that do not exist.

fallback() external payable;

swapUsdc

Function to swap USDC to ETH.

function swapUsdc(uint256 _value) external returns (uint256 amountOut);

swapTokens

Function to swap tokens using UniswapV3.

function swapTokens(
    string memory _uniswapV3PoolIdentifier,
    string memory _tokenInIdentifier,
    string memory _tokenOutIdentifier,
    uint256 _amountIn
) internal returns (uint256 amountOut);

_isIdentifierEth

Checks if the identifier is for ETH.

Compares the identifier to the ETH identifier and returns true if they match.

function _isIdentifierEth(string memory _identifier) internal pure returns (bool isEth);

Parameters

NameTypeDescription
_identifierstringThe identifier to check.

Returns

NameTypeDescription
isEthboolTrue if the identifier is for ETH.

Updates

Git Source

Inherits: ModifiersAndChecks

Functions

_storeEventBlockNumber

Stores the block number of an event.

This function is called after an event is emitted to store the block number. Duplicates are not stored even if multiple events are emitted in the same block.

function _storeEventBlockNumber() internal;

updateContractAddress

Generic update function to set the contract address for a given identifier.

Caller must have OWNER_ROLE. Stores the block number of the event. Emits a ContractAddressUpdated event.

function updateContractAddress(string memory _identifier, address _newContractAddress) external onlyRole(OWNER_ROLE);

Parameters

NameTypeDescription
_identifierstringThe identifier for the contract address.
_newContractAddressaddressThe new contract address.

updateTokenAddress

Generic update function to set the token address for a given identifier.

Caller must have OWNER_ROLE. Emits a TokenAddressUpdated event. Stores the block number of the event.

function updateTokenAddress(string memory _identifier, address _newTokenAddress) external onlyRole(OWNER_ROLE);

Parameters

NameTypeDescription
_identifierstringThe identifier for the token address.
_newTokenAddressaddressThe new token address.

updateUniswapV3Pool

Update UniSwapV3 pool details.

Caller must have OWNER_ROLE. Emits a UniswapV3PoolUpdated event.

function updateUniswapV3Pool(string memory _identifier, address _newUniswapV3PoolAddress, uint24 _newUniswapV3PoolFee)
    external
    onlyRole(OWNER_ROLE);

updateSlippageTolerance

Update the Slippage Tolerance.

Caller must have OWNER_ROLE. Emits a SlippageToleranceUpdated event.

function updateSlippageTolerance(uint16 _slippageTolerance) external onlyRole(OWNER_ROLE);

Parameters

NameTypeDescription
_slippageToleranceuint16The new Slippage Tolerance.

Variables

Git Source

Inherits: Imports

This variables contract has all the custom variables for the SimpleSwap contract.

State Variables

s_creator

address internal s_creator;

s_contractAddresses

mapping(string => address) internal s_contractAddresses;

s_tokenAddresses

mapping(string => address) internal s_tokenAddresses;

s_uniswapV3Pools

mapping(string => UniswapV3Pool) internal s_uniswapV3Pools;

s_eventBlockNumbers

uint64[] internal s_eventBlockNumbers;

s_slippageTolerance

uint16 internal s_slippageTolerance;

VERSION

The current contract version.

string internal constant VERSION = "0.0.1";

OWNER_ROLE

The role hashes for the contract.

bytes32 internal constant OWNER_ROLE = keccak256("OWNER_ROLE");

SLIPPAGE_TOLERANCE_MAXIMUM

The maximum Slippage Tolerance.

The value is hardcoded in the contract to prevent terrible trades from occurring due to a high slippage tolerance. A contract upgrade is required to change this value.

uint16 internal constant SLIPPAGE_TOLERANCE_MAXIMUM = 100;