@gala-chain/gswap-sdk

中文文档
2.1.0发布于 2026/11/10Apache-2.0TypeScriptESM + CJS近 30 天下载 4221

A source development kit for interacting with GSwap.

原始使用文档
文档目录11 节
  1. Install
  2. 2.0: signing moved to @gala-chain/gala-core-sdk
  3. Quick start
  4. Market data and leaderboard
  5. Onramper widget URL
  6. Hosts and environment presets
  7. Realtime stream
  8. Signers and identity
  9. Wallet and app integration
  10. Documentation
  11. License

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.quoting runs read-only exact-input and exact-output simulations.
  • gSwap.swaps submits queued RequestTrade DTOs.
  • gSwap.pools reads pools, slot0, and composite pool snapshots.
  • gSwap.positions reads positions and submits liquidity operations.
  • gSwap.assets reads user balances; gSwap.symbols resolves 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.

Every signed DTO carries the dtoOperation of its call (asset-channel_basic-asset_GalaChainDex:<Method>): the chain refuses a DTO without it or with another call's, and it is part of what is signed. The SDK sets it before signing, from the same table that builds the route; a DTO you sign yourself must set it first (core's withDtoOperation). See Signing and Identity.

Install

npm install @gala-chain/gswap-sdk @gala-chain/gala-core-sdk

@gala-chain/gala-core-sdk is a peer dependency (range >=1.2.0 <2): install it next to the SDK. 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 BigNumber from 'bignumber.js'; // a dependency of the SDK; install it in your own app too
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',
  // The least you accept (1% under the quote), not the quote itself: the swap is applied a few
  // seconds later and a bound equal to the quote is rejected whenever the price moves in between.
  amountOutMinimum: new BigNumber(quote.amountOut).multipliedBy('0.99').toFixed(),
});
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 (prod is also the default when env is omitted). 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.

PresetTargets
stageThe staging swap backend (the preset sets dexBackendBaseUrl)
prodhttps://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

SignerSchemeIdentity resolved by the chain
PrivateKeySignerGalaChain native signatureRecovered from the private key
GalaWalletSignerNative 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|...)
BrowserWalletSignerEIP-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.

版本与发布记录

@gala-chain/gswap-sdk 共发布 48 个版本,首次发布于 2025/07/04;过去 12 个月发布了 37 个版本。

版本发布日期距今
2.1.0latest2026/11/106 天前
2.1.0-beta.112026/11/078 天前
2.1.0-beta.92026/11/0610 天前
2.1.0-beta.102026/11/0610 天前
2.1.0-beta.82026/11/0511 天前
2.1.0-beta.72026/11/0412 天前

其他发布通道:beta → 1.1.1,rc → 1.2.0-rc.10。

关于 @gala-chain/gswap-sdk 的常见问题

@gala-chain/gswap-sdk 是什么?

A source development kit for interacting with GSwap.

如何安装 @gala-chain/gswap-sdk?

在项目目录运行 npm install @gala-chain/gswap-sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@gala-chain/gala-core-sdk(>=1.2.0 <2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gala-chain/gswap-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gala-chain/gswap-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gala-chain/gswap-sdk 可以商用吗?

@gala-chain/gswap-sdk 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@gala-chain/gswap-sdk 的下载量有多少?

根据 npm 官方下载统计,@gala-chain/gswap-sdk 在 2026/10/16 – 2026/11/14 这 30 天内被下载 4,221 次,日均约 141 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gala-chain/gswap-sdk 还在维护吗?

最新版本 2.1.0 发布于 2026/11/10(6 天前);至今共发布 48 个版本,其中过去 12 个月发布了 37 个;首次发布于 2025/07/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。