TypeScript SDK for **Varla Protocol** — lending and risk infrastructure for prediction markets.
npm install @varla/sdkTypeScript SDK for Varla Protocol — lending and risk infrastructure for prediction markets.
Provides contract ABIs, deployed addresses, typed viem bindings, read-only view helpers, simulate-first write actions, leverage planning, error decoding, and formatting utilities.
Supported chains: Polygon (Polymarket) · BSC (Opinion)
---
``bash`
bun add @varla/sdkor
npm i @varla/sdk
Peer dependency: viem ^2.0.0
---
| Import | Description |
| --- | --- |
| @varla/sdk | Core: contracts, views, actions, events, batch, format — everything re-exported |@varla/sdk/views
| | Read-only on-chain queries (account, pool, oracle, system) |@varla/sdk/actions
| | Simulate-first write helpers (deposit, borrow, repay, liquidate, oracle config…) |@varla/sdk/events
| | Event log fetching, decoding, and oracle registry sync |@varla/sdk/contracts
| | Typed viem contract instances (getVarlaContracts) |@varla/sdk/abi
| | Raw ABI constants for all deployed contracts |@varla/sdk/addresses
| | Per-chain deployed address books (polygon, bsc) |@varla/sdk/errors
| | Custom error decoding across all Varla contracts |@varla/sdk/leverage
| | Leverage loop planning, execution, and deleverage |@varla/sdk/batch
| | Multicall chunking utilities for RPC-efficient reads |@varla/sdk/format
| | Number formatting (formatWad, formatBps, parseUnits) |@varla/sdk/types
| | Shared types (ChainKey, AddressBook) |
`ts`
import { getVarlaContracts } from "@varla/sdk/contracts";
import * as views from "@varla/sdk/views";
import * as actions from "@varla/sdk/actions";
---
`ts
import { createPublicClient, http } from "viem";
import { polygon } from "viem/chains";
import { getVarlaContracts } from "@varla/sdk/contracts";
import * as views from "@varla/sdk/views";
const client = createPublicClient({
chain: polygon,
transport: http(process.env.POLYGON_RPC_URL!),
});
const c = getVarlaContracts({ chain: "polygon", client });
`
---
All view helpers are async functions that accept a typed viem contract instance and return plain objects.
`ts
// Pool rates, utilization, and APY
const rates = await views.readPoolRates({ pool: c.pool });
// Pool health score (utilization-based safety signal)
const health = await views.readPoolHealthScore({ pool: c.pool });
// → { kind: "ok", utilizationWad, scoreBps } or { kind: "no-liquidity" }
// Share price (assets per share, WAD precision)
const price = await views.readPoolSharePrice({ pool: c.pool });
// Full pool snapshot (caps, accounting, rates, share price)
const poolSnap = await views.readPoolSnapshot({ pool: c.pool });
// User's lender position: shares, current value, max withdrawable
const lender = await views.readLenderSnapshot({ pool: c.pool, user: "0x..." });
// → { shares, assets, maxWithdrawAssets, maxRedeemShares }
`
`ts
// Full account overview: positions, debt, health factor, borrow limits
const account = await views.readAccountSnapshot({ core: c.core, user: "0x..." });
// Just borrow limits + health factor
const limits = await views.readBorrowLimits({ core: c.core, user: "0x..." });
// Health factor (liquidation threshold check)
const hf = await views.readHealthFactor({ core: c.core, user: "0x..." });
// → { healthFactor, canBeLiquidated }
// LTV tier configuration
const tiers = await views.readTieredLtvConfig({ core: c.core });
// → { tier0, tier1, tier2 } (CONSERVATIVE / MODERATE / RISK)
// Effective LTV for a specific position
const ltv = await views.readLtvForPosition({ core: c.core, positionId: 123n });
`
`ts
// Oracle registry (all configured positions)
const registry = await views.readOracleRegistry({ oracle: c.oracle });
// Price data for a position
const priceData = await views.readOraclePriceData({ oracle: c.oracle, positionId: 123n });
// Position snapshot (price + metadata)
const snap = await views.readPositionSnapshot({ oracle: c.oracle, positionId: 123n });
// Batch: many position snapshots in one multicall
const snaps = await views.readManyPositionSnapshots({
oracle: c.oracle,
positionIds: [1n, 2n, 3n],
});
`
`ts`
// Everything at once: pool + core + oracle state
const system = await views.readSystemSnapshot({
core: c.core,
pool: c.pool,
oracle: c.oracle,
});
---
All write helpers use the simulate-first pattern — they return a SimulatedTx with a pre-validated request you can send via any viem wallet client.
`ts
import * as actions from "@varla/sdk/actions";
// Deposit collateral
const sim = await actions.prepareCoreDeposit({
publicClient: client,
coreAddress: c.core.address,
account: "0x...",
positionId: 123n,
amount: 1_000_000n,
});
// Send the transaction
const hash = await actions.sendTx({ walletClient, request: sim.request });
`
`ts
// Borrow from pool
await actions.prepareCoreBorrow({ publicClient, coreAddress, account, amount });
// Repay debt
await actions.prepareCoreRepay({ publicClient, coreAddress, account, amount });
// Withdraw collateral
await actions.prepareCoreWithdraw({ publicClient, coreAddress, account, positionId, amount });
// ERC-20 approval (for pool deposits)
await actions.prepareErc20Approve({ publicClient, tokenAddress, spender, amount });
// Pool deposit (lender)
await actions.preparePoolDeposit({ publicClient, poolAddress, account, assets });
// Pool withdraw (lender)
await actions.preparePoolWithdraw({ publicClient, poolAddress, account, assets });
`
---
Plan and execute leveraged positions through iterative borrow → buy → deposit loops.
`ts
import { planLeverage, executeLeverage } from "@varla/sdk/leverage";
// Plan a 3× leveraged long position
const plan = planLeverage({
initialCapital: 100_000_000n, // 100 USDC (6 decimals)
tokenPriceE8: 50_000_000n, // $0.50
ltvWad: 650_000_000_000_000_000n, // 65% LTV
targetLeverageWad: 3_000_000_000_000_000_000n, // 3.0×
});
console.log(plan.summary.effectiveLeverageWad); // actual achieved leverage
console.log(plan.summary.estimatedLiquidationPriceE8); // liquidation price
console.log(plan.steps); // ordered steps: buy → deposit → borrow → buy → ...
`
---
Automatically decode custom Solidity errors from any Varla contract.
`ts
import { decodeVarlaError, formatVarlaError } from "@varla/sdk/errors";
try {
await publicClient.simulateContract({ / ... / });
} catch (err) {
const decoded = decodeVarlaError(err);
if (decoded) {
console.log(formatVarlaError(decoded));
// → "VarlaCore.InsufficientCollateral(required=1000, actual=500)"
console.log(decoded.contract, decoded.name, decoded.args, decoded.selector);
}
}
`
---
`ts
import { formatWad, formatBps, formatPriceE8, parseUnits, parseWad } from "@varla/sdk/format";
formatWad(1_500_000_000_000_000_000n); // "1.5"
formatWad(1_500_000_000_000_000_000n, { fractionDigits: 4 }); // "1.5"
formatBps(1500); // "15%"
formatBps(1234); // "12.34%"
formatPriceE8(50_000_000n); // "0.5"
parseUnits("1.5", 18); // 1_500_000_000_000_000_000n
parseUnits("100", 6); // 100_000_000n
parseWad("2.5"); // 2_500_000_000_000_000_000n
`
---
Chunk large read batches to stay within RPC provider limits.
`ts
import { multicallChunks } from "@varla/sdk/batch";
const results = await multicallChunks({
client,
contracts: [
{ address: poolAddr, abi: poolAbi, functionName: "totalAssets" },
{ address: poolAddr, abi: poolAbi, functionName: "totalSupply" },
// ... hundreds of calls
],
chunkSize: 64, // calls per multicall (default: 128)
});
`
---
`ts
import {
getEventLogsChunked,
syncOracleRegistryViaEvents,
getRecentEvents,
ORACLE_EVENTS,
CORE_EVENTS,
POOL_EVENTS,
} from "@varla/sdk/events";
// Fetch oracle events in manageable chunks
const logs = await getEventLogsChunked({
client,
address: c.oracle.address,
events: ORACLE_EVENTS,
fromBlock: 50_000_000n,
toBlock: "latest",
chunkSize: 10_000,
});
// Reconstruct oracle registry from events (no paginated RPC needed)
const registry = await syncOracleRegistryViaEvents({
client,
oracleAddress: c.oracle.address,
fromBlock: 50_000_000n,
});
`
---
`ts
import { getChainMeta } from "@varla/sdk";
const meta = getChainMeta("polygon");
// → { chain: "polygon", platform: "polymarket", collateral: { kind: "USDC", symbol: "USDC", decimals: 6 } }
const bscMeta = getChainMeta("bsc");
// → { chain: "bsc", platform: "opinion", collateral: { kind: "USDT", symbol: "USDT", decimals: 18 } }
`
---
`bash
cd packages/sdk
bun run test:quick # build + run all tests
bun run test:types # typecheck only (no runtime)
bun run test:rpc # RPC integration tests (needs POLYGON_RPC_URL, BSC_RPC_URL)
bun run test:rpc:slow # slow RPC tests (opt-in via SDK_SLOW_RPC_TESTS=1)
`
---
This package lives in the varla-protocol monorepo under packages/sdk/.
`bash`
bun install # install from repo root
cd packages/sdk && bun run prepack # regenerate artifacts + build
cd packages/sdk && bun run test:quick # verify
See AGENTS.md` for the complete auto-generated API reference.