@sodax/dapp-kit
v2.0.0
Published
React hooks for building dApps on the SODAX cross-chain DeFi platform
Maintainers
Readme
@sodax/dapp-kit
High-level React hooks library for dApp developers. Wraps @sodax/sdk with React Query into feature-organized hooks. Used alongside @sodax/wallet-sdk-react (no direct dependency — shared types come from @sodax/sdk).
Features
- Swap/Intent —
useQuote,useSwap,useSwapAllowance,useSwapApprove,useCancelSwap,useCreateLimitOrder,useCancelLimitOrder,useStatus - Bridge —
useBridge,useBridgeAllowance,useBridgeApprove,useGetBridgeableAmount,useGetBridgeableTokens - Money Market —
useSupply,useWithdraw,useBorrow,useRepay,useMMAllowance,useMMApprove, plus reserves data hooks - Staking —
useStake,useUnstake,useInstantUnstake,useClaim,useCancelUnstake, approval hooks, info/config/ratio queries - DEX —
useDexDeposit,useDexWithdraw,useSupplyLiquidity,useDecreaseLiquidity,useClaimRewards, pool/position queries, param builders - Migration —
useMigrateIcxToSoda,useRevertMigrateSodaToIcx,useMigratebnUSD,useMigrateBaln,useMigrationApprove,useMigrationAllowance - Bitcoin (Bound Exchange) —
useRadfiAuth,useRadfiSession,useTradingWallet,useTradingWalletBalance,useBitcoinBalance,useFundTradingWallet,useRadfiWithdraw,useExpiredUtxos,useRenewUtxos - Partner —
useFetchAssetsBalances,useGetAutoSwapPreferences,useIsTokenApproved,useApproveToken,useSetSwapPreference,useFeeClaimSwap - Recovery —
useHubAssetBalances,useWithdrawHubAsset - Backend Queries — Intent tracking, swap-tx submission + status, orderbook, money market position queries
- Shared —
useXBalances,useDeriveUserWalletAddress,useGetUserHubWalletAddress,useStellarTrustlineCheck,useRequestTrustline,useEstimateGas
Installation
pnpm add @sodax/dapp-kit @tanstack/react-query
# Optional: wallet connectivity
pnpm add @sodax/wallet-sdk-reactQuick Start
1. Set up providers
RPC URLs are injected through config.chains. SodaxProvider is the outermost wrapper; QueryClientProvider wraps everything inside it.
// providers.tsx
import { QueryClientProvider } from '@tanstack/react-query';
import { SodaxProvider, createSodaxQueryClient } from '@sodax/dapp-kit';
import { SodaxWalletProvider, type SodaxWalletConfig } from '@sodax/wallet-sdk-react';
import { ChainKeys, type SodaxOptions } from '@sodax/sdk';
const queryClient = createSodaxQueryClient();
const sodaxConfig: SodaxOptions = {
chains: {
[ChainKeys.SONIC_MAINNET]: { rpcUrl: 'https://sonic-rpc.publicnode.com' },
[ChainKeys.BSC_MAINNET]: { rpcUrl: 'https://bsc-dataseed.binance.org' },
[ChainKeys.BASE_MAINNET]: { rpcUrl: 'https://base.drpc.org' },
[ChainKeys.ARBITRUM_MAINNET]: { rpcUrl: 'https://arb1.arbitrum.io/rpc' },
// Add chains your dApp needs
},
};
const walletConfig: SodaxWalletConfig = {
EVM: {
chains: {
[ChainKeys.BSC_MAINNET]: { rpcUrl: 'https://bsc-dataseed.binance.org' },
[ChainKeys.BASE_MAINNET]: { rpcUrl: 'https://base.drpc.org' },
},
},
};
export function Providers({ children }: { children: React.ReactNode }) {
return (
<SodaxProvider config={sodaxConfig}>
<QueryClientProvider client={queryClient}>
<SodaxWalletProvider config={walletConfig}>
{children}
</SodaxWalletProvider>
</QueryClientProvider>
</SodaxProvider>
);
}2. Get a wallet provider
import { useWalletProvider } from '@sodax/wallet-sdk-react';
import { ChainKeys } from '@sodax/sdk';
function MyFeature() {
const walletProvider = useWalletProvider(ChainKeys.BSC_MAINNET);
// undefined until wallet is connected
}3. Use feature hooks
All mutation hooks accept no arguments at initialization. Domain inputs (params, walletProvider) flow through mutate(vars):
import { useSwap } from '@sodax/dapp-kit';
import { useWalletProvider } from '@sodax/wallet-sdk-react';
import { ChainKeys } from '@sodax/sdk';
import type { CreateIntentParams } from '@sodax/sdk';
function SwapButton({ intentParams }: { intentParams: CreateIntentParams }) {
const walletProvider = useWalletProvider(ChainKeys.BSC_MAINNET);
const { mutateAsyncSafe: swap, isPending } = useSwap();
const handleSwap = async () => {
if (!walletProvider) return;
const result = await swap({ params: intentParams, walletProvider });
if (!result.ok) {
alert(result.error instanceof Error ? result.error.message : 'Swap failed');
return;
}
console.log('Swap submitted!', result.value);
};
return (
<button onClick={handleSwap} disabled={isPending || !walletProvider}>
{isPending ? 'Swapping...' : 'Swap'}
</button>
);
}Requirements
- Node.js >= 20.12.0
- React >= 18
- TypeScript
API Reference
Provider
SodaxProvider— Wraps your app, creates theSodaxSDK instance. Acceptsconfig?: SodaxOptions.createSodaxQueryClient()— Factory for aQueryClientwith global mutation observability (onMutationErrorhook,meta.silentopt-out).
Swap Hooks
useQuote()— Real-time quote (auto-refreshes every 3s)useSwap()— Submit a cross-chain swap intentuseSwapAllowance()— Check token approvaluseSwapApprove()— Approve token spendinguseStatus()— Track intent execution statususeCancelSwap()— Cancel a pending swapuseCreateLimitOrder()— Create a limit order (no deadline)useCancelLimitOrder()— Cancel a limit order
Money Market Hooks
useSupply()— Supply collateraluseWithdraw()— Withdraw supplied tokensuseBorrow()— Borrow against collateraluseRepay()— Repay borrowed tokensuseMMAllowance()— Check approval (auto-skips for borrow/withdraw)useMMApprove()— Approve token spendinguseReservesData()— All reserve datauseReservesHumanized()— Reserves in decimal-normalized formatuseReservesList()— List of reserve asset addressesuseReservesUsdFormat()— Reserves with USD valuesuseUserFormattedSummary()— User portfolio summary (health factor, collateral, debt)useUserReservesData()— User reserve positionsuseAToken()— aToken metadatauseATokensBalances()— aToken balances
Bridge Hooks
useBridge()— Execute a cross-chain bridge transferuseBridgeAllowance()— Check token approvaluseBridgeApprove()— Approve token spendinguseGetBridgeableAmount()— Max bridgeable amount between two tokensuseGetBridgeableTokens()— Tokens bridgeable to a destination chain
Staking Hooks
useStake()— Stake SODA, receive xSODAuseUnstake()— Request unstake (waiting period)useInstantUnstake()— Instant unstake with slippageuseClaim()— Claim SODA after waiting perioduseCancelUnstake()— Cancel pending unstakeuseStakeApprove()— Approve SODA for stakinguseUnstakeApprove()— Approve xSODA for unstakinguseInstantUnstakeApprove()— Approve xSODA for instant unstakinguseStakeAllowance()— Check SODA approvaluseUnstakeAllowance()— Check xSODA approval for unstakinguseInstantUnstakeAllowance()— Check xSODA approval for instant unstakinguseStakingInfo()— User staking positionuseUnstakingInfo()— Pending unstake requestsuseUnstakingInfoWithPenalty()— Unstake requests with penalty calcsuseStakingConfig()— Unstaking period, max penaltyuseStakeRatio()— SODA-to-xSODA exchange rateuseInstantUnstakeRatio()— Instant unstake rateuseConvertedAssets()— xSODA to SODA conversion
DEX Hooks
usePools()— List available poolsusePoolData()— Pool details (price, tick, liquidity)usePoolBalances()— User pool token balancesusePositionInfo()— Position details by token IDuseDexDeposit()— Deposit assets into pool tokensuseDexWithdraw()— Withdraw assets from pool tokensuseDexAllowance()— Check approval for deposituseDexApprove()— Approve token spendinguseLiquidityAmounts()— Token amounts for a tick rangeuseSupplyLiquidity()— Supply liquidity to a positionuseDecreaseLiquidity()— Remove liquidityuseClaimRewards()— Claim trading feesuseCreateDepositParams()— Build deposit params with ERC-4626 conversionuseCreateWithdrawParams()— Build withdraw paramsuseCreateSupplyLiquidityParams()— Build tick range + liquidity paramsuseCreateDecreaseLiquidityParams()— Build decrease params from position state
Migration Hooks
useMigrateIcxToSoda()— ICX/wICX (ICON) → SODA (Sonic)useRevertMigrateSodaToIcx()— SODA (Sonic) → wICX (ICON)useMigratebnUSD()— Legacy bnUSD ↔ new bnUSD (bidirectional)useMigrateBaln()— BALN (ICON) → SODA with optional lock perioduseMigrationApprove()— Approve token spending before migrationuseMigrationAllowance()— Check if approval is needed
Bitcoin (Bound Exchange) Hooks
useRadfiSession()— Manage Bound Exchange session (login, auto-refresh)useRadfiAuth()— Authenticate with Bound Exchange via BIP322 signinguseTradingWallet()— Get trading wallet address from persisted sessionuseBitcoinBalance()— BTC balance for any addressuseTradingWalletBalance()— Trading wallet balance from Bound Exchange APIuseFundTradingWallet()— Fund trading wallet from personal walletuseRadfiWithdraw()— Withdraw from trading walletuseExpiredUtxos()— Fetch expired UTXOs (polls every 60s)useRenewUtxos()— Renew expired UTXOs
Partner Hooks
useFetchAssetsBalances()— Fetch partner asset balancesuseGetAutoSwapPreferences()— Get auto-swap preferencesuseIsTokenApproved()— Check token approvaluseApproveToken()— Approve tokenuseSetSwapPreference()— Set swap preferenceuseFeeClaimSwap()— Claim partner fees via swap
Recovery Hooks
useHubAssetBalances()— Get hub asset balancesuseWithdrawHubAsset()— Withdraw hub asset
Shared Hooks
useSodaxContext()— Access theSodaxSDK instanceuseHubProvider()— Access the hub chain (Sonic) provideruseXBalances()— Cross-chain token balances for an addressuseDeriveUserWalletAddress()— Derive hub wallet address (CREATE3)useGetUserHubWalletAddress()— Derive hub wallet address (wallet router)useEstimateGas()— Estimate gas for transactionsuseStellarTrustlineCheck()— Check Stellar trustlineuseRequestTrustline()— Request Stellar trustline
Backend Query Hooks
useBackendIntentByTxHash()— Get intent by hub tx hash (polls 1s)useBackendIntentByHash()— Get intent by intent hashuseBackendUserIntents()— All intents for a user with date filteringuseBackendOrderbook()— Solver orderbook (cached 30s, no auto-refetch)useBackendMoneyMarketPosition()— User money market positionuseBackendAllMoneyMarketAssets()— All MM assetsuseBackendMoneyMarketAsset()— Single MM asset detailsuseBackendMoneyMarketAssetBorrowers()— Asset borrowersuseBackendMoneyMarketAssetSuppliers()— Asset suppliersuseBackendAllMoneyMarketBorrowers()— All borrowers
Swaps API Hooks (sodax.api.swaps)
Typed wrappers over the backend Swaps API v2 — one useSwapsApi* hook per endpoint (21 total). Highlights:
useSwapsApiQuote()— Solver quote for a cross-chain swapuseSwapsApiCreateIntent()— Build an unsigned create-intent txuseSwapsApiSubmitTx()— Submit swap tx to backenduseSwapsApiSubmitTxStatus()— Check submitted swap status
See src/hooks/swapsApi/ for the full set (tokens, deadline, allowance, approve, submit/cancel intent, status, hash, packet, extra-data, intent lookups, limit orders, gas, fees).
DEX Utils
createDepositParamsProps()— Build deposit params from pool data and spoke asset infocreateWithdrawParamsProps()— Build withdraw params with optional destination infocreateSupplyLiquidityParamsProps()— Build concentrated liquidity supply paramscreateDecreaseLiquidityParamsProps()— Build decrease liquidity params
Development
pnpm install # Install dependencies
pnpm build # Build the package (ESM + CJS)
pnpm dev # Watch mode
pnpm checkTs # Type checking
pnpm test # Run tests
pnpm pretty # Format code
pnpm lint # Lint codeAI agent docs
AI-readable docs for @sodax/dapp-kit (and the other @sodax/* packages) are shipped via @sodax/skills — a separate npm package bundling Claude-Code SKILL.md files and a long-form knowledge tree.
Recommended: skills CLI — from your project root:
npx skills@latest add icon-project/sodax-sdks/packages/skillsnpm + AGENTS.md pointer (fallback for web chats, or when you prefer a devDependency over the CLI):
pnpm add -D @sodax/skillsThen point your agent at node_modules/@sodax/skills/AGENTS.md. See docs/ai-integration-guide.md for all install modes and per-tool wiring.
