Skip to main content

Branded Types

The GalaSwap SDK uses TypeScript branded types to prevent common mistakes when working with prices and amounts. These types help avoid, for example, mixing up regular prices with square root prices, which can lead to calculation errors.

What are Branded Types?​

Branded types are a TypeScript pattern that adds compile-time safety by "branding" primitive types with additional metadata. This prevents you from accidentally passing the wrong type of value to a function.

Available Branded Types​

Price Types​

TypeDescriptionUsage
PriceInInput price values (decimal string or BigNumber)When providing price parameters to functions
PriceCalculated price values (always BigNumber)When receiving price results from calculations
SqrtPriceInInput square root price values (decimal string or BigNumber)When providing square root price parameters
SqrtPriceCalculated square root price values (always BigNumber)When receiving square root price results

Usage Example​

Casting​

Financial amounts are decimal strings or BigNumber instances, never JavaScript numbers. Price inputs are branded on top of that, so a price API (for example addLiquidityByPrice's minPrice and maxPrice) takes a PriceIn: a calculated Price, or a string or BigNumber you cast with as PriceIn. An unbranded string does not compile:

import BigNumber from 'bignumber.js';
import type { PriceIn } from '@gala-chain/gswap-sdk';

function myFunction(price: PriceIn) {
// ...
}

myFunction('0.5' as PriceIn);
myFunction(new BigNumber('0.5') as PriceIn);

A bare number is refused at compile time:

myFunction(0.5); // ERROR: Argument of type 'number' is not assignable to parameter of type 'PriceIn'

The point of forcing this casting is to require the caller to declare explicitly that they are passing in a price value (as opposed to a square root price value, or some other numeric value) thus helping to prevent incorrect data being used.