Authentication overview

0x, a decentralized exchange infrastructure, employs distinct authentication mechanisms depending on the nature of the interaction. For programmatic access to the 0x API, primarily for read-only operations, liquidity queries, and managing API request rates, developers utilize API keys. These keys serve to identify the client making requests and enforce rate limits, ensuring fair usage and preventing abuse of the public API infrastructure 0x API documentation.

Conversely, critical actions involving on-chain state changes, such as executing token swaps or placing orders, do not rely on traditional API keys for authentication. Instead, these operations require cryptographic signatures generated by a user's blockchain wallet. This decentralized approach ensures that users retain full control over their funds and that transactions are authorized directly on the blockchain, aligning with the principles of Web3 and decentralized finance (DeFi).

The 0x API acts as an aggregator, providing access to liquidity across various sources. While API keys help manage access to this aggregation service, the ultimate approval for any value transfer or state change on the blockchain always rests with the user's wallet signature. This dual-method authentication strategy separates access control for API services from transaction authorization on the underlying blockchain networks like Ethereum or Polygon Polygon PoS chain details.

Supported authentication methods

0x supports two primary authentication methods, each designed for specific types of interactions:

  • API Keys: Used for authenticating developer applications when interacting with the 0x API.
  • Wallet Signatures: Used for authorizing on-chain transactions, such as token swaps.

The table below outlines the specific use cases and security considerations for each method:

Method When to Use Security Level
API Keys Accessing the 0x API for data retrieval, liquidity quotes, order book information, and managing request rate limits. Primarily for off-chain API interactions. Moderate. Protects API access and rate limits. Compromise could lead to service disruption or unauthorized data access, but not direct fund loss.
Wallet Signatures Authorizing on-chain transactions, including token swaps, liquidity provision, and any operation that alters blockchain state. Required for all financial transactions. High. Cryptographically secures transactions. Compromise of a private key leads to potential loss of funds. Aligns with Web3 security models Web3 definition on MDN.

Developers implementing with 0x will typically use both methods in conjunction: an API key for their application to query the 0x API for optimal trade routes, and then prompt the user to sign the final transaction with their wallet to execute the trade on-chain.

Getting your credentials

For API Keys

To obtain an API key for the 0x API, developers typically need to register on the 0x developer portal or a similar service that grants access to the API infrastructure. The process generally involves:

  1. Navigating to the 0x developer documentation or a designated API key management page 0x official documentation.
  2. Registering an account or logging in.
  3. Generating a new API key through a dashboard interface.
  4. Configuring any necessary permissions or rate limits associated with the key (though 0x API keys are often primarily for identification and rate limiting).

Once generated, API keys should be treated as sensitive information and stored securely to prevent unauthorized use. 0x's documentation provides specific instructions on how to set up and manage these keys.

For Wallet Signatures

Wallet signatures do not require pre-obtained credentials from 0x. Instead, they rely on a user's existing blockchain wallet, such as MetaMask, WalletConnect, or a hardware wallet. The process involves:

  1. A user connecting their wallet to a decentralized application (dApp) that integrates with 0x.
  2. The dApp preparing a transaction (e.g., a token swap) and presenting it to the user's wallet for approval.
  3. The user reviewing the transaction details within their wallet interface.
  4. The user cryptographically signing the transaction using their wallet's private key.
  5. The signed transaction being broadcast to the blockchain network for execution.

This method ensures that the user is always in control of their assets and explicitly authorizes every on-chain operation. Developers need to integrate wallet connection libraries and transaction signing flows into their dApps, rather than managing user credentials directly.

Authenticated request example

When making API requests to the 0x API that require an API key, the key is typically passed in the request headers. For example, using cURL:

curl -X GET \
  'https://api.0x.org/swap/v1/quote?buyToken=DAI&sellToken=WETH&sellAmount=1000000000000000000' \
  -H '0x-Api-Key: YOUR_API_KEY'

In this example, YOUR_API_KEY should be replaced with the actual API key obtained from the 0x developer portal. The 0x-Api-Key header is the standard way to transmit the key for identification and rate limiting. The 0x TypeScript/JavaScript SDK also provides methods to configure API keys, abstracting the header management:

import { ZeroEx } from '@0x/asset-swapper'; // This is a conceptual example, actual SDK usage may vary slightly
import { Web3Wrapper } from '@0x/web3-wrapper';

const API_KEY = 'YOUR_API_KEY';

// Initialize the 0x client with the API key
const zeroEx = new ZeroEx({ ... /* provider, networkId, etc. */, zeroExApiKey: API_KEY });

// Example: Getting a swap quote
async function getQuote() {
  try {
    const quote = await zeroEx.getSwapQuote(
      'DAI',
      'WETH',
      '1000000000000000000', // 1 WETH in wei
      { skipValidation: true } // Example option
    );
    console.log('Swap Quote:', quote);
  } catch (error) {
    console.error('Error fetching quote:', error);
  }
}

getQuote();

For wallet-signed transactions, the process involves interacting with a Web3 provider (like MetaMask) to prompt the user for a signature. The 0x SDKs and libraries often facilitate this by providing methods to prepare transaction data that can then be passed to the user's connected wallet for signing and broadcasting. This typically involves using a Web3 provider library (e.g., ethers.js or web3.js) in conjunction with the 0x libraries.

import { ethers } from 'ethers';
import { BigNumber } from '@0x/utils';

// Assume provider and signer are already set up from user's connected wallet
// For example, using ethers.js with MetaMask
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
const userAddress = await signer.getAddress();

// This is a simplified conceptual example for transaction signing flow
// Real 0x swap execution involves more steps like approval of tokens, getting a quote, etc.
async function executeSwapWithWalletSignature() {
  // In a real scenario, you'd get a quote from 0x API first (using API key)
  // and then construct the transaction data based on that quote.
  const swapTarget = '0x_0x_Exchange_Proxy_Address'; // Replace with actual 0x Exchange Proxy address
  const callData = '0x...'; // The encoded calldata for the swap operation from a 0x quote
  const value = new BigNumber(0); // If ETH is being sent as part of the swap

  const tx = {
    to: swapTarget,
    data: callData,
    value: value.toString(),
  };

  try {
    const transactionResponse = await signer.sendTransaction(tx);
    console.log('Transaction sent:', transactionResponse.hash);
    await transactionResponse.wait();
    console.log('Transaction confirmed');
  } catch (error) {
    console.error('Error sending transaction:', error);
  }
}

// Call the function to initiate a swap requiring a wallet signature
// executeSwapWithWalletSignature();

Security best practices

Adhering to security best practices is crucial when integrating with 0x, particularly given the financial nature of decentralized exchange operations.

For API Keys

  • Keep API Keys Confidential: Never hardcode API keys directly into client-side code, commit them to version control systems (like Git), or expose them in public repositories. Store them as environment variables or use a secure secret management service.
  • Use Server-Side Proxies: For client-side applications, route API requests through a secure backend proxy server. This prevents exposing API keys directly to end-users and allows for additional logging and rate limiting.
  • Implement Rate Limiting and Monitoring: Even with API keys, implement your own application-level rate limiting to prevent abuse. Monitor API key usage for unusual patterns that might indicate compromise.
  • Rotate Keys Regularly: Periodically generate new API keys and revoke old ones. This minimizes the window of exposure if a key is compromised.
  • Principle of Least Privilege: If 0x were to introduce granular permissions for API keys (currently, they primarily manage rate limits), ensure keys only have the necessary permissions for their intended function.

For Wallet Signatures

  • Educate Users on Transaction Details: When prompting users to sign transactions, clearly display all relevant transaction details (e.g., tokens being swapped, amounts, gas fees) in an easily understandable format. This helps users verify the transaction before signing and prevents phishing attacks.
  • Verify Contract Addresses: Ensure that your application verifies the target contract address for any transaction (e.g., the 0x Exchange Proxy address) to prevent users from interacting with malicious contracts.
  • Handle Gas Fees Appropriately: Provide clear information about estimated gas fees and allow users to adjust them if necessary. Properly handle network congestion and potential transaction failures due to insufficient gas.
  • Secure Wallet Integration: Use established and audited libraries for wallet connection (e.g., web3-react, wagmi, ethers.js, web3.js) to ensure secure interaction with user wallets.
  • Protect Private Keys: Remind users about the importance of securing their private keys or seed phrases. Your application should never ask for or have access to a user's private key. Wallet providers are responsible for protecting these credentials. FIDO Alliance standards offer a framework for secure user authentication without exposing private keys FIDO Alliance overview.
  • Audit Smart Contract Interactions: If your application interacts directly with 0x smart contracts (beyond the API), ensure that those interactions are thoroughly audited for security vulnerabilities.