Token Swap
Build a token swap dApp on Nexus
Example Token Swap on Nexus
This guide provides a complete walkthrough for creating a decentralized token swap application (DEX) using the Nexus blockchain. Users will be able to swap two tokens Token A
and Token B
for one another.
- Live Demo: nexus-swap-example.vercel.app
- Source Code: github.com/nexus-xyz/nexus-swap-example
Overview
This project demonstrates fundamental decentralized finance (DeFi) operations on Nexus. Users can:
- Connect their crypto wallets.
- Perform token swaps (Token A ⇄ Token B) at a fixed 1:1 ratio.
- Understand the workflow of token approvals, transactions, and balance management.
This example serves as a starting point for developers interested in creating more sophisticated financial applications.
Project Context
Decentralized exchanges (DEXs) allow direct peer-to-peer cryptocurrency transactions without intermediaries, leveraging smart contracts for secure and trustless swaps. This Nexus token swap example illustrates blockchain concepts such as smart contract deployment, ERC20 token standards, wallet integrations, and real-time transaction management.
Decentralized exchanges (DEXs) allow direct peer-to-peer cryptocurrency transactions without intermediaries, leveraging smart contracts for secure and trustless swaps. This Nexus token swap example illustrates blockchain concepts such as smart contract deployment, ERC20 token standards, wallet integrations, and real-time transaction management.
Setting Up Your Development Environment
1. Install Required Tools
Hardhat is a development environment and task runner for Ethereum that helps developers compile, deploy, test, and debug smart contracts. The —save-dev flag ensures Hardhat is installed as a development-only dependency, keeping it separate from production dependencies.
2. Create a New Project
3. Configure Hardhat for Nexus
Within your project directory, create/update your config file hardhat.config.js
which will define the network configuration, RPC endpoint for Hardhat to connect to, and chainID for signature verification:
4. Configure your private key in .env file
-
Get your private key from Nexus
- Go to the Nexus Web App
- Sign in to your account in the top right corner
- Click the “Settings” tab
- Navigate to “Account & Security”
- Click on “Private Key”
- Click “Reveal” to view your private key
-
Create your .env file
- Create a new file named
.env
in your project root directory - Add your private key in this format:
- Create a new file named
-
Install dotenv package
-
Update hardhat.config.js
- Add this line at the top of your
hardhat.config.js
if not already present:
- Add this line at the top of your
Important Security Notes:
- Never share your private key
- Never commit it to version control
- Keep it secure and backed up
- Use a test account for development
5. Receive test NEX from a faucet for contract deployment
To deploy your contract on Nexus Layer 1, you’ll need NEX tokens to pay for gas fees. Gas fees are the cost of executing transactions on the blockchain, similar to how you need fuel to drive a car.
There are two ways to receive NEX for testing:
-
Earn NEX through Proving
- Submit proofs to earn points and NEX in real-time
- This is the recommended way as it helps secure the network
- For detailed instructions on proving, visit our Proving Guide
-
Use the Nexus Faucet
- A faucet is a service that provides small amounts of cryptocurrency for testing.
- It’s like a water faucet, but instead of water, it dispenses test tokens
- Visit our Faucet to receive test NEX
Note: The amount of NEX you receive from the faucet is sufficient for deploying and testing basic contracts. For more extensive testing, consider earning NEX through proving.
The Smart Contracts
1. Create the Contract Files
This example includes three contracts: two ERC20 tokens and a swap contract that allows users to exchange one token for the other at a fixed 1:1 rate. Together, they demonstrate token creation, approval flows, and user-to-contract and contract-to-user transfers.
Token A Contract
Token A is a standard ERC20 token deployed with an initial supply minted to the deployer’s wallet.
Purpose:
Represents one side of the swap pair. Token A is the token users must send into the TokenSwap
contract in order to receive Token B.
Behavior:
- Inherits from OpenZeppelin’s
ERC20
implementation for standard compliance and security. - Accepts an
initialSupply
argument at deployment. - Mints the full supply to
msg.sender
, typically the deployer.
Token B Contract
Token B is functionally identical to Token A, but represents the asset dispensed during a swap.
Purpose:
Acts as the output token users receive after submitting Token A to the TokenSwap
contract.
Behavior:
- Same structure and logic as Token A.
- Deployed independently with its own symbol, name, and supply.
- Minted to the deployer, who is expected to fund the
TokenSwap
contract with Token B before users can perform swaps.
Token Swap Contract
The TokenSwap
contract performs the core logic of the application: exchanging Token A for Token B at a fixed 1:1 ratio.
Purpose: Enables users to trade Token A for Token B in a single-step transaction, after approval.
Constructor:
- Accepts the addresses of the deployed Token A and Token B contracts.
- Stores them as immutable
IERC20
instances for interaction.
Swap Logic:
- The
swap(uint256 amount)
function executes the exchange. - First, it transfers
amount
of Token A from the caller to the contract usingtransferFrom
. This requires the user to have previously approved the contract to spend their tokens. - Then, it transfers the same
amount
of Token B from the contract to the user.
Assumptions:
- The contract must be preloaded with a sufficient Token B balance (liquidity).
- The exchange is strictly 1:1; no pricing, slippage, or fee logic is applied.
2. Create a Deployment Script
Create scripts/deploy.js
:
A deployment script is a programmatic way to deploy your smart contracts to a blockchain using Hardhat. Instead of manually interacting with the network through a UI or console, deployment scripts allow you to:
- Automate contract deployment
- Set constructor arguments dynamically
- Log or save deployed addresses
- Chain deployments in a predictable order
- Integrate easily into testing, development, or CI/CD pipelines
Here we create a new folder entitled scripts and create a file entitled deploy.js, which will deploy our code to the Layer 1:
This script demonstrates a complete, real-world deployment pattern:
- It manages asynchronous deployment logic with await
- Provides helpful logs to track progress
- Prepares for contract verification on Nexus Explorer
Deploying Your Contract
1. Deploy to Nexus
Run the following command to deploy your contract to the Nexus network:
You should see the following output in your terminal:
This means your contract has been successfully deployed to the Nexus network. Save the contract address - you’ll need it to interact with your contract later.
2. Examine Counter contract on the Nexus Explorer
Visit the Testnet III Nexus Explorer to view your deployed contract. The block explorer is a search engine for the blockchain that lets you:
- View all transactions
- Check contract code
- Monitor contract interactions
- Track token transfers
- View account balances
To find your contract:
- Copy your contract’s address from the deployment output
- Paste it into the search bar at the top of the explorer
- Click on your contract to view its details
You’ll see:
- Contract code (verified)
- Transaction history
- Contract balance
- Recent interactions
- Event logs
This is where you can verify that your contract was deployed correctly and monitor its activity on the network.
Building a Simple Frontend
The frontend uses ethers.js v6 to interact with the smart contract. Create a new Next.js project using the command
On which, you will see the following prompts:
Install ether.js
in your Next.js project:
Edit the src/app/page.tsx
file to integrate the deployed smart contract with the frontend:
Project Structure
This repository is organized as follows
Key Features
Smart Contract Architecture
- Utilizes robust ERC20 token standards provided by OpenZeppelin.
- Straightforward 1:1 swap logic ensuring simplicity and transparency.
- Secure approval and transaction processes.
Frontend Implementation
- Modern UI leveraging Next.js and Tailwind CSS.
- Dynamic real-time token balance updates.
- User-friendly wallet connection and transaction status indicators.
- Comprehensive error handling and notifications for a smooth user experience.
Demonstrated DeFi Concepts
- Token approvals and transaction flow.
- Multi-step DeFi transactions (approve and swap).
- Real-time balance and contract interaction management.
- Monitoring blockchain events for accurate transaction feedback.
Resources
- Live Demo: nexus-swap-example.vercel.app
- Source Code: github.com/nexus-xyz/nexus-swap-example
Follow these steps to set up and run the application locally:
- Clone and install dependencies:
- Deploy smart contracts:
- Run frontend locally:
Using the dApp
Follow these simple steps to execute a token swap:
- Connect your cryptocurrency wallet (e.g., MetaMask).
- Verify your current balances of Token A and Token B.
- Enter the amount of Token A to swap.
- Click “Swap” and approve the transaction.
- Confirm the transaction in your wallet.
- Observe updated balances upon transaction completion.
Deployed Contract Addresses
- Token A:
0x83FD4F92926AC4FB7a0b510aD5615Fe76e588cF8
- Token B:
0x67bae4B1E5528Fb6C92E7E0BC243341dc71330db
- Token Swap:
0xf18529580694Ff80e836132875a52505124358EC