SDK Integration
Consume the protocol from browser and Node.js with the official TypeScript SDK.
@steerprotocol/collateral-rail-sdk is the first-class TypeScript interface for this protocol.
- Runs in browser apps (via wagmi/viem)
- Runs in Node.js/automation (via viem transport)
- Keeps risky operations explicit with typed helper methods
- Supports swap preview/execute + settlement reconciliation + launch setup utilities
For production signed quote swaps, use SignedCollateralSwapRouter helpers. They keep native Uniswap v4 swap controls explicit: amountSpecified sign determines exact-in/exact-out, sqrtPriceLimitX96 constrains the pool price boundary, and final slippage remains amountOutMin/amountInMax. Only signed quote hookData can trigger vault settlement; empty or otherwise non-signed hookData is pure AMM pass-through.
Install
npm install @steerprotocol/collateral-rail-sdk1) Choose your runtime
Browser + wagmi
Use existing wagmi config and connected wallet context.
Node.js / bots
Use direct viem clients with HTTP transport and explicit keys/accounts.
Browser pattern (wagmi)
import {
clientsFromWagmiConfig,
buildSwapIntent,
buildExactInputSignedQuoteCallDescriptor,
previewCollateralManagerSwap,
parseEventsFromReceipt,
} from "@steerprotocol/collateral-rail-sdk";
import { createConfig, http } from "wagmi";
import { mainnet } from "viem/chains";
const wagmiConfig = createConfig({
chains: [mainnet],
transports: { [mainnet.id]: http("https://...") },
});
const clients = await clientsFromWagmiConfig({
config: wagmiConfig,
chainId: mainnet.id,
});
const swapParams = {
amountSpecified: -1_000000n,
sqrtPriceLimitX96: 0n,
amountOutMinimum: 0n,
zeroForOne: true,
};
const poolKey = {
currency0: "0xStableToken",
currency1: "0xCollateral",
fee: 3000,
tickSpacing: 60,
hooks: "0xHook",
};
const intent = buildSwapIntent(swapParams);
const swapInput = {
executorAddress: "0xSignedCollateralSwapRouter",
poolKey,
amountIn: 1n,
amountOutMin: 0n,
sqrtPriceLimitX96: 0n,
zeroForOne: true,
hookData: "0x1234", // signed quote bytes or explicit controller hook data
receiver: "0xYourWallet",
deadline: BigInt(Math.floor(Date.now() / 1000) + 120),
};
const call = buildExactInputSignedQuoteCallDescriptor({
...swapInput,
});
if (!clients.walletClient) {
throw new Error("Wallet client is required to execute swaps");
}
// 1) preview using collateral manager
const [preAmount0, preAmount1] = await previewCollateralManagerSwap(
clients.publicClient,
"0xCollateralManager",
"0xSender",
poolKey,
swapParams,
);
// 2) submit swap transaction
const txHash = await clients.walletClient.writeContract(call as never);
// 3) parse settlement and risk logs from receipt
const events = await parseEventsFromReceipt(clients.publicClient, txHash, {
collateralManager: "0xCollateralManager",
hook: "0xHook",
});
console.log({ direction: intent.intent.direction, events, preAmount0, preAmount1 });Node.js pattern (backend)
import {
createProtocolPublicClient,
createProtocolWalletClient,
defaultSwapDeadline,
inferSwapDirection,
buildExactInputSignedQuoteCallDescriptor,
getCollateralManagerMaxMintable,
} from "@steerprotocol/collateral-rail-sdk";
import { optimismSepolia } from "viem/chains";
const publicClient = createProtocolPublicClient({
chain: optimismSepolia,
rpcUrl: "https://rpc.example",
});
const walletClient = createProtocolWalletClient({
chain: optimismSepolia,
rpcUrl: "https://rpc.example",
account: "0xYourAdmin",
});
const swapParams = {
amountSpecified: -1_000000n,
sqrtPriceLimitX96: 0n,
amountOutMinimum: 0n,
zeroForOne: true,
};
console.log(inferSwapDirection(swapParams));
// -> { direction: "mint", absoluteAmount: 1000000n }
const route = {
collateralManager: "0xCollateralManager",
sender: "0xTrader",
executor: "0xSignedCollateralSwapRouter",
poolKey: {
currency0: "0xStableToken",
currency1: "0xCollateral",
fee: 3000,
tickSpacing: 60,
hooks: "0xHook",
},
amountIn: 1n,
};
await getCollateralManagerMaxMintable(publicClient, route.collateralManager, route.sender);
const swapInput = {
executorAddress: route.executor,
poolKey: route.poolKey,
amountIn: route.amountIn,
amountOutMin: 0n,
sqrtPriceLimitX96: 0n,
zeroForOne: true,
hookData: "0x1234", // signed quote bytes or explicit controller hook data
receiver: route.sender,
deadline: defaultSwapDeadline(120),
};
const call = buildExactInputSignedQuoteCallDescriptor(swapInput);
const swapHash = await walletClient.writeContract(call as never);Signed-quote mode (optional)
For tighter settlement intent controls, you can request and attach a signed quote. The on-chain contract still computes settlement amount/direction from SwapParams; signature controls policy gates (trader, poolId, maxAbsAmount, expiry, signer, oracle bound, replay).
import {
createProtocolWalletClient,
signSignedSwapQuote,
buildExactInputSignedQuoteCallDescriptor,
type SignedSwapQuoteBase,
} from "@steerprotocol/collateral-rail-sdk";
import { optimismSepolia } from "viem/chains";
const walletClient = createProtocolWalletClient({
chain: optimismSepolia,
rpcUrl: "https://rpc.example",
account: "0xSignerOrTrader",
});
const poolKey = {
currency0: "0xStableToken",
currency1: "0xCollateral",
fee: 3000,
tickSpacing: 60,
hooks: "0xHook",
};
const swapParams = {
amountSpecified: -1_000000n,
sqrtPriceLimitX96: 0n,
amountOutMinimum: 0n,
zeroForOne: true,
};
const quote: SignedSwapQuoteBase = {
// poolId must be the exact on-chain pool id for this pair/fee/ticks/hooks
poolId: "0x2222222222222222222222222222222222222222222222222222222222222222",
trader: "0xTrader",
maxAbsAmount: 1_000000n,
quotedPriceE18: 1_000000000000000000n,
// unix timestamp in seconds
expiry: 1_700_000_000n,
};
const signedSwapQuote = await signSignedSwapQuote(
walletClient,
"0xCollateralManager",
optimismSepolia.id,
quote,
"0xSignerOrTrader",
);
const signedCall = buildExactInputSignedQuoteCallDescriptor({
poolKey,
amountIn: 1n,
amountOutMin: 0n,
sqrtPriceLimitX96: 0n,
zeroForOne: true,
receiver: "0xTrader",
deadline: BigInt(Math.floor(Date.now() / 1000) + 120),
executorAddress: "0xSignedCollateralSwapRouter",
signedSwapQuote,
});
await walletClient.writeContract(signedCall as never);Signed-quote failure example (strict reject)
If a signed quote is supplied but invalid (expired, wrong trader, wrong signer, consumed derived replay key, or policy violation), settlement reverts and does not fall back to unsigned pure-AMM execution in the same transaction.
import { parseError } from "@steerprotocol/collateral-rail-sdk";
try {
await walletClient.writeContract(signedCall as never);
} catch (error) {
const parsed = parseError(error);
// Example names: SignedQuoteExpired, SignedQuoteReplay, SignedQuotePolicyViolation
console.error("swap rejected", parsed?.source, parsed?.name, parsed?.args);
}Reality check
settleCollateralManagerSwap is a settlement callback helper for hook-authorized contexts (integration tests, simulations, or protocol operator flows).
Regular signed quote integrations should execute swaps through SignedCollateralSwapRouter and monitor emitted events.
2) SDK modules at a glance
Client helpers
createProtocolPublicClient,createProtocolWalletClient,createProtocolClientsclientsFromWagmiConfigcustomProviderTransportgetErrorMessage(extract readable error source + name)
Swap helpers
inferSwapDirection(sign-to-direction fromamountSpecified)resolveHookDataandbuildSwapIntentpreviewCollateralSwapFromParamsbuildSwapCallDescriptorbuildExactInputSignedQuoteCallDescriptor,buildExactOutputSignedQuoteCallDescriptor,buildTargetOutputSignedQuoteCallDescriptorsimulateSwap,executeSwap
CollateralManager / settlement helpers
previewCollateralManagerSwapsettleCollateralManagerSwap(hook-authorized callback contexts only)getCollateralManagerConfig,getCollateralManagerBalance,totalDebtdepositCollateral,withdrawCollateral,mintStableForAccount,redeemStableForAccount
Risk/oracle/admin helpers
getRiskConfigCollateral,setRiskConfigCollateral,getRiskConfigGlobal,setRiskConfigGlobal,setRiskConfigSafeMode,guardianSetSafeModegetHookPoolRiskConfig,setHookOracleAdapter,setHookGlobalSafeMode,setHookPoolRiskConfigsetCollateralManagerOracleAdapter,setCollateralManagerSettlementHook,setCollateralManagerDegradedHaircutsetOracleCollateralConfig,setOracleGlobalPaused,getOracleCollateralConfig,getOracleEffectivePricesetStablecoinMinter,getStablecoinIsMinter
Launch and validation helpers
withDefaultsCollateralConfigwithDefaultsGlobalConfigwithDefaultsPoolRiskConfigwithDefaultsOracleConfigvalidateLaunchInputbuildLaunchStepsbuildLaunchCallDescriptors
Event and error parsing
parseHookSettlementLogs,parseHookRiskEvaluatedLogs,parseAfterSwapSettlementLogsparseEventsFromReceiptparseError
3) Full runtime flow (swap + settlement)
- Read user intent (
SwapParams) and detect direction. - Build a typed executor call descriptor with the signed quote helpers.
- Ask
previewCollateralManagerSwapfor proposed settlement deltas before sending user tx. - Execute the swap through
SignedCollateralSwapRouter. - Settlement callback is handled by the hook/manager path inside the same transaction.
- Read event stream with
parseEventsFromReceiptfor settlement and guard events. - Surface errors with
parseErrorand show a normalized message.
4) Error and observability playbook
Use event parsers to classify behavior:
BeforeSwapRiskEvaluated-> guard behavior and oracle mode.AfterSwapSettlementEvaluated-> final settlement delta/returned unspecified delta.HookSettlementExecuted-> concrete user settle action (mint/redeem) and amount.
import { parseError } from "@steerprotocol/collateral-rail-sdk";
try {
// contract call
} catch (err) {
const parsed = parseError(err);
if (parsed) {
console.error(parsed.source, parsed.name, parsed.args);
}
}For high-volume monitoring:
- Track
amountSpecifiedvsamount1/amount0deltas per pool - Alert on repeated missing settlement events where one was expected
- Alert when preview and final callback settlement outcomes diverge
5) Migration note on generated wagmi actions
The package exposes both:
viemprimitives (core, stable, always available)generatedtyped wagmi actions (generated.read*/generated.write*)
Use generated when your app already depends on wagmi types; otherwise keep the viem-first helpers as your default.
6) Next step
- Read the end-to-end swap lifecycle walkthrough.
- Review API references.
- For launch order and policy checks, use New Market Onboarding.
Explicit risk mode changes
setRiskConfigGlobal retains the current mode and reverts if its supplied mode
is stale. Use setRiskConfigSafeMode(walletClient, riskConfig, expectedMode, nextMode, account?) for an explicit admin mode transition without rewriting
limits. Refresh and review a mode mismatch before retrying. Guardian emergency
changes continue to use guardianSetSafeMode. The new helper requires a registry
that implements the new entrypoint; older deployments retain their existing API.