Querying Data

The SDK provides a query module for accessing licensing information and agreement history. The query module automatically connects to the appropriate data source based on your network configuration:

import { SpaceportSDK, SpaceportChainType, QueryClient } from '@spaceport/sdk'

async function queryExamples() {
  // Option 1: Access the query module via the SDK instance
  // This automatically uses the environment from the SDK configuration
  const sdk = SpaceportSDK.create({ chain: 'devnet' })
  console.log(`Using environment: ${sdk.query.getEnvironment()}`) // 'devnet'

  // Query active listings
  const activeListings = await sdk.query.listings.getActiveListings({ first: 10 })
  console.log(`Found ${activeListings.totalCount} active listings`)

  // Option 2: Use the QueryClient directly with a specific environment
  // This is useful for standalone queries or when you need to query multiple environments
  const queryClient = new QueryClient('testnet')
  const testnetListings = await queryClient.listings.getActiveListings({ first: 5 })

  // Common query examples

  // Get listings by licensor
  const licensorAddress = '0x1234...'
  const licensorListings = await sdk.query.listings.getListingsByLicensor(licensorAddress)

  // Get agreements for a licensee
  const licenseeAddress = '0xabcd...'
  const licenseeAgreements = await sdk.query.agreements.getAgreementsByLicensee(licenseeAddress)

  // Get agreements for a licensor
  const licensorAgreements = await sdk.query.agreements.getAgreementsByLicensor(licensorAddress)

  // Get a specific listing by ID
  const listingId = '0x1234...' // Listing identifier
  const listing = await sdk.query.listings.getListingById(listingId)

  // Get active agreements
  const activeAgreements = await sdk.query.agreements.getBindingAgreements()

  // Get smart licenses
  const smartLicenses = await sdk.query.smartLicenses.getSmartLicenses({ first: 5 })

  // Get a specific smart license by its hash
  const smartLicenseHash = '0xabcd...'
  const smartLicense = await sdk.query.smartLicenses.getSmartLicenseByHash(smartLicenseHash)

  // Execute custom queries using the underlying GraphQL client
  const client = sdk.query.getGraphQLClient()
  const customQuery = `
    query {
      listingObjects(where: { price_gt: "1000000000000000000" }) {
        id
        price
        licensor
        nftId
      }
    }
  `
  const result = await client.query(customQuery).toPromise()
}