SDKs overview

The 0x protocol offers a suite of tools, prominently including its official SDKs, designed to streamline interaction with its decentralized exchange infrastructure. These SDKs abstract away the complexities of direct smart contract interaction and API calls, providing developers with a more accessible interface for building decentralized finance (DeFi) applications. The primary focus of the 0x SDKs is to enable functionalities such as token swaps, order creation, liquidity aggregation, and interaction with the 0x Exchange Proxy and 0x API as detailed in the 0x documentation.

Developers utilizing the 0x SDKs can integrate various exchange features into their platforms, ranging from basic token-to-token swaps to more complex order book management. The SDKs are built to support multiple blockchain networks where 0x is deployed, ensuring broad compatibility for DeFi projects. This approach allows developers to focus on application logic rather than low-level blockchain mechanics, accelerating development cycles for dApps that require robust exchange capabilities.

Official SDKs by language

0x provides official SDKs primarily in TypeScript, which can also be used in JavaScript environments. These SDKs are maintained by the 0x Labs team and are designed to offer a consistent and reliable interface for interacting with the 0x protocol. The TypeScript SDK includes modules for various aspects of the 0x ecosystem, such as API interaction, smart contract utilities, and wallet integration helpers.

The official SDKs are regularly updated to reflect changes and improvements in the 0x protocol and underlying blockchain technologies. They serve as the recommended method for developers to integrate 0x functionality into their applications, providing type safety and comprehensive documentation.

Official 0x SDKs

Language Package Name Install Command Maturity
TypeScript/JavaScript @0x/asset-swapper npm install @0x/asset-swapper Stable
TypeScript/JavaScript @0x/contract-wrappers npm install @0x/contract-wrappers Stable
TypeScript/JavaScript @0x/subproviders npm install @0x/subproviders Stable
TypeScript/JavaScript @0x/order-utils npm install @0x/order-utils Stable
TypeScript/JavaScript @0x/utils npm install @0x/utils Stable

Installation

Installing the 0x SDKs typically involves using a package manager like npm or yarn. The core packages are available through the public npm registry. Developers can choose to install specific modules based on their project requirements, or a combination of modules to cover various functionalities. For example, the @0x/asset-swapper package is crucial for executing token swaps, while @0x/contract-wrappers provides interfaces for direct smart contract interaction.

To install the primary 0x SDK modules:


npm install @0x/asset-swapper @0x/contract-wrappers @0x/order-utils @0x/utils

Or, using Yarn:


yarn add @0x/asset-swapper @0x/contract-wrappers @0x/order-utils @0x/utils

After installation, the modules can be imported into your TypeScript or JavaScript project. It is important to ensure that your project's development environment is configured to handle TypeScript compilation if you are using TypeScript, or to use a modern JavaScript environment that supports ES module imports.

Quickstart example

This quickstart example demonstrates how to use the 0x SDK to fetch a quote for a token swap and execute it. This example assumes you have an Ethereum provider (e.g., MetaMask, Web3.js, Ethers.js) configured and available in your environment, as well as a wallet with sufficient funds to cover the swap and gas fees. The @0x/asset-swapper library simplifies the process of interacting with the 0x API to get optimal swap routes and execute trades.


import { getContractAddressesForChainOrThrow } from '@0x/contract-addresses';
import { create and use a provider for your network, e.g., ethers.js JsonRpcProvider
import { SupportedProvider, SwapQuoter, RfqClient, signOrder, ContractWrappers } from '@0x/asset-swapper';
import { BigNumber, providerUtils } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';

// --- Configuration ---
const CHAIN_ID = 1; // Example: Ethereum Mainnet
const RPC_URL = 'YOUR_ETHEREUM_RPC_URL'; // Replace with your RPC URL
const MAKER_PRIVATE_KEY = 'YOUR_PRIVATE_KEY'; // For signing orders (use with caution in production)
const TAKER_ADDRESS = 'YOUR_WALLET_ADDRESS'; // The address that will execute the swap

// Token addresses for WETH and USDC on Ethereum Mainnet
const WETH_ADDRESS = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
const USDC_ADDRESS = '0xA0b86991c6218b36c1d19D4a2e9Eb0CE3606eB48';

// Amount of WETH to sell (e.g., 0.1 WETH)
const WETH_AMOUNT_TO_SELL = new BigNumber('1e17'); // 0.1 WETH in WEI

async function executeSwap() {
    // 1. Initialize Provider and Web3Wrapper
    const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
    const web3Wrapper = new Web3Wrapper(provider);

    // 2. Get contract addresses for the specified chain
    const contractAddresses = getContractAddressesForChainOrThrow(CHAIN_ID);

    // 3. Initialize SwapQuoter (for getting quotes from 0x API)
    const swapQuoter = new SwapQuoter(provider, RPC_URL, { chainId: CHAIN_ID });

    // 4. Get a quote for selling WETH for USDC
    console.log('Fetching swap quote...');
    const quote = await swapQuoter.get  ({
        buyToken: USDC_ADDRESS,
        sellToken: WETH_ADDRESS,
        sellAmount: WETH_AMOUNT_TO_SELL,
    });

    if (!quote) {
        console.error('Could not get a swap quote.');
        return;
    }

    console.log(`Quote fetched: ${quote.grossBuyAmount.div(new BigNumber('1e6')).toFixed(2)} USDC for ${WETH_AMOUNT_TO_SELL.div(new BigNumber('1e18')).toFixed(2)} WETH`);

    // 5. Approve the 0x Exchange Proxy to spend your WETH
    console.log('Approving 0x Exchange Proxy...');
    const wethContract = new ContractWrappers(provider, { chainId: CHAIN_ID }).erc20Token;
    const allowance = await wethContract.getAllowanceAsync(WETH_ADDRESS, TAKER_ADDRESS, contractAddresses.erc20Bridge); // Assuming ERC20Bridge is the proxy

    if (allowance.isLessThan(WETH_AMOUNT_TO_SELL)) {
        const approvalTxHash = await wethContract.approveAsync(WETH_ADDRESS, contractAddresses.erc20Bridge, new BigNumber(2).pow(256).minus(1), { from: TAKER_ADDRESS });
        console.log(`Approval transaction sent: ${approvalTxHash}`);
        await web3Wrapper.awaitTransactionMinedAsync(approvalTxHash);
        console.log('Approval confirmed.');
    } else {
        console.log('Allowance already sufficient.');
    }

    // 6. Execute the swap
    console.log('Executing swap...');
    const txHash = await web3Wrapper.sendTransactionAsync({
        from: TAKER_ADDRESS,
        to: quote.to,
        data: quote.data,
        value: quote.value,
        gasPrice: quote.gasPrice,
        gas: quote.gas,
    });

    console.log(`Swap transaction sent: ${txHash}`);
    await web3Wrapper.awaitTransactionMinedAsync(txHash);
    console.log('Swap confirmed!');

    // 7. Verify balances (optional)
    const usdcContract = new ContractWrappers(provider, { chainId: CHAIN_ID }).erc20Token;
    const newUsdcBalance = await usdcContract.getBalanceAsync(USDC_ADDRESS, TAKER_ADDRESS);
    console.log(`New USDC balance: ${newUsdcBalance.div(new BigNumber('1e6')).toFixed(2)}`);

} 

executeSwap().catch(console.error);

This example outlines the fundamental steps: obtaining a quote, ensuring token approval for the 0x Exchange Proxy, and then submitting the transaction for the swap. For a production environment, considerations like error handling, gas management, and secure private key management (not storing directly in code) are critical. The 0x documentation offers more advanced examples and best practices for secure integration in its API quick start guide.

Developers working with decentralized applications often need to manage private keys securely. For backend services, environment variables or secret management systems are recommended. For client-side applications, users typically interact through browser extensions like MetaMask, which abstracts away private key handling. More information on secure key management practices can be found in general blockchain development guides, such as those provided by the Azure Blockchain documentation on integration patterns.

Community libraries

While 0x Labs provides official SDKs, the open-source nature of the 0x protocol has fostered the development of various community-contributed libraries and tools. These libraries often extend functionality, provide language bindings for other programming languages, or offer specialized utilities that complement the official offerings. Community libraries can be valuable for developers working in environments not directly supported by the official TypeScript SDK or for those seeking alternative implementations.

When considering community libraries, it is important to evaluate their maintenance status, community support, and security audits. Projects like 0x are part of a broader Web3 ecosystem where many tools are community-driven, as discussed in resources like the Mozilla Web3 Glossary. Always review the source code and community reputation before integrating third-party libraries into production systems.

Examples of potential community contributions include:

  • Python Wrappers: Libraries that wrap the 0x API for Python developers, enabling backend services to interact with the protocol.
  • Go Clients: Go language clients for interacting with 0x smart contracts or the 0x API, suitable for high-performance blockchain services.
  • Frontend Framework Integrations: Components or hooks designed for specific frontend frameworks (e.g., React, Vue) that simplify UI development for 0x-powered dApps.
  • Data Analytics Tools: Scripts or libraries for parsing 0x protocol data from blockchain explorers or API endpoints for analytics and monitoring.

Developers are encouraged to explore community forums, GitHub repositories, and the broader DeFi developer ecosystem to discover these resources. Contributions to the 0x ecosystem are also welcomed, allowing developers to build and share their own tools with the community.