gSwap SDK
@gala-chain/gswap-sdk is the TypeScript SDK for the current GalaChain DEX
contract. It uses trading symbols for pool operations, signs writes with the
signer supplied by the application, and submits them through the Chain
Gateway. Swap requests are queued for later application.
Pools are identified by trading symbols: the SDK resolves class keys through the
symbol registry and orders token0 and token1 with plain string ordering. The
public surface is grouped by responsibility:
gSwap.quotingruns read-only exact-input and exact-output simulations.gSwap.swapssubmits queuedRequestTradeDTOs.gSwap.poolsreads pools, slot0, and composite pool snapshots.gSwap.positionsreads positions and submits liquidity operations.gSwap.assetsreads user balances;gSwap.symbolsresolves symbols.
All reads and writes go through the configured swap backend. The SDK signs the
DTO, posts writes to the method-specific chain-gateway backend route, and returns
a SubmittedTransaction. Swap acknowledgements are queued; call confirm() to
read the applied trade or chain rejection. There is no bundler or socket
waiter, and EIP-712 is only an opt-in scheme of BrowserWalletSigner.
Install
npm install @gala-chain/gswap-sdk@next @gala-chain/gala-core-sdk@next
@gala-chain/gala-core-sdk is a peer dependency (range >=1.0.0-rc.7 <2):
install it next to the SDK. 2.0 is a release candidate under the next
dist-tag; latest is still 1.2.0, so an install without @next gets 1.x.
Pin exact versions for a wallet or app build.
2.0: signing moved to @gala-chain/gala-core-sdk
Since 2.0.0 the signing, transport, wallet-helper and base-error layer lives in
@gala-chain/gala-core-sdk. This package no longer exports or re-exports it:
signers (PrivateKeySigner, GalaWalletSigner, BrowserWalletSigner), the
signing and EIP-712 primitives, the transport adapters, the failure views, the
unique-key helpers and the wallet helpers are imported from the core package.
GSwap, the DEX API and the DEX error catalog stay here. The old
@gala-chain/gswap-sdk/wallet subpath is now @gala-chain/gala-core-sdk/wallet,
and some identifiers were renamed (isGSwapErrorLike is isGalaErrorLike).
The full old-path to new-path table is in
../gala-core-sdk/MIGRATING-FROM-GSWAP.md;
see also Migration from 0.x.
Quick start
import { GSwap } from '@gala-chain/gswap-sdk';
import { PrivateKeySigner } from '@gala-chain/gala-core-sdk';
const signer = new PrivateKeySigner(process.env.GALACHAIN_PRIVATE_KEY!);
const gSwap = new GSwap({ signer, walletAddress: process.env.GALACHAIN_ADDRESS, env: 'stage' });
const quote = await gSwap.quoting.quoteExactInput('GALA', 'GUSDC', '100');
const tx = await gSwap.swaps.swap('GALA', 'GUSDC', quote.feeTier, {
exactIn: '100',
amountOutMinimum: quote.amountOut,
});
console.log({ mode: tx.mode, uniqueKey: tx.uniqueKey, transactionId: tx.transactionId });
const applied = await tx.confirm();
console.log(applied.result);
The env: 'stage' preset targets the staging swap backend, and prod targets
the production swap backend. All SDK traffic uses the swap backend. Use class keys such as GALA|Unit|none|none when a symbol is not
available; the SDK resolves registered symbols and orders pool tokens for you.
Every write returns a SubmittedTransaction. A swap acknowledgement has
mode === 'queued', result === undefined, and a durable uniqueKey; call
confirm() to read its applied outcome, or swaps.confirmSwap(uniqueKey) to
resolve it later from the persisted key alone. Liquidity writes continue to
confirm by re-reading position state. A request transactionId may be null when the
gateway does not provide one.
Market data and leaderboard
Public reads, no signer needed: USD prices (market.getPrices, 1-500 tokens, split into requests
the backend accepts, each read under the
exact id it was asked for), price series (market.getPriceSeries, windows 1D 1W 1M 1Y
ALL), platform volume (market.getVolumeSummary) and the trading-competition seasons and
rankings (leaderboard.getSeasons, getCurrentSeason, getLeaderboard,
getCurrentLeaderboard). See Market Data and Leaderboard.
const gala = await gSwap.market.getPrice('GALA$Unit$none$none'); // undefined: no entry
const series = await gSwap.market.getPriceSeries('GALA$Unit$none$none', '1W');
const season = await gSwap.leaderboard.getCurrentSeason(); // null between seasons
Onramper widget URL
gSwap.onramper.generateWidgetUrl(request) asks the swap backend for a signed Onramper (fiat
on-ramp) widget URL. The route is public: the request carries no Authorization header. An app that
needs only this builds the small service without a whole client:
import { createOnramper } from '@gala-chain/gswap-sdk';
const onramper = createOnramper({ dexBackendBaseUrl: 'https://dex-backend-prod1.defi.gala.com' });
const url = await onramper.generateWidgetUrl({ walletAddress: '0x…', defaultCrypto: 'gala', mode: 'buy' });
Hosts and environment presets
The SDK has one network boundary: the swap backend. It does not call public GalaChain gateway hosts directly.
| Preset | Targets |
|---|---|
stage | The staging swap backend (the preset sets dexBackendBaseUrl) |
prod | https://dex-backend-prod1.defi.gala.com |
Use dexBackendBaseUrl for a test or private deployment override.
Realtime stream
gSwap.stream is a client for the realtime stream (wss://…/ws, JSON-RPC 2.0): live swaps, liquidity
adds/removes/collects, pool and balance changes, new pools and blocks, with automatic reconnect.
import { GSwap } from '@gala-chain/gswap-sdk';
const gSwap = new GSwap({ env: 'stage' });
await gSwap.stream.connect();
await gSwap.stream.subscribeLiquidity((e) => console.log(e.action, e.owner, e.amount0, e.amount1));
See the realtime stream guide.
Signers and identity
| Signer | Scheme | Identity resolved by the chain |
|---|---|---|
PrivateKeySigner | GalaChain native signature | Recovered from the private key |
GalaWalletSigner | Native gala_signChainDto; opt-in personal-sign needs a Gala Wallet build that signs the bare DTO (see Signing and Identity) | Selected account (0x..., eth|..., client|...) |
BrowserWalletSigner | EIP-1193 personal_sign; opt-in { scheme: 'eip712' } (eth_signTypedData_v4) | Selected Ethereum account (eip712 also resolves a client| alias) |
The signers are exported by @gala-chain/gala-core-sdk, not by this package.
Native signing is the default for server keys and current Gala Wallets.
Browser wallet personal-sign signs the bare serialized DTO (the wallet applies
the EIP-191 header) and sends that header as the DTO's prefix, which is what
the chain prepends when it recovers the signer. EIP-712 is opt-in on
BrowserWalletSigner for RequestTrade, AddLiquidity, RemoveLiquidity and
CollectPositionFees (CreatePool still uses personal-sign); it is not the
default and not part of the Gala Wallet path. See
Signing and Identity.
Wallet and app integration
The SDK core is platform neutral (only fetch, globalThis.crypto and timers) and ships the
building blocks a wallet or app needs, each behind an adapter: confirmAppliedTrade (apply-results
polling with AbortSignal, AppliedTradeError), PendingSwapStore (async StorageAdapter;
storageAdapterFromChromeStorage(chrome.storage.local) for an extension, webStorageAdapter(localStorage)
for a web app),
DexFees (DryRun fee quotes), swaps.swapShadow (dark swaps through X-Shadow), a configurable
uniqueKeyPrefix, and the realtime stream with an injected WebSocket (and an apiKey for
server-side clients). See App and Wallet Integration.
Errors carry a stable code and flat params that an app localizes; classifyFailure,
pendingSwapFateFor, isNoMarket and the other deciders answer retry and outcome questions from the
code, never from message text (Error Handling). App-shell code
that must not load the SDK imports its wallet helpers from @gala-chain/gala-core-sdk/wallet
(Bundle size). Tick and price math, including the contract's
in-range rule, is in Tick and Price Math.
Documentation
Start with Getting started, then follow the tutorials for quoting, trading and liquidity management.
For apps and wallets: Error handling (the error
catalog, classifyFailure, localization),
App and wallet integration (pending-swap storage,
wire options, signing primitives, dark swaps),
Signing and identity,
Bundle size (the @gala-chain/gala-core-sdk/wallet
subpath and shell-safe helpers) and
Tick and price math. The API reference is generated from the
package's TSDoc. The site at galachain.github.io/gswap-sdk describes the 1.x API
only. Working examples are in examples/cli,
examples/full_dex and examples/demos of the package (runnable
scripts for swaps, quotes, pools, liquidity positions, fees, market data, leaderboards and pool
watching).
License
This SDK is provided under the Apache License 2.0. Gala™, GalaChain™, and related marks are trademarks of Blockchain Game Partners Inc. This software is provided “AS IS” without warranties of any kind.