SDK
TypeScript SDK for quoting, swapping and managing liquidity on Relatick.
The SDK wraps Relatick's contracts for TypeScript: quotes, swaps through the router, adding and removing liquidity, pool reads and the contract ABIs. It builds on viem.
- Package:
@metric.xyz/metric-omm-sdk-v1 - Source: github.com/Metricxyz/sdk
{% hint style="info" %} Use version 0.7.1 or later. Earlier versions point at a liquidity adder that has since been replaced. The examples on this page were checked against 0.7.4. {% endhint %}
Install
npm install @metric.xyz/metric-omm-sdk-v1 viem
Set up
Everything is exported from the package root. ABIs are under /abis.
import { createPublicClient, createWalletClient, http } from "viem";
import { mainnet } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";
import { ChainId, getAddressesOrThrow } from "@metric.xyz/metric-omm-sdk-v1";
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const publicClient = createPublicClient({ chain: mainnet, transport: http(process.env.RPC_URL) });
const walletClient = createWalletClient({ account, chain: mainnet, transport: http(process.env.RPC_URL) });
// Contract addresses for the chain: factory, simpleRouter, quoter, liquidityAdder, dataProvider, wrappedNative, ...
const addresses = getAddressesOrThrow(ChainId.ETHEREUM);The protocol contracts have the same address on every chain; only the wrapped native token differs. getSupportedChainIds() lists the chains bundled with your SDK version. Addresses are also listed under Deployments.
Quote a swap
A live quote simulates the swap against the pool's current price with eth_call. Nothing is sent on-chain.
import { quoteLiveExactInSingle } from "@metric.xyz/metric-omm-sdk-v1";
const quote = await quoteLiveExactInSingle({
publicClient,
pool: poolAddress,
tokenIn,
tokenOut,
recipient: account.address,
amountIn: 1_000_000_000n, // 1,000 USDC (6 decimals)
quoterAddress: addresses.quoter,
});
// quote.amountIn, quote.amountOutFor a path through several pools use quoteLiveExactIn with pools: [poolA, poolB]. Exact-output variants are quoteLiveExactOutSingle and quoteLiveExactOut.
Things to know:
- A live quote on a paused pool rejects with
errorName === "PoolPaused". - A single-pool exact-output quote can return less than you asked for when the pool isn't deep enough. Compare the quoted output with your request before building the swap; the router rejects a short fill.
- A quote is not a guarantee. See Why a swap reverts.
{% hint style="warning" %} Pools that depend on price updates, on Ethereum. For these pools the fresh price lands in the same block as the trade, so between trades the on-chain price is stale and a live quote, or any simulation of the swap, reverts with the price provider's error. This is expected. Take prices for these pools from the API instead, which applies the latest updates. See Freshness and ordering. {% endhint %}
Swap
Approve the router for the input token once, then build the parameters and send. buildExactInputSingleParams quotes the pool and sets the minimum output from your slippage tolerance.
import { erc20Abi, maxUint256 } from "viem";
import { buildExactInputSingleParams, encodeExactInputSingleCalldata } from "@metric.xyz/metric-omm-sdk-v1";
// 1. Approve the router (ERC-20 input)
await walletClient.writeContract({
address: tokenIn,
abi: erc20Abi,
functionName: "approve",
args: [addresses.simpleRouter, maxUint256],
});
// 2. Build the swap
const params = await buildExactInputSingleParams({
publicClient,
pool: poolAddress,
tokenIn,
tokenOut,
recipient: account.address,
amountIn: 1_000_000_000n,
slippagePercent: 0.5,
deadline: BigInt(Math.floor(Date.now() / 1000) + 1200),
quoterAddress: addresses.quoter,
});
// 3. Send it. Encode with the SDK's encoder, which fills in the optional fields.
const hash = await walletClient.sendTransaction({
to: addresses.simpleRouter,
data: encodeExactInputSingleCalldata(params),
});- Several pools:
buildExactInputParamswithpools: [poolA, poolB], thenencodeExactInputCalldata. - Paying with native ETH:
prepareExactInputSingleSupportingNativePaymentCalldata. It wraps the swap in a multicall that refunds unused ETH. Setvalueon the transaction yourself. - Receiving native ETH:
prepareExactInputSingleAndUnwrapCalldata. - From a route returned by the API:
prepareExactInputFromRoute. See the end-to-end example.
{% hint style="warning" %} The router holds nothing between transactions. Use the SDK's native-payment and unwrap helpers, which add the refund step for you. If you build a multicall by hand, include refundETH or sweepToken in the same transaction. {% endhint %}
Add liquidity
Approve the liquidity adder for both tokens, then use a weighted add. You give the bins, their relative weights and the most you want to spend of each token; the adder sizes the deposit on-chain so neither cap is exceeded.
import {
buildAddLiquidityWeightedParams,
encodeAddLiquidityWeightedSelfCalldata,
getPoolImmutables,
getPoolState,
getPriceProvider,
} from "@metric.xyz/metric-omm-sdk-v1";
import { PriceProviderAbi } from "@metric.xyz/metric-omm-sdk-v1/abis";
// 1. Approve the liquidity adder for token0 and token1 (as in the swap example, with addresses.liquidityAdder)
// 2. Read the pool's reference price
const priceProvider = await getPriceProvider(publicClient, addresses.dataProvider, poolAddress);
const { result: [, , referencePriceX64] } = await publicClient.simulateContract({
address: priceProvider,
abi: PriceProviderAbi,
functionName: "getQuote",
});
// 3. Choose bins inside the pool's range: here the current bin and one on each side
const immutables = await getPoolImmutables(publicClient, addresses.factory, poolAddress);
const state = await getPoolState(publicClient, addresses.dataProvider, poolAddress);
const current = Number(state.curBinIdx);
const bins = [current - 1, current, current + 1].filter(
(bin) => bin >= Number(immutables.lowestBin) && bin <= Number(immutables.highestBin),
);
// 4. Build the deposit
const params = await buildAddLiquidityWeightedParams({
publicClient,
factoryAddress: addresses.factory,
dataProviderAddress: addresses.dataProvider,
poolAddress,
bins,
weights: bins.map(() => 1), // equal weight per bin
currentPriceX64: referencePriceX64,
maxAmountToken0: balance0,
maxAmountToken1: balance1,
maxOracleDistanceChangePercent: 0.5,
});
// 5. Send it. Keep params.salt: it identifies the position and you need it to remove it.
const hash = await walletClient.sendTransaction({
to: addresses.liquidityAdder,
data: encodeAddLiquidityWeightedSelfCalldata({ pool: poolAddress, ...params }),
});maxOracleDistanceChangePercentprotects the deposit: if the pool's price moves further than this from where it was when you built the transaction, the add reverts withBinPositionOutOfBoundsinstead of depositing at a worse mix.- If the price read in step 2 reverts, the pool depends on price updates (see the warning above). Take
bidAdjandaskAdjfrom the API's bid and ask for the pool and pass the square root of their product ascurrentPriceX64. The deposit itself doesn't need a fresh on-chain price. - Native ETH on one side:
prepareAddLiquidityWeightedSelfSupportingNativePaymentCalldata, and setvalue.
Remove liquidity
Removing goes to the pool directly; no approval is needed. A position is identified by its owner and the salt it was created with.
import {
buildModifyLiquidityArgsForPercentageRemoval,
removalPlanToPoolLiquidityDelta,
encodeRemoveLiquidityCalldata,
} from "@metric.xyz/metric-omm-sdk-v1";
const [salt, deltas] = await buildModifyLiquidityArgsForPercentageRemoval({
publicClient,
dataProviderAddress: addresses.dataProvider,
poolAddress,
owner: account.address,
salt: positionSalt, // the salt used when the position was added
percentageToRemove: 100,
});
const hash = await walletClient.sendTransaction({
to: poolAddress,
data: encodeRemoveLiquidityCalldata({
owner: account.address,
salt,
deltas: removalPlanToPoolLiquidityDelta(deltas),
}),
});- If
deltasis empty, there is no position for that owner and salt. - Positions opened in the Relatick app each have their own salt. You can read it from the
saltargument of the transaction that added the liquidity. - Tokens are returned as the wrapped token; there is no native-ETH path on removal.
Read a pool
import { getPoolImmutables, getPoolState, getSlot0 } from "@metric.xyz/metric-omm-sdk-v1";
const immutables = await getPoolImmutables(publicClient, addresses.factory, poolAddress); // tokens, bin range, extensions
const state = await getPoolState(publicClient, addresses.dataProvider, poolAddress); // pause level, current bin, fees
const slot0 = await getSlot0(publicClient, addresses.dataProvider, poolAddress);For pools with a StopLoss, getOracleStopLossAnyBinStatus reports whether any bin is currently blocked and how long until it clears.
More
- The package README and
HOW_TO.mdcover pool creation, extensions and oracle registration. - Smart contracts reference for the underlying calls.
- API reference for pool discovery, prices and routing.
Last updated 29 days ago
Relatick