Skip to main content

Type Safety with ts-rest

The Long.xyz API uses ts-rest to provide compile-time and runtime type safety:
  • Contract-based: All endpoints are defined in typed contracts
  • Zod validation: Request/response bodies are validated with Zod schemas
  • Auto-completion: Full TypeScript IntelliSense support
  • Runtime safety: Responses are validated at runtime

Response Handling

All ts-rest responses follow this structure:
const response = await client.assets.getAsset({
  params: { assetAddress: '0x...' },
});

// response.status: number (HTTP status code)
// response.body: ResponseBody (typed based on status)
// response.headers: Headers
Always check the status before accessing the body:
if (response.status === 200) {
  // response.body.result is typed correctly
  console.log(response.body.result);
} else if (response.status === 404) {
  console.error('Not found');
}

Authentication

Every request requires an API key:
const client = initClient(rootContract, {
  baseUrl: 'https://api.long.xyz/v1',
  baseHeaders: {
    'X-API-KEY': process.env.LONG_API_KEY!,
  },
});
Never commit API keys to version control. Use environment variables.

Error Handling

Handle different status codes appropriately:
switch (response.status) {
  case 200:
    // Success
    break;
  case 400:
    // Bad request (invalid parameters)
    break;
  case 401:
    // Unauthorized (invalid API key)
    break;
  case 404:
    // Not found
    break;
  case 500:
    // Server error
    break;
}

Pagination

List endpoints support pagination:
const response = await client.assets.listAssets({
  query: {
    limit: 10,  // Results per page (max 50)
    offset: 0,  // Skip first N results
  },
});

Hex Addresses

All Ethereum addresses are validated as hex strings:
import { hex } from '@longdotxyz/shared';

// Valid hex address format
const address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e';

// Invalid - will fail validation
const invalid = '0xINVALID';

BigInt Values

Large numbers (token amounts, prices) are returned as strings:
const asset = response.body.result;

// Convert to BigInt for calculations
const totalProceeds = BigInt(asset.auction_pool.pool_current_total_proceeds);
const maxProceeds = BigInt(asset.auction_pool.pool_config_max_proceeds);

const remaining = maxProceeds - totalProceeds;