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:
- Create commission groups in the admin panel — set name, maker/taker fee, referral payout percentage.
- Link the group to an API key via the
FeeGroupIDfield (see model above). - Configure permissions for the key: spot_trade, withdraw, read_account, etc.
- Set an IP whitelist — restrict access to trusted addresses only.
- 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.







