Skip to main content
In this recipe we’ll show you how to use the Codex api to fetch a list of swaps for a token, complete with filtering, sorting, and realtime updates. This data powers the transactions tables view on Defined.fi.
Swap

Queries

To get a list of swaps for a token, you can use the getTokenEvents query. For example, for the WBNB token on the BNB chain (networkId 56), you can use the following query:
Test this query in the Explorer →
query Events {
  getTokenEvents(
    query: {
      address: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"
      networkId: 56
    }
  ) {
    items {
      id
      token0Address
      token1Address
      token0SwapValueUsd
      token1SwapValueUsd
      transactionHash
    }
  }
}
To get more (paginate), you can use the cursor argument to get the next page of results. Modify the query to include the cursor like this:
Test this query in the Explorer →
query PaginatedEvents {
  getTokenEvents(
    cursor: "eyJpdiI6ImNhYmI1Y2UzMmUyYjRmYzRhOGU4NWM5Njc1NzFjZGEzIiwiY29udGVudCI6ImU4ZGNiNTI3YTRiZDJmYTRlNDNjNzE0ZTM3MGU1MDdjZjE5YjhiNTM4ZWE0NjUxM2MxMzlmYjA0OTQ4YTZjNTA1MmVmM2M1ZTdiNTNhOWIyZDczY2Q2NjYxYjM2MTllZTQ1ZDE2ZTJkMDJmYjllZTU2N2YwOTQ3OWNhYmY1NzRjZDNhZTJlM2IwMDQ3ZjZkZGQzODE1Mzk0YTNkMWExMzBiZTNkZTQ4MGUyOWQyNjRiYmFlNjMwMjQ1NzgwOGFhM2RhZDU1YmY0ZjNhZGFlNWYyNDM2NGJhMjY1OWZlZjI0MzQifQ=="
    query: {
      address: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"
      networkId: 56
    }
  ) {
    cursor
    items {
      id
      token0Address
      token1Address
      token0SwapValueUsd
      token1SwapValueUsd
      transactionHash
      timestamp
      blockNumber
    }
  }
}
Now you know how to use a paginated cursor to fetch more results. This pattern is used in many places in the Codex API, see getTokenEventsForMaker, holders for an example.

Realtime Updates

To get realtime updates, you can use the onTokenEventsCreated subscription.
Test this query in the Explorer →
subscription TokenEventsCreated {
  onTokenEventsCreated(
    input: {
      tokenAddress: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"
      networkId: 56
    }
  ) {
    events {
      id
      token0Address
      token1Address
      token0SwapValueUsd
      token1SwapValueUsd
      transactionHash
      timestamp
      blockNumber
    }
  }
}

Now you’ve got all you need to build a fully functional swap list view.

See more event queries in the api reference, like getTokenEventsForMaker, getEventLabels for an example.

And more subscriptions like