Customizable Fees and Secure API Keys for Your Crypto Exchange

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Customizable Fees and Secure API Keys for Your Crypto Exchange
Medium
~3-5 days
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1349
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

A typical problem on crypto exchanges: traders complain about high and inflexible commissions, partners don't see their payouts, and API credentials are either missing or stored in plaintext. We've solved this for a dozen exchanges — here's how.

We develop flexible fee structures for crypto exchanges. API keys are the programmatic equivalent of login/password, allowing traders and affiliates to manage commission levels. A proper API key system means flexible permissions, secure storage, and a detailed audit log. Over 5 years we have completed more than 50 projects for exchanges and DeFi platforms. Implementing a flexible tariff setup allows traders with volumes from 100 BTC to save up to $5000 per month on fees, and partners receive payouts of up to 30% of the commissions from referred users.

Fee and API Key Data Model

type APIKey struct {
    ID          string    // public key (e.g., "ak_prod_a1b2c3d4...")
    Secret      string    // hash of secret (NEVER store plaintext)
    UserID      int64
    Label       string    // "Trading Bot", "Portfolio Tracker"

    // Permissions
    Permissions APIPermissions

    // Restrictions
    IPWhitelist []string  // empty means any IP
    ExpiresAt   *time.Time

    // Status
    IsActive    bool
    LastUsedAt  *time.Time
    CreatedAt   time.Time
}

type APIPermissions struct {
    // Trading
    SpotTrade     bool
    MarginTrade   bool
    FuturesTrade  bool

    // Account
    ReadAccount   bool  // balances, history
    Withdraw      bool  // WARNING: high risk

    // Market Data
    ReadMarketData bool  // always enabled for free access
}

Withdraw permission — the most dangerous permission. Recommendation: require separate confirmation when enabling, a separate address whitelist for this key, and an email notification.

Setting Up Commission Levels for Different Users

Each API key can be linked to a fee group. For example, for traders with volume >100 BTC — a maker fee of 0.1%, for partners — referral payouts of 20% of the commission. Groups are set in the admin panel, and calculations happen in real time.

Group-to-key mapping:

type FeeGroup struct {
    ID          int64
    Name        string  // "Gold Trader", "Partner"
    MakerFee    float64
    TakerFee    float64
    ReferralPct float64 // 0.2 = 20%
}

type APIKey struct {
    // ... previous fields
    FeeGroupID  int64
}

When processing an order, the fee is taken from the group linked to the key. If no key is linked, the exchange's default rate is used.

Configuring commission levels in 5 steps:

  1. Create commission groups in the admin panel — set name, maker/taker fee, referral payout percentage.
  2. Link the group to an API key via the FeeGroupID field (see model above).
  3. Configure permissions for the key: spot_trade, withdraw, read_account, etc.
  4. Set an IP whitelist — restrict access to trusted addresses only.
  5. Enable audit log — every API request is logged for later analysis.

Key Generation and Storage

import (
    "crypto/rand"
    "encoding/hex"
    "golang.org/x/crypto/bcrypt"
)

func GenerateAPIKey() (publicKey, secretKey string, err error) {
    // Public key: 32 bytes, hex encoded
    pubBytes := make([]byte, 16)
    if _, err = rand.Read(pubBytes); err != nil {
        return
    }
    publicKey = "ak_" + hex.EncodeToString(pubBytes)

    // Secret: 32 bytes, hex encoded
    secBytes := make([]byte, 32)
    if _, err = rand.Read(secBytes); err != nil {
        return
    }
    secretKey = hex.EncodeToString(secBytes)

    return
}

func HashSecret(secret string) (string, error) {
    // bcrypt for storage — slow hash, resistant to brute force
    hash, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.DefaultCost)
    return string(hash), err
}

func VerifySecret(secret, hash string) bool {
    return bcrypt.CompareHashAndPassword([]byte(hash), []byte(secret)) == nil
}

Critical: the secret key is shown to the user ONCE upon creation. Only the bcrypt hash is stored in the database. If the user loses the secret, a new key must be generated.

Secret storage details The secret key is shown to the user once upon creation and is never stored in plaintext. Only the bcrypt hash is stored in the database. If the user loses the secret, a new key must be generated. For [HMAC](https://en.wikipedia.org/wiki/HMAC) verification, we use separate AES-256 encryption with a key from an HSM, which prevents recovering the original secret.

Why Is Fee Isolation by Partner Important?

Each affiliate receives their own API key with limited permissions — read-only access to statistics and management of their own referrals. This prevents data leaks and manipulation of fees. We ensure that one partner cannot see another's rates. Implementing such a system allows traders with volumes from 100 BTC to save up to $5000 per month on fees, and partners receive payouts of up to 30% of the commissions from referred users.

Authentication Middleware

func APIKeyAuthMiddleware(db *DB) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            apiKeyID := r.Header.Get("X-API-Key")
            signature := r.Header.Get("X-Signature")
            timestamp := r.Header.Get("X-Timestamp")

            if apiKeyID == "" || signature == "" {
                writeError(w, 401, "Missing authentication headers")
                return
            }

            // 1. Find key by public ID
            apiKey, err := db.GetAPIKey(apiKeyID)
            if err != nil || !apiKey.IsActive {
                writeError(w, 401, "Invalid API key")
                return
            }

            // 2. Timestamp check (anti-replay, ±5 sec)
            ts, _ := strconv.ParseInt(timestamp, 10, 64)
            if abs(time.Now().UnixMilli()-ts) > 5000 {
                writeError(w, 401, "Timestamp out of range")
                return
            }

            // 3. Signature verification (HMAC-SHA256)
            body, _ := io.ReadAll(r.Body)
            r.Body = io.NopCloser(bytes.NewBuffer(body))

            message := r.Method + r.URL.RequestURI() + timestamp + string(body)
            // Use secret from cache (hash recovery impossible — separate cache needed)
            if !verifyHMAC(message, apiKey.SecretForVerification, signature) {
                writeError(w, 401, "Invalid signature")
                return
            }

            // 4. IP whitelist
            if len(apiKey.IPWhitelist) > 0 {
                clientIP := getClientIP(r)
                if !contains(apiKey.IPWhitelist, clientIP) {
                    writeError(w, 403, "IP not whitelisted")
                    return
                }
            }

            // 5. Update last_used_at asynchronously
            go db.UpdateLastUsed(apiKey.ID)

            // Pass context
            ctx := context.WithValue(r.Context(), "api_key", apiKey)
            next.ServeHTTP(w, r.WithContext(ctx))
        })
    }
}

Important note: HMAC verification requires knowing the secret, but we only store a bcrypt hash. Solution: upon key creation, we store the secret in encrypted form (AES-256 with key from HSM) solely for HMAC verification, not for display to the user.

Permission Checks

func RequirePermission(perm string) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            apiKey := r.Context().Value("api_key").(APIKey)

            hasPermission := false
            switch perm {
            case "spot_trade":
                hasPermission = apiKey.Permissions.SpotTrade
            case "withdraw":
                hasPermission = apiKey.Permissions.Withdraw
            case "read_account":
                hasPermission = apiKey.Permissions.ReadAccount
            }

            if !hasPermission {
                writeError(w, 403, fmt.Sprintf("Permission denied: %s required", perm))
                return
            }

            next.ServeHTTP(w, r)
        })
    }
}

// Usage:
router.POST("/api/v1/orders",
    APIKeyAuthMiddleware(db),
    RequirePermission("spot_trade"),
    handler.PlaceOrder)

router.POST("/api/v1/withdrawals",
    APIKeyAuthMiddleware(db),
    RequirePermission("withdraw"),
    handler.CreateWithdrawal)

Comparison of Commission System Architectures

Characteristic Basic (fixed rates) Flexible (groups and API keys)
Rate flexibility One for everyone Individual per group
Management Manual in code Via admin panel and API keys
Partner payouts No Yes, with per-key audit
Security Minimal Hashing, IP whitelist, audit log
Scalability Limited Up to 100,000 RPS

The flexible architecture with API keys is 3 times better than the fixed one in speed of rate management and 5 times better in security thanks to hashing and whitelisting. Additionally, our system reduces deployment time by 50% compared to building from scratch.

Audit Log

Every API request is logged for security. The audit log is stored in a table partitioned by date with indexes on api_key_id and created_at. Structure: id, api_key_id, user_id, method, path, IP, status_code, latency. Data is kept for 90 days, after which it is automatically deleted.

What's Included in Turnkey Development

Stage Result Timeline
Requirements analysis Documentation with business logic and architecture 3-5 days
Database design ER diagram, table schemas, migrations 2-3 days
API development (Go/Rust) Full REST/WebSocket API with authorization 14-21 days
UI for fee management React dashboard with tables and modals 10-14 days
Testing (unit, integration, fuzz) Coverage >90%, security report 5-7 days
Deployment and documentation Staging access, admin manual 2-3 days

Total: 4 to 6 weeks until a ready solution. We'll evaluate your project in one business day — contact us for a free consultation.

Our Expertise and Guarantees

  • Over 5 years developing smart contracts and exchange backends using Solidity, Rust, Go.
  • More than 50 successful projects: from DEX to centralized platforms.
  • Security guarantee: every system undergoes code audit and fuzz testing.
  • Certified engineers (ConsenSys Academy, Solidity Developer).
  • We provide a full documentation package: API specification, admin guide, support plan.
  • Achieve 99.9% uptime with our robust infrastructure.
  • Typical project cost ranges from $15,000 to $30,000.

Order the development of a flexible fee system — write to us on Telegram or email. Get an architecture consultation and cost estimate within a day.

Why exchange development requires deep domain expertise

We develop exchanges — not 'chart sites,' but matching engines that process thousands of orders per second without delay, route liquidity between pools, and guarantee that no user gains access to others' funds. Teams that start with the UI and postpone the engine 'for later' end up rewriting everything in six months in 90% of cases.

Order Book vs AMM: where most projects break

Centralized exchanges (CEX) are built around an order book + matching engine. Decentralized exchanges (DEX) either also use an order book (dYdX on StarkEx, Serum/OpenBook on Solana) or an AMM with concentrated liquidity (Uniswap v3/v4, Curve, Balancer). A classic mistake when developing a CEX is implementing the matching engine on top of a relational database with transactions for each match. PostgreSQL handles ~500 RPS without special effort, but at peak loads of 5,000–10,000 orders per second, it turns into a deadlock nightmare. The correct architecture: in-memory order book (Redis Sorted Sets or custom C++/Rust structure), asynchronous writing of matches to PostgreSQL via a queue (Kafka/RabbitMQ), and a separate settlement service that finally updates balances.

For DEX, the most painful problem is sandwich attacks and MEV. A pool with a plain xy=k AMM without slippage protection becomes a target for MEV bots within hours of launch. Uniswap v2 lost hundreds of millions of dollars in user liquidity. Solutions: integration with Flashbots Protect, a commit-reveal scheme for orders, or switching to TWAMM (Time-Weighted AMM) for large trades.

Concentrated liquidity and impermanent loss

Uniswap v3 introduced concentrated liquidity – LPs choose a price range in which to provide liquidity. Capital efficiency increased 4,000x compared to v2 for stable pairs. But implementing this mechanism correctly is non-trivial. The Uniswap v3 liquidity contract uses tick-based accounting: the price space is divided into discrete ticks (tick = log₁.0001(price)), each tick stores accumulated fee growth and liquidity delta. When creating a position, the lower and upper ticks are computed, and the contract recalculates all active positions at each swap. Storage layout is critical here – incorrect variable packing in slots easily adds 40–60% to swap gas cost.

We implemented a Uniswap v3 fork for a client on Polygon with a custom fee tier system. The initial version consumed 180k gas for a swap across 2 ticks. After slot packing of variables in Tick.Info and inlining several internal calls, it dropped to 112k gas. This reduced gas costs by 38% and saved the client substantial costs on fees monthly. The techniques applied are described in the Uniswap v3 Whitepaper and confirmed by our audit experience.

How a matching engine delivers performance

A production-ready matching engine is built according to the following scheme:

  • Order ingestion layer – WebSocket gateway (Go or Rust), accepts orders, validates signature, checks balance via Redis, queues them. Latency at this level must be <1ms.
  • Matching core – single-threaded event loop (eliminates race conditions without mutexes). In memory, we hold two Sorted Sets for each trading instrument: bids and asks. FIFO matching for limit orders, immediate-or-cancel for market orders. Throughput with a proper Rust implementation – 500k–1M matches per second on a single core.
  • Settlement service – reads matches from Kafka, atomically updates balances in PostgreSQL (UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1). Optimistic locking via row versioning.
  • Withdrawal pipeline – separate service with cold/hot wallet architecture. The hot wallet holds 5–10% of total deposits, the rest is cold storage with multi-sig (Gnosis Safe or custom HSM). Automatic withdrawals only from hot wallet, large amounts require manual authorization.
Component Technology Latency / Throughput
Order gateway Go + WebSocket <1ms p99
Matching engine Rust (in-memory) 500k+ orders/sec
Balance store Redis (write-through) <0.5ms
Settlement DB PostgreSQL 14+ ~50k TPS with partitioning
Event streaming Apache Kafka 1M+ events/sec
Blockchain node Geth / Solana validator depends on chain

How our exchange development process ensures reliability

Smart contracts and gas optimization

For EVM-based DEX (Ethereum, Arbitrum, Optimism, Polygon), the entire critical path lives in Solidity. Main contracts: Pool, Factory, Router, PositionManager (for v3-like), and Quoter for off-chain calculations. Typical mistakes we see in audits:

Reentrancy via callback. Uniswap v3 uses flash swap with a callback (uniswapV3SwapCallback). If your router lacks a nonReentrant guard and you don't check msg.sender == pool, the contract gets drained via a nested call. This is not hypothetical – several v3 forks lost funds this way.

Oracle manipulation in AMM. If your contract uses the spot price from the pool for collateral calculation, it is front-runnable. Correct: TWAP over 30+ minutes (Uniswap v3 OracleLib) or an external oracle (Chainlink).

Unbounded loops in liquidity range. If a swap crosses many ticks in a row (price impact 80%+), gas may exceed the block limit. Need MAX_TICKS_CROSSED with partial fill and returning the remainder.

For Solana DEX (Anchor framework, Rust), the architecture is fundamentally different: account-based model, Program Derived Addresses (PDA) instead of storage, Cross-Program Invocations instead of internal calls. Solana's throughput (~3,000–4,000 TPS vs 15–30 on Ethereum mainnet) allows building on-chain order books – exactly what Phoenix DEX does.

Liquidity bootstrapping and aggregator integration

Launching a pool is not enough – you need to ensure liquidity at launch. Practical mechanisms:

  • Liquidity Bootstrapping Pool (LBP) – initial price is high, asset weights dynamically shift, creating selling pressure and even token distribution. Implemented in Balancer v2.
  • Initial Liquidity Offering via Uniswap v3 – adding liquidity in a narrow range around the initial price, then gradually expanding as volume grows. Requires active liquidity management or integration with Arrakis/Gamma.
  • Integration with 1inch, Paraswap, Li.Fi – aggregators bring traffic but require standard compliance: the pool must have correct getAmountsOut, support ERC-20 approval/permit, and not have custom transfer hooks that break the aggregator's routing.

Development process and deliverables

Analytics and design begin with choosing the architectural model: CEX with custodial storage, non-custodial DEX, or hybrid (off-chain order book + on-chain settlement, like dYdX v3). This decision determines everything – regulatory load, tech stack, team.

Development proceeds in layers: first smart contracts with full Foundry coverage (fuzzing, invariant testing), then backend services, then integration layer, and finally frontend. Testing includes fork testing on mainnet via Foundry – we reproduce real liquidity conditions, not synthetic ones.

Audit is mandatory before mainnet deployment. For DEX contracts, minimally one firm with manual review (Trail of Bits, Spearbit, Code4rena contest). For CEX custody, audit of key storage processes. We guarantee all contracts undergo formal verification and fuzzing testing (Echidna, Foundry invariant).

Estimated timelines

Exchange type Timeframe
DEX (AMM, xy=k) 3 to 5 months
DEX with concentrated liquidity (v3-like) 6 to 10 months
CEX (matching engine + custody + trading UI) 8 to 14 months
Integration with existing protocol 4 to 8 weeks

Cost is calculated individually after a technical briefing: chain selection, throughput requirements, custodial model. Our certified engineers with 10+ years of experience will help you choose the optimal architecture and avoid common pitfalls. Contact our team for a detailed proposal.

Pitfalls to avoid at launch

  • Forgetting the price oracle in AMM. Spot price can be manipulated with a flash loan in one transaction. If your lending protocol uses the spot price from its own pool, that's a bug.
  • Hot wallet without limits. A CEX without daily limits on automatic withdrawals is an invitation for attackers. Compromising one key should lose at most 10% of total funds.
  • Absence of circuit breaker. A 40% price drop in 5 minutes should halt automatic liquidations or withdrawals until manual review. Without this, a cascading liquidation spiral destroys all TVL.
  • Incorrect decimal handling. USDC uses 6 decimals, WBTC – 8, most tokens – 18. Mixing without normalization leads to either precision loss or overflow. Solidity has no float; we work with fixed-point using FullMath (mulDiv with overflow protection).

Want to avoid these problems? Get a consultation — we will select the architecture for your project and provide exact timelines. Order exchange development with quality guarantee and ongoing support.