npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@liqpro/liq-core

v0.68.0

Published

SDK foundation — types, enums, EIP-712 helpers, chain config, and contract addresses for the Liq perpetuals exchange.

Readme

@liq/core

SDK foundation — types, enums, EIP-712 helpers, chain config, and contract addresses for the Liq perpetuals exchange.

Overview

@liq/core is the zero-framework base layer shared by all Liq SDK packages. It provides the canonical EIP-712 domain and order type definitions, chain configuration with contract addresses for each supported network, shared TypeScript types and enums for orders/positions/accounts, and the branded numeric primitives (Price, Qty, Usd, Margin) used throughout the system. The only runtime dependency is zod.

Key Exports

Chain config

  • getChainConfig(chainId) — returns ChainConfig (contracts, rpcUrl, subgraphUrl) for a given chain ID
  • getContractAddress(chainId, contract) — shortcut to a single contract address
  • ChainConfig — interface with PerpsMarketProxy, SynthetixCoreProxy, PerpsAccountProxy, SpotMarketProxy, OracleManagerProxy, TrustedMulticallForwarder, USDC, sUSDC

Supported chains: MegaETH Testnet (chainId 6343)

Контур production передеплоен (с 0.67.0)

Prod-контур пересобран с нуля 2026-10-09 (snx-omnibus-megaeth-production:3-dev): все адреса в liqChains[6343].production новые, включая PerpsMarketProxy — это verifyingContract EIP-712. Подписи ордеров под старым PerpsMarketProxy (0x330E5A38…) на новом контуре невалидны, окна совместимости нет: клиент обязан обновиться до 0.67.0 вместе с шлюзом. Id тоже другие: susdcMarketId = 1 (было 3), perpsCoreMarketId = 3 (было 2); в collaterals у production появился USDm (getCollateral(chain, 'USDm')), как у staging. Старый контур продолжает отвечать на цепи теми же рынками, поэтому устаревший адрес выглядит живым и ломается только на «account not owned» или несовпадении домена EIP-712.

EIP-712

  • EIP712_ORDER_TYPES — typed data schema for order signing
  • EIP712_DOMAIN_NAME / EIP712_DOMAIN_VERSION — "PerpExchange" / "1"
  • buildEip712Domain(chainId, verifyingContract) — constructs the EIP-712 domain object
  • buildLimitOrderMessage(params) — builds a signed limit order payload
  • buildMarketOrderMessage(params) — builds a signed market order payload
  • buildConditionalOrderMessage(params) — builds a signed TP/SL/stop order payload
  • ORDER_TYPE_INDEX — numeric index mapping for OrderType enum values

Types (src/types/)

  • OrderType enum — MARKET, LIMIT, STOP_MARKET, STOP_LIMIT, TAKE_PROFIT_MARKET, TAKE_PROFIT_LIMIT
  • Order, position, account, fill, market, and API types shared across SDK packages

Branded primitives (src/primitives.ts)

  • Price, Qty, Usd, Margin, Bps — branded bigint types (18 decimals)
  • Each brand: constructor, .parse(str), .fmt(val), .zod schema, .mul() arithmetic

Prices (src/prices/)

  • REDSTONE_FEEDS — RedStone push-feed addresses on MegaETH testnet (chainId 6343), keyed by symbol
  • RedStoneFeedSymbol — feed symbol type; a key of REDSTONE_FEEDS
  • REDSTONE_DECIMALS — decimals of every RedStone feed (8)
  • isRedStoneFeedSymbol(value) — type guard for a feed symbol
  • redstoneFeedAddress(feedId) — feed address for a Market.feedId symbol, or undefined when unknown

Скобки позиции — positionBrackets(position, conditional) (src/positions/)

С 0.65.0 принимает позицию ({ marketId, size }), а не рынок. Скобка — условный reduce-only ордер этого рынка в TRIGGER_PENDING на стороне, закрывающей позицию (у длинной — SELL, у короткой — BUY). Нет позиции — нет скобок. У каждой скобки size (подписанный размер, модулем) и effectiveSize = min(size, |position.size|) — столько она закроет: движок урезает reduce-only до позиции, и после частичного закрытия показывать надо effectiveSize.

reduceOnlyLegs(position, orders) (src/positions/reduce-only-legs.ts, с 0.66.0) — шире positionBrackets: все reduce-only ордера позиции на закрывающей стороне (TP/SL в TRIGGER_PENDING, отдыхающие LIMIT / STOP_LIMIT / TAKE_PROFIT_LIMIT в PENDING / PARTIALLY_FILLED), у каждого effectiveSize = min(остаток, |position.size|); остаток — remainingSize, а если его нет, то |sizeDelta|. Дубль по id — первое вхождение, свежий список передают первым. Резерв сматченных, но не рассчитанных ордеров не учитывается.

GatewayOrder.reduceOnly — с 0.65.0 в типе. Список ордеров шлюз отдавал с колонкой и раньше; одиночный orders.get(id) — только у шлюза с 0.65.0.

describeOrderOutcome называет снятие скобки вместе с позицией: position_closed, position_flipped, no_position, и отмену reduce-only лимитки, под которую не осталось позиции: reduce_only.

Маржа ордера и аккаунта (с 0.67.0)

validateOrder (src/order/validate.ts) судит доступность по требованию протокола. Ломающее изменение: из OrderVerdictInput ушли available и marginCost, пришли requiredMargin и free (Margin | undefined). requiredMargin — поле requiredMargin предпросмотра маржи ордера (getOrderMarginPreview в @liq/onchain, useOrderMarginPreview в @liq/react), free — free шлюза (client.accounts.getMargin, useAccountMargin). Предупреждение exceeds-available-margin — когда оба известны и requiredMargin > free; равенство не предупреждает. Неизвестное — undefined, пока чтение не пришло; Margin(0n) вместо него не подставлять: 0n и отрицательный free — известные значения, и они предупреждают. Это предупреждение, а не блок: requiredMargin не включает убыток филла хуже марка, который ворота протокола списывают с доступной маржи, так что requiredMargin <= free необходимо, но не достаточно; решает шлюз.

const verdict = validateOrder({
	markPrice,
	sizeQty,
	minSize,
	leverage,
	maxLeverage,
	requiredMargin: preview?.requiredMargin,
	free: margin === undefined ? undefined : Margin(margin.free),
});

marginUsage({ requiredInitialMargin, available }) (src/margin/usage.ts) — доля начального требования в доступной марже, WAD: getRequiredMargins(accountId)[0] (награда за ликвидацию уже внутри) на ончейн getAvailableMargin (уже за вычетом долга). Нулевое требование — 0n; положительное при available <= 0n — undefined (под водой).

marginCost (src/order/math.ts) — калькулятор размера для слайдера плеча (notional / leverage), а не маржа; маржа ордера — requiredMargin предпросмотра. draftLiquidationPrice — @deprecated: с кросс-позициями не сходится; оценка — estimatedLiquidationPrice предпросмотра или accountMargin(...).liquidationPriceFor.

Install

pnpm add @liq/core

Build

moon run liq-core:build    # tsup → dist/