The smart contract enables exchanges within a single network through various DEXs or cross-network swaps from any token to any token.
- Safeblock DEX Smart Contract
The Safeblock DEX Smart Contract is built using the Diamond Proxy pattern (EIP-2535), which allows for modular and upgradeable smart contracts. The architecture consists of:
The EntryPoint contract serves as a proxy to facilitate dynamic function execution. It achieves this by mapping function selectors to designated facet contracts (external modules). This design enables modular functionality, where each function can be delegated to a specific facet, making the system flexible and upgradable.
-
Storage of Selectors and Facets:
- The contract uses the
SSTORE2library to store a combined array of function selectors and facet addresses. This array is stored in a single, efficient storage slot to reduce gas costs. - The selectors and addresses are organized so that each selector is mapped to a unique facet address.
- The contract uses the
-
Function Delegation:
EntryPointuses a fallback function to delegate incoming function calls to the appropriate facet based on the function selector.- The
_getAddressfunction employs binary search to identify the facet for a given selector, optimizing lookup time. - The contract also has multicall capabilities, which allow it to execute multiple functions in a single transaction, either with or without argument replacement.
- SSTORE2: Efficient storage of large data (selectors and addresses).
- Binary Search: Used for fast, efficient retrieval of facet addresses from stored selectors.
- Transient Storage: Temporary storage for multicall sender address and callback address during execution.
- multicall: Executes a batch of function calls. It supports both straightforward execution and argument replacement modes.
- _getAddress and _getAddresses: Internal helper functions to retrieve facet addresses associated with specific selectors.
The system is composed of multiple facets, each handling specific functionalities:
- MultiswapRouterFacet: Handles token swaps across Uniswap V3 and Uniswap V2 protocols, supporting complex swap transactions like "multiswaps" and "partswaps".
- TransferFacet: Handles token and native asset transfers with support for wrapping/unwrapping native tokens.
- StargateFacet: Enables cross-chain messaging and token bridging using the Stargate protocol.
- LayerZeroFacet: Facilitates cross-chain communication with the LayerZero protocol.
- SymbiosisFacet: Handles cross-chain swaps using the Symbiosis protocol.
- AcrossFacet: Manages cross-chain transfers using the Across protocol.
- CrossCurveFacet: Enables cross-chain swaps using the Curve protocol.
- Modular Architecture: Each functionality is implemented in separate facets, allowing for independent upgrades.
- Cross-Chain Compatibility: Supports multiple cross-chain protocols (Stargate, LayerZero, Symbiosis, Across).
- Gas Optimization: Uses efficient storage patterns and binary search for function lookups.
- Multi-Swap Support: Complex swap operations across multiple DEXs in a single transaction.
- Native Token Support: Seamless handling of native and wrapped tokens.
- Fee Management: Configurable fee system with dedicated fee contract.
- Permit2 Integration: Supports gasless approvals using Uniswap's Permit2.
- Multicall Capability: Execute multiple function calls in a single transaction.
├── script/ # Deployment and upgrade scripts
├── src/ # Smart contract source files
│ ├── EntryPoint.sol # Diamond proxy contract
│ ├── FeeContract.sol # Fee management contract
│ ├── facets/ # Individual facet implementations
│ ├── interfaces/ # Contract interfaces
│ ├── libraries/ # Utility libraries
│ ├── proxy/ # Proxy-related contracts
│ └── external/ # External contract dependencies
├── test/ # Test files
└── lib/ # External libraries
-
Install Foundry:
curl -L https://foundry.paradigm.xyz | bash foundryup -
Clone the repository:
git clone https://github.com/your-org/safeblock-dex.git cd safeblock-dex -
Install dependencies:
forge install
Copy the example environment file and configure your variables:
cp .env.example .envEdit .env with your private key and RPC URLs:
PRIVATE_KEY=your_private_key_here
ETH_RPC_URL=https://mainnet.infura.io/v3/YOUR_PROJECT_ID
# Add other network RPC URLs as neededforge script script/DeployContract.s.sol --sig "run(uint256)" 0 --rpc-url {network} --broadcast --verifyReplace {network} with the target network (e.g., ethereum, polygon, arbitrum).
For production deployments, use version 1, 2, or 3:
forge script script/DeployContract.s.sol --sig "run(uint256)" 1 --rpc-url {network} --broadcast --verify# Start Anvil local testnet
anvil
# In another terminal, deploy
forge script script/DeployContract.s.sol --sig "run(uint256)" 0 --rpc-url http://localhost:8545 --broadcastAfter deployment, update the contract addresses in the DeployEngine.sol file in the getContracts method for the specific network.
To upgrade specific facets:
-
Update the
.envfile with your private key and RPC URL. -
In the
DeployEngine.solfile, locate thegetContractsfunction for your target network and set the addresses of the facets you want to upgrade toaddress(0). -
Run the deployment script:
forge script script/DeployContract.s.sol --sig "run(uint256)" 0 --rpc-url {network} --broadcast --verify
For production upgrades, use the appropriate version number:
forge script script/DeployContract.s.sol --sig "run(uint256)" 1 --rpc-url {network} --broadcast --verifyRun all tests:
forge testRun tests with gas reports:
forge test --gas-reportRun specific test files:
forge test -mp "Multiswap"Generate coverage report:
forge coverageGenerate coverage report with lcov format (for HTML report):
forge coverage --report lcovGenerate HTML coverage report (requires lcov to be installed):
forge coverage --report lcov && genhtml lcov.info -o coverageThis project is licensed under the MIT License - see the LICENSE.md file for details.
MIT License
Copyright (c) 2025 SafeBlock
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.