Skip to main content

dSwap ERC20 Standard

Dswap Concept Overview

The dSwap ERC20 Standard by DeUnity and DePerp Labs represents an ERC20 built in AMM and liquidiy pool. This standard allows users to exchange tokens for ETH and vice versa, as well as participate in staking to earn transaction fees. Key features and functionalities of the contract include:


Key Features

  1. AMM Formula

    • Description: Utilizes the constant product formula x * y = k, where x and y are the reserves of two assets (ETH and tokens), and k is a constant that remains unchanged.
    • Function: Maintains the product of reserves constant during transactions, automatically adjusting prices based on the volume of traded assets.
  2. Token Exchange

    • Buying Tokens: Users can exchange ETH for tokens. The contract allows for setting a minimum token amount to avoid slippage.
    • Selling Tokens: Users can exchange tokens for ETH. A minimum ETH amount can also be set to protect against adverse price changes.
  3. Liquidity Management

    • Reserves: The contract maintains ETH and token reserves, which are automatically updated after each transaction.
    • Adding/Removing Liquidity: The contract does not support direct liquidity management. Liquidity is managed through exchange operations.
    • Basis Reserves: Upon deployment, the contract sets the basis reserves, determining the baseline value.
  4. Fees and Staking

    • Fees: A 0.3% fee is charged on each transaction and sent to the staking address.
    • Staking: Developers can specify a staking contract address where trading fees from the token contract will be directed.
  5. Transparency and Decentralization

    • Automation: The contract automatically handles purchases, sales, and fee calculations, eliminating the need for manual intervention.
    • Decentralization: A fully decentralized system with no centralized control.
  6. Price Evaluation and Prediction

    • Token Evaluation: The getCurrentPrice function returns the current token price in ETH.
    • Trade Predictions: Functions getEstimatedTokensForETH and getEstimatedETHForTokens provide estimates for token and ETH exchanges.

Technical Description and Formulas

AMM Formula:

The constant product formula used is: x * y = k

where:

  • x = ETH Reserve
  • y = Token Reserve
  • k = Constant (product of reserves)

Exchange Calculation:

To compute the amount of tokens or ETH received in an exchange, the following formula is used:

outputAmount=inputAmountoutputReserveinputReserve+inputAmount\text{outputAmount} = \frac{\text{inputAmount} \cdot \text{outputReserve}}{\text{inputReserve} + \text{inputAmount}}

This formula ensures balanced reserves and adjusts the price based on transaction volume.

Fee Calculation:

A 0.3% fee is applied to each transaction:

 fee=inputAmountCOMMISSION_FEEBPS \text{ fee} = \frac{\text{inputAmount} \cdot \text{COMMISSION\_FEE}}{\text{BPS }}​

where:

  • COMMISSION_FEE = 30 (basis points)
  • BPS = 10000 (basis points)

The fee is deducted from the transaction amount and sent to the staking address.


FAQ

How Does the AMM Work?

The AMM uses the formula x * y = k to maintain reserve balance during transactions. This formula adjusts prices based on trade volume, ensuring the constant product of reserves.

What Problem Does It Solve?

It offers a decentralized solution for token trading and liquidity management without relying on centralized exchanges. Provides transparent, automated management of trading and fees with staking opportunities.

Who Will Use This?

  • Developers and projects looking to create tokens with integrated trading and liquidity mechanisms.
  • Traders and users interested in exchanging tokens or ETH in a decentralized manner.
  • Speculators seeking to launch or trade innovative tokens and assets.

What Are the Benefits?

  • Transparency: Automated processes and open-source code ensure transparency.
  • Decentralization: Eliminates centralized control or intermediaries.
  • Automation: Handles trading, fees, and liquidity management automatically.
  • Security: Includes protections against common attacks and errors.

Interaction with DeUnity-DePerp:

  • The DeUnity-DePerp platform provides an interface for trading and analytics supporting this standard.
  • Each token can be represented on futures without needing external oracle listings.
  • DeUnity-DePerp is working on extending this standard to support swaps, spot markets, initial token offerings, and cross-chain integrations.

Key Components

  1. Imported Contracts and Libraries

    • ERC20 and ERC20Burnable from OpenZeppelin: Standard ERC20 token contract with burnable capabilities.
    • ReentrancyGuard from OpenZeppelin: Protection against reentrant calls.
  2. State Variables

    • INITIAL_SUPPLY: Initial token supply, set to total supply tokens with 18 decimal places.
    • ethReserve: The ETH reserve held by the contract.
    • tokenReserve: The token reserve held by the tokenscontract.
    • basisValue: Base virtual reserve value for initial valuation.
    • BPS: Basis points for percentage calculations (10000, i.e., 1% = 100).
    • DEV_SUPPLY_PERCENT: Percentage of initial token supply allocated to developers.
    • COMMISSION_FEE: Swap fee in basis points (0.3%).
    • Q112: Constant for fixed-point arithmetic (2^112).
    • stake: Address to receive fees.
    • accumulatedFeesInToken: Accumulated fees in tokens.
    • accumulatedFeesInETH: Accumulated fees in ETH.
    • lastClaimTime: Timestamp of the last fee claim.
    • claimCooldown: Cooldown period for fee claims (1 day).

Events

  1. TokensPurchased: Emitted when tokens are purchased, including the buyer, ETH amount, and token amount.
  2. TokensSold: Emitted when tokens are sold, including the seller, token amount, and ETH amount.
  3. ReservesUpdated: Emitted when reserves are updated.
  4. FeesWithdrawn: Emitted when fees are withdrawn, including the recipient address and amounts in tokens and ETH.
  5. FeeAccumulated: Emitted when fees are accumulated in tokens and ETH.

Functions

Overview

TOKEN-DSwap is an advanced ERC20 token implementation that combines automated market maker (AMM) functionality with staking capabilities. It features a built-in swap, liquidity pool, fee mechanism, and rewards distribution system.

Core Components

1. DswapBuild Contract

The main token contract implementing ERC20 functionality with the following features:

  • Built-in AMM (Automated Market Maker)
  • 0.3% fee on all trades
  • ETH/Token built-in liquidity pool
  • Token burning mechanism
  • Fee accumulation and distribution

2. StakeY Contract

Staking contract that enables:

  • Token staking
  • Dual rewards in ETH and tokens
  • Time-based reward distribution
  • 1-hour cooldown between reward claims

3. DeploymentFactory Contract

Factory contract for deploying new token instances with:

  • Automated setup of token and staking contracts
  • Configurable initial parameters
  • Fee collection mechanism
  • Ownership management

Key Features

Automated Market Making

  • Constant product formula (x * y = k)
  • Dynamic pricing based on reserve ratios
  • Slippage protection
  • Minimum trade amounts

Fee Structure

  • 0.3% fee on all trades (30 basis points)
  • Fees split between:
    • Token staking rewards
    • ETH staking rewards
    • Protocol maintenance

Liquidity Management

  • Initial liquidity provided at deployment
  • Basis value mechanism for price stability
  • Reserve tracking for both ETH and tokens
  • Anti-manipulation safeguards

Staking Mechanism

  • Flexible staking periods
  • Dual reward system (ETH + Tokens)
  • Pro-rata reward distribution
  • Anti-gaming measures

Technical Specifications

Token Parameters

  • ERC20 compliant
  • Burnable token functionality
  • Configurable initial supply
  • Developer allocation percentage
  • Custom token icon support (IPFS)

AMM Parameters

  • Constant product formula
  • Price impact calculations
  • Reserve ratio maintenance
  • Minimum liquidity requirements

Anti-Manipulation

  • Reserve ratio monitoring
  • Minimum liquidity requirements
  • Slippage protection
  • Reentrancy guards

Price Stability

  • Basis value mechanism
  • Dynamic pricing algorithm
  • Reserve balance checks
  • Fee accumulation system

Best Practices

Trading

  • Include slippage protection
  • Monitor gas costs
  • Check price impact
  • Verify reserves

Staking

  • Monitor reward rates
  • Track cooldown periods
  • Verify reward calculations
  • Check stake amounts

Integration Guide

Contract Deployment

  1. Deploy using DeploymentFactory
  2. Configure initial parameters:
    • Token name and symbol
    • Initial supply
    • Developer allocation
    • Basis value (minimal reserve ratio)
    • Token icon IPFS hash

Mainnet Deployments

ContractNetworkAddressExplorerStatus
DeploymentFactoryBase0x719CaAe0704eb116F623b3BfD7c60aCf7C49a68cView on Basescan✅ Verified

Trading Integration

Buy tokens

await dswapContract.buyTokens(minTokenAmount, {value: ethAmount});

Sell tokens

await dswapContract.sellTokens(tokenAmount, minEthAmount);

Staking Integration

Stake tokens

await stakeYContract.stake(amount);

Claim rewards

await stakeYContract.claimRewards();

Withdraw stake

await stakeYContract.withdraw(amount);

Contract ABIs and Examples

Integration Examples

DswapBuild Contract Integration

const DswapBuildAbi = require('./DswapBuildAbi.js');

// Initialize contract
const dswapContract = new ethers.Contract(
DSWAP_ADDRESS,
DswapBuildAbi,
signer
);

// Example usage
const price = await dswapContract.getCurrentPrice();
const reserves = await dswapContract.getReserves();

StakeY Contract Integration

const StakeYAbi = require('./StakeyAbi.js');

// Initialize contract
const stakeContract = new ethers.Contract(
STAKE_ADDRESS,
StakeYAbi,
signer
);

// Example usage
const stakedAmount = await stakeContract.getStakedAmount(userAddress);
const earnedRewards = await stakeContract.earned(userAddress);

Full Contract Methods

DswapBuild Methods

// View Functions
getCurrentPrice()
getReserves()
getTokenReserve()
getEthReserve()
getAccumulatedFeesInToken()
getAccumulatedFeesInETH()
getEstimatedTokensForETH(ethAmount)
getEstimatedETHForTokens(tokenAmount)

// State-Changing Functions
buyTokens(minTokenAmount)
sellTokens(tokenAmount, minEthAmount)
claimFees()

StakeY Methods

// View Functions
earned(address)
earnedInToken(address)
getContractBalance()
getRewardTokenReserve()
getStakedAmount(address)
rewardPerToken()
rewardTokenPerToken()

// State-Changing Functions
stake(amount)
withdraw(amount)
claimRewards()
updateRewardToken(address)
updateRewardTokenReserve(amount)
updateStakingToken(address)

Events to Monitor

DswapBuild Events

TokensPurchased(address indexed buyer, uint256 ethAmount, uint256 tokenAmount)
TokensSold(address indexed seller, uint256 tokenAmount, uint256 ethAmount)
ReservesUpdated(uint256 newEthReserve, uint256 newTokenReserve)
FeesWithdrawn(address indexed recipient, uint256 tokenAmount, uint256 ethAmount)
FeeAccumulated(uint256 tokenFeeAmount, uint256 ethFeeAmount)

StakeY Events

FundsReceived(address indexed sender, uint256 amount)
RewardCalculated(address indexed user, uint256 reward)
RewardPaid(address indexed user, uint256 reward)
RewardsClaimed(address indexed user, uint256 reward)
StakingTokenChanged(address indexed newToken)
RewardTokenChanged(address indexed newToken)
Staked(address indexed user, uint256 amount)
Withdrawn(address indexed user, uint256 amount)

Example Implementation Files

⚠️ IMPORTANT DISCLAIMER

Risk Warning

USE AT YOUR OWN RISK. PLEASE READ THIS DISCLAIMER CAREFULLY.

Experimental Technology

DSwap protocol is experimental technology. By using this protocol, you acknowledge and agree that:

  • You are using the software at your own risk
  • You have sufficient knowledge and experience to evaluate the risks and merits of using this protocol
  • You understand and accept all risks associated with using experimental blockchain technology

Financial Risk

  • You may lose ALL of your funds
  • Past performance is not indicative of future results
  • The protocol has not been audited by any third-party security firms
  • Smart contracts may contain bugs or vulnerabilities
  • Market volatility can lead to significant losses
  • Liquidity risks may prevent you from exiting positions

Technical Risks

  • Smart contract failures could result in loss of funds
  • Network congestion may prevent transactions
  • Oracle failures could affect price calculations
  • Frontend interfaces may experience technical issues
  • Blockchain reorganizations could affect transactions
  • This protocol is provided "AS IS" without warranty of any kind
  • The developers assume no responsibility for losses
  • This is not financial advice
  • Users must comply with their local regulations
  • Protocol may be unavailable in certain jurisdictions

Security Recommendations

  1. Start with small amounts to test functionality
  2. Never invest more than you can afford to lose
  3. Verify all transaction details before confirming
  4. Keep your private keys secure
  5. Be cautious of phishing attempts
  6. Double-check contract addresses

Known Limitations

  • Gas costs may be high during network congestion
  • Price impact on large trades
  • Slippage during volatile market conditions
  • Reward calculation delays
  • Cooldown periods for certain operations

No Guarantees

The protocol developers make:

  • No guarantee of profits
  • No guarantee of availability
  • No guarantee of accuracy
  • No guarantee of performance
  • No guarantee against bugs or exploits

By using this protocol, you explicitly acknowledge having read this disclaimer and agree to all terms and conditions.