Integration engineering

Validate swap API responses at runtime

Add runtime validation at the provider boundary so malformed or newly changed response shapes cannot reach wallet execution.

A TypeScript assertion can tell the compiler that JSON is a Quote. It cannot make the server return one. Runtime validation must happen before a quote becomes an executable application object.

The TypeScript handbook explains that type assertions disappear during compilation and add no runtime checking. Treat fetch response data as unknown until its required structure and semantics have been inspected.

Validate structure and relationships

Check the execution variant, chain, token identities, integer-string amounts, address or identifier formats, deadlines and required transaction fields. Then compare those values with the request. A valid-looking response for the wrong token pair is still invalid for the current trade.

Not every identifier is an EVM address. PancakeSwap's pool data can use either a contract address or a longer pool ID. Validate each field according to its documented role rather than applying an address regex everywhere.

Decide how to handle unknown fields

Additional informational fields can often be retained or ignored without breaking execution. An unknown execution engine, changed amount unit or missing recipient deserves a blocked state. Avoid coercions that convert null, empty strings or booleans into plausible numeric values.

Return a typed validation failure with the provider, schema version and safe field path. Do not expose a raw upstream object containing secrets or reusable signatures in the browser error.

Useful negative fixtures

Include missing data, an unexpected null, a very large amount, a wrong chain, an expired candidate and an unknown engine. Assert that each fails before a wallet request is constructed. A parser test that only accepts today's happy-path example cannot detect unsafe fallback behavior.

Sources & verification (2)

Source-check date is recorded in the article details. URLs are provided for manual verification. Use Copy to keep this page open.

  1. Everyday Types

    Type assertions do not add runtime validation

    https://www.typescriptlang.org/docs/handbook/2/everyday-types.html
  2. Response payloads

    Candidate response shapes

    https://developer.pancakeswap.finance/contracts/unified-swap-api/payloads

Continue reading

Swap API integration: quote, approve, simulate, submit