> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokenlayer.network/llms.txt
> Use this file to discover all available pages before exploring further.

# Trade tokens (buy or sell)

> 
    Prepares a transaction to buy or sell tokens. Supports multiple trade types:
    - **Buy exact input**: Spend specific USD amount
    - **Buy exact output**: Receive specific token amount
    - **Sell exact input**: Sell specific token amount
    - **Sell exact output**: Receive specific USD amount

    Automatically uses RobinSwap or UniswapV3 based on token graduation status.

    **Anti-Sniping & Initial Buy Fees:**
    - The first 6 seconds of trading (equivalent in blocks for each chain) has increased fees to prevent sniping
    - Fees start at 80% and decrease linearly to 1% over the first 6 seconds worth of blocks
    - This fee structure applies to all initial purchases, including the first buyer
    - The quoter automatically includes these fees in all price quotes, so the amounts returned reflect the actual cost including anti-sniping fees
    - After the initial 6-second window, normal trading fees apply

    **USD Rewards Attribution:**
    - **Builder attribution**: Set custom builder fees (in basis points) to earn USD rewards on transactions
    - **Token referral**: Enable affiliate programs by specifying referral addresses for token trades
    - USD rewards are processed in real-time on-chain with no third parties involved
    - Token referrals have no additional cost to users - enabling affiliate programs onchain
  



## OpenAPI

````yaml post /trade-token
openapi: 3.0.3
info:
  title: Token Layer API
  version: 1.0.0
  description: |2-

          Token Layer is an omnichain token trading platform where users can create and trade tokens across multiple chains.

          This API provides comprehensive access to token operations, trading, earnings,
          blockchain transactions, and portfolio management.

          ## Base URL
          All endpoints are accessed via: `https://api.tokenlayer.network/{endpoint}`

          ## Authentication
          Most endpoints require authentication using an JWT token or API key passed as a Bearer token in the Authorization header.

          ## Rate Limiting
          API calls are rate limited per user. Please implement appropriate backoff strategies.
        
  contact:
    name: Token Layer API Support
    url: https://app.tokenlayer.network
servers:
  - url: https://api.tokenlayer.network/functions/v1
    description: Production server
  - url: https://api.tokenlayer.network/functions/v1
    description: Staging server
security: []
tags:
  - name: Tokens
    description: Token creation, browsing, search, trading, and price operations
  - name: Transactions
    description: Blockchain transactions (send, tip, ownership checks)
paths:
  /trade-token:
    post:
      tags:
        - Transactions
        - Tokens
      summary: Trade tokens (buy or sell)
      description: |2-

            Prepares a transaction to buy or sell tokens. Supports multiple trade types:
            - **Buy exact input**: Spend specific USD amount
            - **Buy exact output**: Receive specific token amount
            - **Sell exact input**: Sell specific token amount
            - **Sell exact output**: Receive specific USD amount

            Automatically uses RobinSwap or UniswapV3 based on token graduation status.

            **Anti-Sniping & Initial Buy Fees:**
            - The first 6 seconds of trading (equivalent in blocks for each chain) has increased fees to prevent sniping
            - Fees start at 80% and decrease linearly to 1% over the first 6 seconds worth of blocks
            - This fee structure applies to all initial purchases, including the first buyer
            - The quoter automatically includes these fees in all price quotes, so the amounts returned reflect the actual cost including anti-sniping fees
            - After the initial 6-second window, normal trading fees apply

            **USD Rewards Attribution:**
            - **Builder attribution**: Set custom builder fees (in basis points) to earn USD rewards on transactions
            - **Token referral**: Enable affiliate programs by specifying referral addresses for token trades
            - USD rewards are processed in real-time on-chain with no third parties involved
            - Token referrals have no additional cost to users - enabling affiliate programs onchain
          
      operationId: tradeToken
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TradeTokenRequest'
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TradeTokenResponse'
        '400':
          description: Bad request - Invalid parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: Unauthorized - Invalid or missing authentication
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - BearerAuth: []
components:
  schemas:
    TradeTokenRequest:
      type: object
      properties:
        tokenId:
          type: string
          format: uuid
        userAddress:
          type: string
          pattern: ^0x[a-fA-F0-9]{40}$
          description: >-
            User wallet address (optional - if not provided, will use user's
            Privy wallet from user_wallets table)
          example: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
        builder:
          $ref: '#/components/schemas/Builder'
        token_referral:
          type: string
          pattern: ^0x[a-fA-F0-9]{40}$
          description: >-
            Token referral address for attribution (optional - defaults to zero
            address). Used to attribute referral fees to a specific address.
          example: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
        chainSlug:
          $ref: '#/components/schemas/ChainSlug'
        direction:
          type: string
          enum:
            - buy
            - sell
        buyAmountUSD:
          type: number
          minimum: 0
          exclusiveMinimum: true
        buyAmountToken:
          anyOf:
            - type: number
              minimum: 0
              exclusiveMinimum: true
            - type: string
          description: >-
            Token amount to buy (number for regular amounts, string for exact
            wei values at 100%)
          example: 1000
        sellAmountToken:
          anyOf:
            - type: number
              minimum: 0
              exclusiveMinimum: true
            - type: string
          description: >-
            Token amount to sell (number for regular amounts, string for exact
            wei values at 100%)
          example: 1000
        sellAmountUSD:
          type: number
          minimum: 0
          exclusiveMinimum: true
      required:
        - tokenId
        - chainSlug
        - direction
    TradeTokenResponse:
      type: object
      properties:
        success:
          type: boolean
          enum:
            - true
        transaction:
          type: object
          properties:
            to:
              type: string
            data:
              type: string
            value:
              type: string
            gasLimit:
              type: string
            chain:
              $ref: '#/components/schemas/ChainSlug'
          required:
            - to
            - data
            - value
            - gasLimit
            - chain
      required:
        - success
        - transaction
    Error:
      type: object
      properties:
        success:
          type: boolean
          enum:
            - false
        error:
          type: string
      required:
        - success
        - error
      description: Error response
    Builder:
      type: object
      properties:
        code:
          type: string
          pattern: ^0x[a-fA-F0-9]{40}$
          description: Builder address for attribution
          example: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
        fee:
          type: integer
          minimum: 0
          maximum: 10000
          description: Builder fee in basis points (bps). 1 bps = 0.01%. Max 10000 (100%).
          example: 50
      required:
        - code
        - fee
      description: >-
        Builder attribution information (optional). Includes address and fee in
        bps.
    ChainSlug:
      type: string
      enum:
        - solana
        - solana-devnet
        - arbitrum
        - base
        - base-sepolia
        - avalanche
        - op-bnb
        - bnb
        - bnb-testnet
        - ethereum
        - monad
        - unichain
        - unichain-testnet
        - abstract
        - polygon
        - zksync
        - zksync-testnet
      description: >-
        Blockchain identifier. Supported chains: solana, solana-devnet,
        arbitrum, base, base-sepolia, avalanche, op-bnb, bnb, bnb-testnet,
        ethereum, monad, unichain, unichain-testnet, abstract, polygon, zksync,
        zksync-testnet
      example: base-sepolia
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT token or API key

````