@derivexyz/derive-ts 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/version.ts","../src/client.ts","../src/api/deposits.ts","../src/abis/actionManager.ts","../src/abis/erc20.ts","../src/errors.ts","../src/signing/encoding.ts","../src/api/marketData.ts","../src/api/orders.ts","../src/codecs/trade.ts","../src/signing/action.ts","../src/signing/eip712.ts","../src/api/positionTransfers.ts","../src/codecs/rfq.ts","../src/api/rfq.ts","../src/api/sessionKeys.ts","../src/auth/scopes.ts","../src/codecs/sessionKey.ts","../src/api/spotTransfers.ts","../src/codecs/externalTransfer.ts","../src/codecs/transfer.ts","../src/codecs/whitelistedRecipients.ts","../src/api/subaccounts.ts","../src/api/vaults.ts","../src/codecs/vault.ts","../src/api/withdrawals.ts","../src/codecs/withdrawal.ts","../src/auth/auth.ts","../src/signing/modules.ts","../src/config/networks.ts","../src/subscriptions/subscriptions.ts","../src/methodGuard.ts","../src/transport/jsonrpc.ts","../src/transport/http.ts","../src/transport/ws.ts","../src/subscriptions/channels.ts"],"sourcesContent":["export { SDK_VERSION } from './version';\n\nexport { DeriveClient } from './client';\nexport type { ClientContext } from './api/context';\nexport { MarketDataApi } from './api/marketData';\nexport { SubaccountsApi } from './api/subaccounts';\nexport { OrdersApi, type PlaceOrderParams } from './api/orders';\nexport { RfqApi, type RfqLeg, type PricedRfqLeg, type SendQuoteParams, type ExecuteQuoteParams } from './api/rfq';\nexport { PositionTransfersApi, type PositionTransferLeg, type TransferPositionsParams } from './api/positionTransfers';\nexport {\n SpotTransfersApi,\n type ExternalSpotTransferParams,\n type InternalSpotTransferParams,\n type SpotAssetInfo,\n} from './api/spotTransfers';\nexport { WithdrawalsApi } from './api/withdrawals';\nexport { ContractCallDeposits, DepositAddressDeposits, DepositsApi } from './api/deposits';\nexport {\n CuratorVaultsApi,\n ShareholderVaultsApi,\n VaultsApi,\n type BurnVaultSharesRequest,\n type CreateVaultRequest,\n type MintVaultSharesRequest,\n type UpdateVaultInfoRequest,\n type VaultCancelRequest,\n type VaultDepositRequest,\n type VaultWithdrawRequest,\n} from './api/vaults';\nexport { SessionKeysApi, type CreateSessionKeyParams } from './api/sessionKeys';\nexport { OffchainScope, ProtocolScopeCode, ProtocolScopeWireString } from './auth/scopes';\nexport { authHeaders, loginParams, type AuthCredentials, type AuthSigner } from './auth/auth';\nexport { channel, type TypedChannel } from './subscriptions/channels';\nexport { Subscriptions, type Subscription } from './subscriptions/subscriptions';\nexport { NETWORKS, resolveNetwork } from './config/networks';\nexport type {\n ContractAddresses,\n DeriveClientOptions,\n Logger,\n ModuleAddresses,\n NetworkConfig,\n NetworkName,\n} from './config/types';\nexport { DeriveConnectionError, DeriveRpcError, DeriveTimeoutError } from './errors';\nexport { SignedAction, type ActionFields } from './signing/action';\nexport { ACTION_TYPEHASH, domainSeparator } from './signing/eip712';\nexport { expiresIn, randomNonce, toE18, toScaled, type DecimalLike } from './signing/encoding';\nexport { V3_MODULE_ADDRESSES } from './signing/modules';\nexport type { WebSocketFactory, WebSocketLike } from './transport/ws';\nexport type { ChannelSchemaMap, ChannelTemplate, EndpointMap, ParamsOf, ResultFor, RpcMethod } from './types';\n","export const SDK_VERSION = '3.0.0';\n","import { Wallet, type BaseWallet } from 'ethers';\nimport { DepositsApi } from './api/deposits';\nimport { MarketDataApi } from './api/marketData';\nimport { OrdersApi } from './api/orders';\nimport { PositionTransfersApi } from './api/positionTransfers';\nimport { RfqApi } from './api/rfq';\nimport { SessionKeysApi } from './api/sessionKeys';\nimport { SpotTransfersApi } from './api/spotTransfers';\nimport { SubaccountsApi } from './api/subaccounts';\nimport { VaultsApi } from './api/vaults';\nimport { WithdrawalsApi } from './api/withdrawals';\nimport { authHeaders, loginParams, type AuthCredentials } from './auth/auth';\nimport { resolveNetwork } from './config/networks';\nimport type { DeriveClientOptions, Logger, NetworkConfig } from './config/types';\nimport { Subscriptions } from './subscriptions/subscriptions';\nimport { HttpTransport } from './transport/http';\nimport { WsTransport } from './transport/ws';\nimport type { ParamsOf, ResultFor, RpcMethod } from './types';\n\nconst noopLogger: Logger = () => {};\n\nfunction toWallet(input: string | BaseWallet | undefined): BaseWallet | undefined {\n return typeof input === 'string' ? new Wallet(input) : input;\n}\n\nexport class DeriveClient {\n readonly network: NetworkConfig;\n readonly ws: WsTransport;\n readonly http: HttpTransport;\n\n readonly marketData: MarketDataApi;\n readonly subaccounts: SubaccountsApi;\n readonly orders: OrdersApi;\n readonly rfq: RfqApi;\n readonly spotTransfers: SpotTransfersApi;\n readonly positionTransfers: PositionTransfersApi;\n readonly withdrawals: WithdrawalsApi;\n readonly deposits: DepositsApi;\n readonly vaults: VaultsApi;\n readonly sessionKeys: SessionKeysApi;\n readonly subscriptions: Subscriptions;\n\n readonly logger: Logger;\n private readonly owner?: BaseWallet;\n private readonly sessionKey?: BaseWallet;\n private readonly accountOwner?: string;\n private loggedIn = false;\n\n constructor(options: DeriveClientOptions) {\n this.network = resolveNetwork(options.network);\n this.logger = options.logger ?? noopLogger;\n this.owner = toWallet(options.wallet);\n this.sessionKey = toWallet(options.sessionKey);\n this.accountOwner = options.ownerAddress ?? this.owner?.address;\n if (this.sessionKey && !this.accountOwner) {\n throw new Error('a session key acts for an account owner — also pass `wallet` or `ownerAddress`');\n }\n\n const timeoutMs = options.requestTimeoutMs ?? 20_000;\n this.http = new HttpTransport({\n baseUrl: this.network.httpUrl,\n timeoutMs,\n logger: this.logger,\n authHeaders: () => authHeaders(this.credentials()),\n });\n this.ws = new WsTransport({\n url: this.network.wsUrl,\n timeoutMs,\n logger: this.logger,\n wsFactory: options.wsFactory,\n });\n this.ws.onReconnected = async () => {\n if (this.loggedIn) await this.login();\n await this.subscriptions.resubscribeAll();\n };\n\n this.marketData = new MarketDataApi(this);\n this.subaccounts = new SubaccountsApi(this);\n this.orders = new OrdersApi(this, this.marketData);\n this.rfq = new RfqApi(this);\n this.spotTransfers = new SpotTransfersApi(this);\n this.positionTransfers = new PositionTransfersApi(this);\n this.withdrawals = new WithdrawalsApi(this);\n this.deposits = new DepositsApi(this);\n this.vaults = new VaultsApi(this);\n this.sessionKeys = new SessionKeysApi(this);\n this.subscriptions = new Subscriptions(this, this.ws);\n }\n\n /**\n * The identity requests act as: the owner address plus whichever\n * wallet signs (session key when configured, otherwise the owner).\n */\n credentials(): AuthCredentials {\n const signer = this.sessionKey ?? this.owner;\n if (!signer || !this.accountOwner) {\n throw new Error('this operation requires authentication — construct DeriveClient with a wallet or session key');\n }\n return { ownerAddress: this.accountOwner, signer };\n }\n\n /** Opens the websocket. REST-only usage can skip this. */\n async connect(): Promise<void> {\n await this.ws.connect();\n }\n\n /**\n * Authenticates the websocket connection (REST requests instead carry\n * signed headers per request). Re-runs automatically after reconnects.\n */\n async login(): Promise<ResultFor<'public/login'>> {\n if (!this.ws.connected) {\n throw new Error('login runs over the websocket — call connect() first');\n }\n const result = await this.ws.send('public/login', await loginParams(this.credentials()));\n this.loggedIn = true;\n return result;\n }\n\n async close(): Promise<void> {\n this.loggedIn = false;\n await this.ws.close();\n }\n\n /**\n * Typed escape hatch for any public RPC method: uses the websocket\n * when connected, REST otherwise.\n */\n send<M extends RpcMethod>(method: M, params: ParamsOf<M>): Promise<ResultFor<M>> {\n return this.ws.connected ? this.ws.send(method, params) : this.http.send(method, params);\n }\n}\n","import { Contract, getAddress, type Signer } from 'ethers';\nimport { ACTION_MANAGER_ABI } from '../abis/actionManager';\nimport { ERC20_ABI } from '../abis/erc20';\nimport { DeriveTimeoutError } from '../errors';\nimport { toScaled, type DecimalLike } from '../signing/encoding';\nimport type { ClientContext } from './context';\n\n/**\n * Deposits are NOT signed actions in v3. Funds enter through one of two\n * deliberately distinct flows — pick explicitly:\n *\n * - `deposits.contractCall.*` — self-custody: YOUR wallet sends the\n * on-chain ActionManager transaction (approve + deposit); you provide\n * an ethers Signer connected to the chain RPC.\n * - `deposits.depositAddress.*` — CEX-style: register a deterministic\n * deposit address, send funds to it from anywhere, and the exchange\n * sweeps and credits them asynchronously.\n *\n * `getHistory` and `awaitCredited` cover both flows.\n */\nexport class DepositsApi {\n readonly contractCall: ContractCallDeposits;\n readonly depositAddress: DepositAddressDeposits;\n\n constructor(private readonly ctx: ClientContext) {\n this.contractCall = new ContractCallDeposits(ctx);\n this.depositAddress = new DepositAddressDeposits(ctx);\n }\n\n /**\n * Deposit history rows (up to 1000), regardless of which flow funded\n * them. Scoped to one subaccount when `subaccountId` is given,\n * otherwise to the whole owner wallet. Timestamps are unix milliseconds.\n */\n async getHistory(options: { subaccountId?: number; startTimestampMs?: number; endTimestampMs?: number } = {}) {\n return this.ctx.send('private/get_deposit_history', {\n subaccount_id: options.subaccountId,\n wallet: options.subaccountId === undefined ? this.ctx.credentials().ownerAddress : undefined,\n start_timestamp: options.startTimestampMs,\n end_timestamp: options.endTimestampMs,\n });\n }\n\n /**\n * Polls `private/get_subaccounts` until a subaccount id outside\n * `knownSubaccountIds` appears — the signal that a deposit creating a\n * new subaccount (either flow) was credited — and returns the new id.\n * Snapshot the ids BEFORE initiating the deposit.\n */\n async awaitCredited(params: {\n knownSubaccountIds: number[];\n timeoutMs?: number;\n pollIntervalMs?: number;\n }): Promise<number> {\n const { knownSubaccountIds, timeoutMs = 120_000, pollIntervalMs = 2_000 } = params;\n const known = new Set(knownSubaccountIds);\n const wallet = this.ctx.credentials().ownerAddress;\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const { subaccount_ids } = await this.ctx.send('private/get_subaccounts', { wallet });\n const credited = subaccount_ids.find((id) => !known.has(id));\n if (credited !== undefined) return credited;\n if (Date.now() >= deadline) {\n throw new DeriveTimeoutError(`deposit not credited within ${timeoutMs}ms — no new subaccount for ${wallet}`);\n }\n await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));\n }\n }\n}\n\nexport interface ContractCallDepositBase {\n /** Caller-provided ethers signer connected to the chain RPC (the SDK holds no provider). */\n signer: Signer;\n /** Protocol asset label the deposit credits (see abis/actionManager.ts), NOT the ERC-20. */\n asset: string;\n /** Underlying ERC-20 to approve and pull funds from. Defaults to the network's USDC. */\n erc20?: string;\n /**\n * Amount in human units — scaled by the ERC-20's on-chain `decimals()`\n * (USDC = 6) — or a bigint of already-raw token units.\n */\n amount: DecimalLike;\n}\n\n/**\n * Self-custody deposits: the caller's wallet signs on-chain\n * ActionManager transactions directly.\n */\nexport class ContractCallDeposits {\n constructor(private readonly ctx: ClientContext) {}\n\n /**\n * Approves (if needed) and deposits into an existing subaccount.\n * `fallbackRecipient` (default: the signer) receives the funds into\n * its fallback subaccount if the deposit cannot be applied.\n * Resolves once the transaction is mined — crediting happens\n * asynchronously once the deposit is observed on-chain.\n */\n async deposit(\n params: ContractCallDepositBase & { subaccountId: number; fallbackRecipient?: string },\n ): Promise<{ txHash: string }> {\n const { actionManager, amountRaw } = await this.approveForDeposit(params);\n const fallback = getAddress(params.fallbackRecipient ?? (await params.signer.getAddress()));\n const tx = await actionManager.getFunction('deposit')(\n getAddress(params.asset),\n amountRaw,\n params.subaccountId,\n fallback,\n );\n await tx.wait();\n return { txHash: tx.hash as string };\n }\n\n /**\n * Approves (if needed) and deposits into a NEW subaccount under\n * `managerId`, owned by `owner` (default: the signer). The exchange\n * assigns the subaccount id asynchronously — discover it with\n * `deposits.awaitCredited` against a pre-deposit snapshot of the\n * owner's ids.\n */\n async depositToNewSubaccount(\n params: ContractCallDepositBase & { managerId: number; owner?: string },\n ): Promise<{ txHash: string }> {\n const { actionManager, amountRaw } = await this.approveForDeposit(params);\n const owner = getAddress(params.owner ?? (await params.signer.getAddress()));\n const tx = await actionManager.getFunction('depositToNewSubaccount')(\n getAddress(params.asset),\n amountRaw,\n params.managerId,\n owner,\n );\n await tx.wait();\n return { txHash: tx.hash as string };\n }\n\n /** Scales the amount, then ensures the ActionManager may pull it from the ERC-20. */\n private async approveForDeposit(\n params: ContractCallDepositBase,\n ): Promise<{ actionManager: Contract; amountRaw: bigint }> {\n const managerAddress = this.ctx.network.contracts.actionManager;\n if (!managerAddress) {\n throw new Error(\n `network '${this.ctx.network.name}' has no actionManager contract configured — ` +\n 'contract-call deposits need a NetworkConfig with contracts.actionManager set',\n );\n }\n const erc20Address = params.erc20 ?? this.ctx.network.contracts.usdc;\n if (!erc20Address) {\n throw new Error(`network '${this.ctx.network.name}' has no usdc contract configured — pass erc20 explicitly`);\n }\n\n const token = new Contract(getAddress(erc20Address), ERC20_ABI, params.signer);\n const amountRaw =\n typeof params.amount === 'bigint'\n ? params.amount\n : toScaled(params.amount, Number(await token.getFunction('decimals')()));\n if (amountRaw <= 0n) throw new Error('deposit amount must be positive');\n\n const holder = await params.signer.getAddress();\n const allowance: bigint = await token.getFunction('allowance')(holder, managerAddress);\n if (allowance < amountRaw) {\n this.ctx.logger('debug', `approving ${amountRaw} of ${erc20Address} to ActionManager`);\n const approval = await token.getFunction('approve')(managerAddress, amountRaw);\n await approval.wait();\n }\n return { actionManager: new Contract(managerAddress, ACTION_MANAGER_ABI, params.signer), amountRaw };\n }\n}\n\n/**\n * CEX-style deposits: send funds to a registered deterministic address\n * from any wallet or exchange; they are credited asynchronously.\n */\nexport class DepositAddressDeposits {\n constructor(private readonly ctx: ClientContext) {}\n\n /**\n * Registers (or re-fetches — the address is deterministic per wallet/\n * subaccount/manager) the deposit address the exchange watches and\n * sweeps, routing funds to an existing subaccount or, with\n * `managerId`, a new one. `wallet` defaults to the client's owner.\n */\n async register(options: { wallet?: string; subaccountId?: number; managerId?: number } = {}) {\n // The address is deterministic per (wallet, subaccount, manager). The\n // server requires a non-zero managerId whenever a subaccount isn't\n // given (it would be creating one), so fail early rather than eat a\n // confusing invalid_params.\n if (!options.subaccountId && !options.managerId) {\n throw new Error('provide subaccountId (existing) or managerId (to route deposits into a new subaccount)');\n }\n return this.ctx.send('public/register_deposit_address', {\n wallet: getAddress(options.wallet ?? this.ctx.credentials().ownerAddress),\n subaccount_id: options.subaccountId,\n manager_id: options.managerId,\n });\n }\n}\n","/**\n * Deposit entrypoints of the protocol's OnchainActionManager\n * (contracts/src/OnchainActionManager.sol). `asset` is the PROTOCOL\n * asset label registered on the WithdrawalOutbox, not an ERC-20 — the\n * contract resolves the underlying token itself and pulls `amount`\n * (in that token's native decimals) via transferFrom, so the token\n * must first be approved to the ActionManager.\n */\nexport const ACTION_MANAGER_ABI = [\n 'function deposit(address asset, uint256 amount, uint64 subaccountId, address fallbackRecipient) returns (uint256 actionId)',\n 'function depositToNewSubaccount(address asset, uint256 amount, uint32 managerId, address owner) returns (uint256 actionId)',\n];\n","/** Minimal ERC-20 surface for deposit approvals and balance checks. */\nexport const ERC20_ABI = [\n 'function approve(address spender, uint256 amount) returns (bool)',\n 'function allowance(address owner, address spender) view returns (uint256)',\n 'function balanceOf(address owner) view returns (uint256)',\n 'function decimals() view returns (uint8)',\n];\n","/** An error response returned by the exchange for a JSON-RPC request. */\nexport class DeriveRpcError extends Error {\n readonly code: number;\n readonly data: unknown;\n readonly method: string;\n\n constructor(method: string, error: { code: number; message: string; data?: unknown }) {\n super(\n `${method}: [${error.code}] ${error.message}${\n error.data !== undefined ? ` — ${JSON.stringify(error.data)}` : ''\n }`,\n );\n this.name = 'DeriveRpcError';\n this.method = method;\n this.code = error.code;\n this.data = error.data;\n }\n}\n\n/** A request that received no response within the transport timeout, or was in flight when the connection dropped. */\nexport class DeriveTimeoutError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'DeriveTimeoutError';\n }\n}\n\n/** A websocket connection failure (initial connect or reconnect exhaustion). */\nexport class DeriveConnectionError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'DeriveConnectionError';\n }\n}\n","import { parseUnits } from 'ethers';\n\n/**\n * A decimal value accepted from callers: a decimal string (\"1500.5\"),\n * a safe number, or a bigint already at the target field's wire scale\n * (e18 for most values; the ERC-20's native decimals for withdrawal\n * amounts).\n */\nexport type DecimalLike = string | number | bigint;\n\n/**\n * Converts a decimal value to the protocol's e18 wire scale. Signed\n * actions ABI-encode all prices/amounts/fees at 1e18 and signatures\n * commit to those exact bytes. (Withdrawal amounts are the exception —\n * they stay in the ERC-20's native decimals; see codecs/withdrawal.)\n */\nexport function toE18(value: DecimalLike): bigint {\n return toScaled(value, 18);\n}\n\n/**\n * The exchange holds decimals at 1e12 and REJECTS (does not truncate) e18\n * words carrying sub-1e12 precision, so more than 12 decimal places can\n * never produce a valid signature. Holds for negative words too.\n */\nexport function assertE12Precision(e18: bigint, field: string): void {\n if (e18 % 1_000_000n !== 0n) {\n throw new Error(`${field} has more than 12 decimal places — the protocol runs at 1e12 precision`);\n }\n}\n\n/** Scales to e18, rejecting negatives and sub-1e12 precision. Shared by the value-bearing codecs. */\nexport function unsignedE18(value: DecimalLike, field: string): bigint {\n const scaled = toE18(value);\n if (scaled < 0n) throw new Error(`${field} must not be negative`);\n assertE12Precision(scaled, field);\n return scaled;\n}\n\nexport function nonNegativeId(value: number | bigint, field: string): number | bigint {\n const valid = typeof value === 'bigint' ? value >= 0n : Number.isSafeInteger(value) && value >= 0;\n if (!valid) throw new Error(`${field} must be a non-negative integer`);\n return value;\n}\n\n/** Default envelope validity for signed actions; comfortably above the API's minimum. */\nexport const DEFAULT_SIGNATURE_EXPIRY_SEC = 300;\n\nexport function toScaled(value: DecimalLike, decimals: number): bigint {\n if (typeof value === 'bigint') return value;\n const text = typeof value === 'number' ? String(value) : value.trim();\n if (!/^-?\\d+(\\.\\d+)?$/.test(text)) {\n throw new Error(\n `invalid decimal value: ${JSON.stringify(value)} (scientific notation and empty strings are not accepted)`,\n );\n }\n return parseUnits(text, decimals);\n}\n\n/**\n * Action nonces are UTC-nanosecond timestamps (the API accepts a\n * ±5-minute intake window), with sub-millisecond digits randomized so\n * concurrent actions never collide.\n */\nexport function randomNonce(now: number = Date.now()): string {\n const nanos = BigInt(now) * 1_000_000n + BigInt(Math.floor(Math.random() * 1_000_000));\n return nanos.toString();\n}\n\n/** Signature expiry as a unix-seconds timestamp, `seconds` from now. */\nexport function expiresIn(seconds: number, now: number = Date.now()): number {\n return Math.floor(now / 1000) + seconds;\n}\n","import type {\n CurrencyResponse,\n GetAllInstrumentsResponse,\n GetLatestSignedFeedsResponse,\n GetReferralPerformanceResult,\n GetTickersResponse,\n GetTransactionResult,\n IndexCandle,\n InstrumentPublicResponse,\n InterestRateHistoryResult,\n MarginWatchResult,\n OptionSettlementPricesResult,\n PublicAssetType,\n TickerSlimSnapshot,\n} from '../types';\nimport type { ClientContext } from './context';\n\nexport interface InstrumentsQuery {\n instrumentType: PublicAssetType;\n currency?: string;\n /** Include expired instruments. Default false. */\n expired?: boolean;\n page?: number;\n pageSize?: number;\n}\n\n/** One collateral leg of a `simulateMargin` portfolio; `amount` is a decimal string. */\nexport interface SimulatedCollateral {\n assetName: string;\n amount: string;\n}\n\n/** One position leg of a `simulateMargin` portfolio; `amount` is a decimal string. */\nexport interface SimulatedPosition {\n instrumentName: string;\n amount: string;\n /** Perps only — entry price to simulate against; defaults to mark price. */\n entryPrice?: string;\n}\n\nexport interface SimulateMarginParams {\n marginType: 'PM' | 'PM2' | 'SM';\n /** Required for portfolio margin. */\n market?: string;\n simulatedCollaterals: SimulatedCollateral[];\n simulatedPositions: SimulatedPosition[];\n /** Deltas layered on top of `simulatedCollaterals` to model a deposit/withdrawal/spot trade. */\n simulatedCollateralChanges?: SimulatedCollateral[];\n /** Deltas layered on top of `simulatedPositions` to model a perp/option trade. */\n simulatedPositionChanges?: SimulatedPosition[];\n}\n\nconst toWireCollateral = (c: SimulatedCollateral) => ({ asset_name: c.assetName, amount: c.amount });\nconst toWirePosition = (p: SimulatedPosition) => ({\n instrument_name: p.instrumentName,\n amount: p.amount,\n entry_price: p.entryPrice ?? null,\n});\n\n/** Public market data endpoints — no authentication or signing. */\nexport class MarketDataApi {\n constructor(private readonly ctx: ClientContext) {}\n\n getInstrument(instrumentName: string): Promise<InstrumentPublicResponse> {\n return this.ctx.send('public/get_instrument', { instrument_name: instrumentName });\n }\n\n /** One page of instruments; the response carries pagination info. */\n getInstruments(query: InstrumentsQuery): Promise<GetAllInstrumentsResponse> {\n return this.ctx.send('public/get_all_instruments', {\n instrument_type: query.instrumentType,\n expired: query.expired ?? false,\n currency: query.currency ?? null,\n page: query.page ?? null,\n page_size: query.pageSize ?? null,\n });\n }\n\n /** Every currently tradeable instrument name across all currencies. */\n getAllLiveInstruments(): Promise<string[]> {\n return this.ctx.send('public/get_all_live_instruments', null);\n }\n\n /**\n * Latest ticker snapshot: top of book (`b`/`a` prices, `B`/`A`\n * amounts), mark (`M`) and index (`I`) prices, and match bounds.\n */\n getTicker(instrumentName: string): Promise<TickerSlimSnapshot> {\n // The generated schema leaves public/get_ticker's result untyped; this is the shape it returns.\n return this.ctx.send('public/get_ticker', { instrument_name: instrumentName }) as Promise<TickerSlimSnapshot>;\n }\n\n /** Ticker snapshots for every instrument of a type, keyed by instrument name. */\n getTickers(params: {\n instrumentType: PublicAssetType;\n currency?: string;\n expiryDate?: number;\n }): Promise<GetTickersResponse> {\n return this.ctx.send('public/get_tickers', {\n instrument_type: params.instrumentType,\n currency: params.currency ?? null,\n expiry_date: params.expiryDate,\n });\n }\n\n getAllCurrencies(): Promise<CurrencyResponse[]> {\n return this.ctx.send('public/get_all_currencies', null);\n }\n\n getCurrency(currency: string): Promise<CurrencyResponse> {\n return this.ctx.send('public/get_currency', { currency });\n }\n\n /** Latest signed oracle feeds (spot/perp/option/forward), optionally filtered by currency/expiry. */\n getLatestSignedFeeds(params: { currency?: string; expiry?: number } = {}): Promise<GetLatestSignedFeedsResponse> {\n return this.ctx.send('public/get_latest_signed_feeds', {\n currency: params.currency ?? null,\n expiry: params.expiry ?? null,\n });\n }\n\n /** Settlement prices per expiry for the currency's options. */\n getOptionSettlementPrices(currency: string): Promise<OptionSettlementPricesResult> {\n return this.ctx.send('public/get_option_settlement_prices', { currency });\n }\n\n /** On-chain settlement status and hash for a single op by its uuid. */\n getTransaction(opUuid: string): Promise<GetTransactionResult> {\n return this.ctx.send('public/get_transaction', { op_uuid: opUuid });\n }\n\n /** Referral fee-share and reward breakdown over a millisecond window. */\n getReferralPerformance(params: {\n startMs: number;\n endMs: number;\n referralCode?: string;\n wallet?: string;\n }): Promise<GetReferralPerformanceResult> {\n return this.ctx.send('public/get_referral_performance', {\n start_ms: params.startMs,\n end_ms: params.endMs,\n referral_code: params.referralCode ?? null,\n wallet: params.wallet ?? null,\n });\n }\n\n /** Spot index OHLC candles for a currency over a UTC-seconds window; `period` is the bucket size in seconds. */\n getIndexChartData(params: {\n currency: string;\n startTimestamp: number;\n endTimestamp: number;\n period: number;\n }): Promise<IndexCandle[]> {\n return this.ctx.send('public/get_index_chart_data', {\n currency: params.currency,\n start_timestamp: params.startTimestamp,\n end_timestamp: params.endTimestamp,\n period: params.period,\n });\n }\n\n /** Interest-rate candles for a currency's lending pools, optionally scoped to one risk universe. */\n getInterestRateHistory(params: {\n currency: string;\n startTimestamp?: number;\n endTimestamp?: number;\n period?: number;\n riskUniverseId?: number;\n }): Promise<InterestRateHistoryResult> {\n return this.ctx.send('public/get_interest_rate_history', {\n currency: params.currency,\n start_timestamp: params.startTimestamp ?? null,\n end_timestamp: params.endTimestamp ?? null,\n period: params.period ?? null,\n risk_universe_id: params.riskUniverseId ?? null,\n });\n }\n\n // The methods below pre-date the generated EndpointMap, so their method string and params\n // are cast through `never`; results are untyped (`unknown`) unless a generated type exists.\n\n /** 24h and lifetime volume/fee/trade statistics for an instrument name or type (`ALL`/`OPTION`/`PERP`/`SPOT`). */\n getStatistics(params: { instrumentName: string; currency?: string; endTime?: number }): Promise<unknown> {\n return this.ctx.send(\n 'public/statistics' as never,\n {\n instrument_name: params.instrumentName,\n currency: params.currency ?? null,\n end_time: params.endTime ?? null,\n } as never,\n );\n }\n\n /** All maker programs, including past/historical epochs. */\n getMakerPrograms(): Promise<unknown> {\n return this.ctx.send('public/get_maker_programs' as never, {} as never);\n }\n\n /** Per-maker score breakdown for one program epoch. */\n getMakerProgramScores(params: { programName: string; epochStartTimestamp: number }): Promise<unknown> {\n return this.ctx.send(\n 'public/get_maker_program_scores' as never,\n {\n program_name: params.programName,\n epoch_start_timestamp: params.epochStartTimestamp,\n } as never,\n );\n }\n\n /** Paginated liquidation-auction history across all subaccounts (or one, if `subaccountId` is given). */\n getLiquidationHistory(\n params: {\n subaccountId?: number;\n fromTimestamp?: number;\n toTimestamp?: number;\n page?: number;\n pageSize?: number;\n } = {},\n ): Promise<unknown> {\n return this.ctx.send(\n 'public/get_liquidation_history' as never,\n {\n subaccount_id: params.subaccountId ?? null,\n start_timestamp: params.fromTimestamp,\n end_timestamp: params.toTimestamp,\n page: params.page,\n page_size: params.pageSize,\n } as never,\n );\n }\n\n /** Mark-to-market value and maintenance margin for a subaccount. */\n marginWatch(params: {\n subaccountId: number;\n forceOnchain?: boolean;\n isDelayedLiquidation?: boolean;\n }): Promise<MarginWatchResult> {\n return this.ctx.send(\n 'public/margin_watch' as never,\n {\n subaccount_id: params.subaccountId,\n force_onchain: params.forceOnchain,\n is_delayed_liquidation: params.isDelayedLiquidation,\n } as never,\n );\n }\n\n /** Margin requirement for a simulated portfolio and optional trade deltas; ignores open-order margin. */\n simulateMargin(params: SimulateMarginParams): Promise<unknown> {\n return this.ctx.send(\n 'public/get_margin' as never,\n {\n margin_type: params.marginType,\n market: params.market ?? null,\n simulated_collaterals: params.simulatedCollaterals.map(toWireCollateral),\n simulated_positions: params.simulatedPositions.map(toWirePosition),\n simulated_collateral_changes: params.simulatedCollateralChanges?.map(toWireCollateral) ?? null,\n simulated_position_changes: params.simulatedPositionChanges?.map(toWirePosition) ?? null,\n } as never,\n );\n }\n}\n","import { formatUnits } from 'ethers';\nimport { encodeTradeData } from '../codecs/trade';\nimport { SignedAction } from '../signing/action';\nimport { domainSeparator } from '../signing/eip712';\nimport { DEFAULT_SIGNATURE_EXPIRY_SEC, expiresIn, randomNonce, toE18, type DecimalLike } from '../signing/encoding';\nimport type {\n CancelAllResponse,\n CancelByLabelWireResponse,\n InstrumentPublicResponse,\n OrderCreatedWireResponse,\n OrderWireResponse,\n PaginatedOrdersResult,\n ResetMmpResponse,\n SetMmpConfigResponse,\n TriggerPriceType,\n TriggerType,\n} from '../types';\nimport type { ClientContext } from './context';\nimport type { MarketDataApi } from './marketData';\n\nexport interface PlaceOrderParams {\n subaccountId: number;\n instrumentName: string;\n direction: 'buy' | 'sell';\n amount: DecimalLike;\n limitPrice: DecimalLike;\n /**\n * Highest fee per unit the signature allows (the exchange charges its\n * normal fee regardless — this only caps it). Defaults to 3x the\n * instrument's current taker cost; pass explicitly for market makers.\n */\n maxFee?: DecimalLike;\n orderType?: 'limit' | 'market';\n timeInForce?: 'gtc' | 'post_only' | 'fok' | 'ioc';\n label?: string;\n /** Count this order against the market-maker-protection limits. */\n mmp?: boolean;\n reduceOnly?: boolean;\n nonce?: string;\n signatureExpirySec?: number;\n /** Conditional-order trigger: fires the order when the price condition is met. */\n triggerType?: TriggerType;\n triggerPrice?: DecimalLike;\n triggerPriceType?: TriggerPriceType;\n /** Referral code recorded against the order's fees. */\n referralCode?: string;\n /** Reject (rather than downgrade) a post-only order that would cross. */\n rejectPostOnly?: boolean;\n /** Marks the order for the atomic-signing flow. */\n isAtomicSigning?: boolean;\n /** Caller-supplied order tag (wire field `client`). */\n clientOrderId?: string;\n /** Additional per-unit fee the caller opts to pay (wire field `extra_fee`). */\n extraFee?: DecimalLike;\n /** Reject the order if the server clock is past this unix-seconds deadline. */\n rejectTimestamp?: number;\n /** Algo-order parameters (e.g. TWAP). */\n algoType?: string;\n algoDurationSec?: number;\n algoNumSlices?: number;\n}\n\nexport interface OrderHistoryQuery {\n subaccountId?: number;\n fromTimestamp?: number;\n toTimestamp?: number;\n page?: number;\n pageSize?: number;\n}\n\nexport interface SetMmpConfigParams {\n subaccountId: number;\n currency: string;\n /** Freeze duration (ms) once tripped; 0 requires a manual `resetMmp`. */\n mmpFrozenTime: number;\n /** Rolling protection window (ms) over which fills accumulate. */\n mmpInterval: number;\n /** Filled-amount limit within the window (decimal string); omit or 0 for unlimited. */\n mmpAmountLimit?: DecimalLike;\n /** Net-delta limit within the window (decimal string); omit or 0 for unlimited. */\n mmpDeltaLimit?: DecimalLike;\n}\n\n/** Order placement (signed trade actions) and management. */\nexport class OrdersApi {\n /** Asset address/subId per instrument name are immutable — cache the lookups. */\n private readonly instruments = new Map<string, Promise<InstrumentPublicResponse>>();\n\n constructor(\n private readonly ctx: ClientContext,\n private readonly marketData: MarketDataApi,\n ) {}\n\n /**\n * Builds the signed wire payload shared by `place` and `quote`. The trade\n * action commits only to asset/price/amount/fee/recipient — trigger,\n * referral, algo and the other flags below are wire-only and never signed.\n */\n private async buildOrderPayload(params: PlaceOrderParams) {\n const amount = toE18(params.amount);\n if (amount <= 0n) throw new Error('order amount must be positive');\n const limitPrice = toE18(params.limitPrice);\n const maxFee = toE18(params.maxFee ?? (await this.defaultMaxFee(params.instrumentName, params.limitPrice)));\n if (maxFee < 0n) throw new Error('maxFee must not be negative');\n\n const instrument = await this.instrument(params.instrumentName);\n const nonce = params.nonce ?? randomNonce();\n const expirySec = params.signatureExpirySec ?? expiresIn(DEFAULT_SIGNATURE_EXPIRY_SEC);\n const { ownerAddress, signer } = this.ctx.credentials();\n const action = new SignedAction(\n {\n subaccountId: params.subaccountId,\n nonce,\n module: this.ctx.network.modules.trade,\n data: encodeTradeData({\n assetAddress: instrument.base_asset_address,\n subId: instrument.base_asset_sub_id,\n limitPrice,\n amount,\n maxFee,\n recipientSubaccountId: params.subaccountId,\n isBid: params.direction === 'buy',\n }),\n expirySec,\n owner: ownerAddress,\n signer: signer.address,\n },\n domainSeparator(this.ctx.network),\n ).sign(signer);\n\n return {\n subaccount_id: params.subaccountId,\n instrument_name: params.instrumentName,\n direction: params.direction,\n // Wire decimals are formatted from the signed e18 words so the exchange re-derives the exact signed bytes.\n limit_price: formatUnits(limitPrice, 18),\n amount: formatUnits(amount, 18),\n max_fee: formatUnits(maxFee, 18),\n nonce,\n signer: signer.address,\n signature: action.signature!,\n signature_expiry_sec: expirySec,\n order_type: params.orderType ?? 'limit',\n time_in_force: params.timeInForce,\n label: params.label,\n mmp: params.mmp,\n reduce_only: params.reduceOnly,\n trigger_type: params.triggerType,\n trigger_price: params.triggerPrice === undefined ? undefined : formatUnits(toE18(params.triggerPrice), 18),\n trigger_price_type: params.triggerPriceType,\n referral_code: params.referralCode,\n reject_post_only: params.rejectPostOnly,\n is_atomic_signing: params.isAtomicSigning,\n client: params.clientOrderId,\n extra_fee: params.extraFee === undefined ? undefined : formatUnits(toE18(params.extraFee), 18),\n reject_timestamp: params.rejectTimestamp,\n algo_type: params.algoType,\n algo_duration_sec: params.algoDurationSec,\n algo_num_slices: params.algoNumSlices,\n };\n }\n\n async place(params: PlaceOrderParams): Promise<OrderCreatedWireResponse> {\n return this.ctx.send('private/order', await this.buildOrderPayload(params));\n }\n\n /**\n * Prices an order without placing it. Signs like `place` (pass\n * `{ public: true }` to hit the unauthenticated public estimate instead).\n */\n async getOrderQuote(params: PlaceOrderParams, options: { public?: boolean } = {}) {\n const payload = await this.buildOrderPayload(params);\n return this.ctx.send(options.public ? 'public/order_quote' : 'private/order_quote', payload as never);\n }\n\n /** Cancels one order. Needs only authentication, not a signature. */\n cancel(params: { subaccountId: number; orderId: string; instrumentName: string }): Promise<OrderWireResponse> {\n return this.ctx.send('private/cancel', {\n subaccount_id: params.subaccountId,\n order_id: params.orderId,\n instrument_name: params.instrumentName,\n });\n }\n\n cancelAll(\n subaccountId: number,\n options?: { cancelTriggerOrders?: boolean; cancelAlgoOrders?: boolean },\n ): Promise<CancelAllResponse> {\n return this.ctx.send('private/cancel_all', {\n subaccount_id: subaccountId,\n cancel_trigger_orders: options?.cancelTriggerOrders ?? null,\n cancel_algo_orders: options?.cancelAlgoOrders ?? null,\n });\n }\n\n cancelByLabel(params: {\n subaccountId: number;\n label: string;\n instrumentName?: string;\n }): Promise<CancelByLabelWireResponse> {\n return this.ctx.send('private/cancel_by_label', {\n subaccount_id: params.subaccountId,\n label: params.label,\n instrument_name: params.instrumentName ?? null,\n });\n }\n\n getOrder(params: { subaccountId: number; orderId: string }): Promise<OrderWireResponse> {\n return this.ctx.send('private/get_order', {\n subaccount_id: params.subaccountId,\n order_id: params.orderId,\n });\n }\n\n async getOpenOrders(subaccountId: number): Promise<OrderWireResponse[]> {\n const result = await this.ctx.send('private/get_open_orders', { subaccount_id: subaccountId });\n return result.orders;\n }\n\n /** Paginated closed/open order history; defaults to all of the wallet's subaccounts. */\n getOrderHistory(query: OrderHistoryQuery = {}): Promise<PaginatedOrdersResult> {\n return this.ctx.send('private/get_order_history', {\n subaccount_id: query.subaccountId ?? null,\n from_timestamp: query.fromTimestamp ?? null,\n to_timestamp: query.toTimestamp ?? null,\n page: query.page ?? null,\n page_size: query.pageSize ?? null,\n });\n }\n\n /** Sets the market-maker-protection limits for a currency; overwrites any existing config. */\n setMmpConfig(params: SetMmpConfigParams): Promise<SetMmpConfigResponse> {\n return this.ctx.send('private/set_mmp_config', {\n subaccount_id: params.subaccountId,\n currency: params.currency,\n mmp_frozen_time: params.mmpFrozenTime,\n mmp_interval: params.mmpInterval,\n mmp_amount_limit: params.mmpAmountLimit === undefined ? undefined : String(params.mmpAmountLimit),\n mmp_delta_limit: params.mmpDeltaLimit === undefined ? undefined : String(params.mmpDeltaLimit),\n });\n }\n\n /** Clears a tripped market-maker-protection freeze; scoped to one currency, or all when omitted. */\n resetMmp(params: { subaccountId: number; currency?: string }): Promise<ResetMmpResponse> {\n return this.ctx.send('private/reset_mmp', {\n subaccount_id: params.subaccountId,\n currency: params.currency ?? null,\n });\n }\n\n private instrument(name: string): Promise<InstrumentPublicResponse> {\n let lookup = this.instruments.get(name);\n if (!lookup) {\n lookup = this.marketData.getInstrument(name);\n lookup.catch(() => this.instruments.delete(name)); // never cache failures\n this.instruments.set(name, lookup);\n }\n return lookup;\n }\n\n /**\n * The signed max fee must cover whatever the exchange charges at match\n * time or the order is rejected. The exchange bounds the per-unit fee at\n * `2 x taker_fee_rate x max(index, limit) + base_fee`, where `index` is\n * the underlying SPOT feed (`ticker.I`) — NOT the option mark\n * (`ticker.M`). We mirror that and apply a 3x headroom for feed moves\n * between signing and matching.\n */\n private async defaultMaxFee(instrumentName: string, limitPrice: DecimalLike): Promise<string> {\n const [instrument, ticker] = await Promise.all([\n this.instrument(instrumentName),\n this.marketData.getTicker(instrumentName),\n ]);\n const feeBasis = Math.max(Number(ticker.I), Number(limitPrice));\n const perUnitTakerCost = feeBasis * Number(instrument.taker_fee_rate) + Number(instrument.base_fee);\n if (!Number.isFinite(perUnitTakerCost) || perUnitTakerCost < 0) {\n throw new Error(`cannot derive a default max fee for ${instrumentName} — pass maxFee explicitly`);\n }\n return (perUnitTakerCost * 3).toFixed(6);\n }\n}\n","import { concat, getAddress, toBeHex, zeroPadValue } from 'ethers';\nimport { toE18, type DecimalLike } from '../signing/encoding';\n\n/**\n * Inputs to the trade (order) action payload, verified by the trade\n * module (`network.modules.trade`).\n */\nexport interface TradeActionFields {\n /** Protocol asset contract of the instrument (`base_asset_address`). */\n assetAddress: string;\n /** Asset sub id (`base_asset_sub_id`): 0 for perps/spot, the option id for options. */\n subId: string | number | bigint;\n limitPrice: DecimalLike;\n amount: DecimalLike;\n /** Worst acceptable fee per unit traded the signature allows. */\n maxFee: DecimalLike;\n /** Subaccount credited with the fill — the trading subaccount itself. */\n recipientSubaccountId: number | bigint;\n isBid: boolean;\n}\n\nconst I128_MIN = -(2n ** 127n);\nconst I128_MAX = 2n ** 127n - 1n;\nconst U64_MAX = 2n ** 64n - 1n;\nconst U128_MAX = 2n ** 128n - 1n;\n\n/**\n * The exchange holds decimals at 1e12 and rejects (not truncates) signed\n * e18 words with sub-1e12 precision, so more than 12 decimal places can\n * never produce a valid signature.\n */\nfunction assertE12Precision(e18: bigint, field: string): void {\n if (e18 % 1_000_000n !== 0n) {\n throw new Error(`${field} has more than 12 decimal places — the protocol runs at 1e12 precision`);\n }\n}\n\n/**\n * The exchange reads limit price and amount as an i128 from the LOW 16\n * bytes of the word; the high 16 bytes stay zero even for negative\n * values. Standard ABI int256 encoding would sign-extend the high half\n * and produce bytes the exchange rejects.\n */\nfunction i128LowHalfWord(e18: bigint, field: string): string {\n if (e18 < I128_MIN || e18 > I128_MAX) {\n throw new Error(`${field} out of range: e18-scaled value must fit in an i128`);\n }\n const twosComplement = e18 < 0n ? e18 + 2n ** 128n : e18;\n return zeroPadValue(toBeHex(twosComplement, 16), 32);\n}\n\nfunction uintWord(value: bigint, max: bigint, field: string): string {\n if (value < 0n || value > max) {\n throw new Error(`${field} out of range: must be an unsigned integer <= ${max}`);\n }\n return zeroPadValue(toBeHex(value), 32);\n}\n\n/**\n * Encodes the order action data: seven static words — asset, subId,\n * limitPrice, amount, maxFee, recipientId, isBid — with\n * prices/amounts/fee e18-scaled.\n */\nexport function encodeTradeData(fields: TradeActionFields): string {\n const limitPrice = toE18(fields.limitPrice);\n const amount = toE18(fields.amount);\n const maxFee = toE18(fields.maxFee);\n assertE12Precision(limitPrice, 'limitPrice');\n assertE12Precision(amount, 'amount');\n assertE12Precision(maxFee, 'maxFee');\n return concat([\n zeroPadValue(getAddress(fields.assetAddress), 32),\n uintWord(BigInt(fields.subId), U128_MAX, 'subId'),\n i128LowHalfWord(limitPrice, 'limitPrice'),\n i128LowHalfWord(amount, 'amount'),\n uintWord(maxFee, U128_MAX, 'maxFee'),\n uintWord(BigInt(fields.recipientSubaccountId), U64_MAX, 'recipientSubaccountId'),\n zeroPadValue(fields.isBid ? '0x01' : '0x00', 32),\n ]);\n}\n","import { AbiCoder, concat, getAddress, isHexString, keccak256, type BaseWallet } from 'ethers';\nimport { ACTION_TYPEHASH } from './eip712';\n\nexport interface ActionFields {\n subaccountId: number | bigint;\n /** UTC-nanosecond timestamp as a decimal string; see `randomNonce()`. */\n nonce: string;\n /** Address of the protocol module that verifies this action. */\n module: string;\n /** ABI-encoded action payload produced by one of the codecs. */\n data: string;\n /** Unix-seconds signature expiry. */\n expirySec: number;\n owner: string;\n signer: string;\n}\n\n/**\n * The signed-action envelope shared by every protocol operation\n * (orders, transfers, withdrawals, RFQs, session keys, vault actions).\n *\n * The digest is\n * keccak256(0x1901 ‖ domainSeparator ‖ structHash) where structHash\n * commits to ACTION_TYPEHASH, the envelope fields, and keccak256(data).\n * The domain separator comes from `domainSeparator(network)`.\n */\nexport class SignedAction {\n readonly fields: Readonly<ActionFields>;\n private readonly domainSeparator: string;\n signature?: string;\n\n constructor(fields: ActionFields, domainSeparator: string) {\n if (!isHexString(fields.data)) throw new Error('action data must be a 0x-prefixed hex string');\n if (!/^\\d+$/.test(fields.nonce)) throw new Error('action nonce must be a decimal string');\n if (!isHexString(domainSeparator, 32)) throw new Error('domainSeparator must be 32 bytes of hex');\n this.fields = Object.freeze({\n ...fields,\n module: getAddress(fields.module),\n owner: getAddress(fields.owner),\n signer: getAddress(fields.signer),\n });\n this.domainSeparator = domainSeparator;\n }\n\n actionHash(): string {\n const f = this.fields;\n return keccak256(\n AbiCoder.defaultAbiCoder().encode(\n ['bytes32', 'uint256', 'uint256', 'address', 'bytes32', 'uint256', 'address', 'address'],\n [ACTION_TYPEHASH, f.subaccountId, f.nonce, f.module, keccak256(f.data), f.expirySec, f.owner, f.signer],\n ),\n );\n }\n\n digest(): string {\n return keccak256(concat(['0x1901', this.domainSeparator, this.actionHash()]));\n }\n\n /**\n * Signs the digest with a raw signing key. The wallet must be the\n * declared `signer` (the owner itself, or a registered session key).\n */\n sign(wallet: BaseWallet): this {\n if (getAddress(wallet.address) !== this.fields.signer) {\n throw new Error(`signing wallet ${wallet.address} does not match declared signer ${this.fields.signer}`);\n }\n this.signature = wallet.signingKey.sign(this.digest()).serialized;\n return this;\n }\n}\n","import { AbiCoder, getAddress, keccak256, toUtf8Bytes } from 'ethers';\nimport type { NetworkConfig } from '../config/types';\n\n/**\n * keccak256(\"Action(uint256 subaccountId,uint256 nonce,address module,bytes data,uint256 expiry,address owner,address signer)\").\n * Chain-independent protocol constant.\n */\nexport const ACTION_TYPEHASH = '0x4d7a9f27c403ff9c0f19bce61d76d82f9aa29f8d6d4b0c5474607d9770d1af17';\n\nconst DOMAIN_TYPEHASH = keccak256(\n toUtf8Bytes('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),\n);\nconst NAME_HASH = keccak256(toUtf8Bytes('Matching'));\nconst VERSION_HASH = keccak256(toUtf8Bytes('1.0'));\n\n/**\n * The EIP-712 `verifyingContract` for the action domain. v3 anchors the\n * domain to the v2 mainnet `Matching` contract on every network — the\n * verifying contract is constant, only the chain id varies — so it is\n * hardcoded here rather than read from network config.\n */\nexport const MATCHING_VERIFYING_CONTRACT = '0xeB8d770ec18DB98Db922E9D83260A585b9F0DeAD';\n\n/**\n * The EIP-712 domain separator actions sign under — a standard 4-field\n * `EIP712Domain` (name \"Matching\", version \"1.0\", no salt) computed from\n * the network's chain id and the constant Matching verifying contract.\n */\nexport function domainSeparator(network: Pick<NetworkConfig, 'chainId'>): string {\n return keccak256(\n AbiCoder.defaultAbiCoder().encode(\n ['bytes32', 'bytes32', 'bytes32', 'uint256', 'address'],\n [DOMAIN_TYPEHASH, NAME_HASH, VERSION_HASH, network.chainId, getAddress(MATCHING_VERIFYING_CONTRACT)],\n ),\n );\n}\n","import { formatUnits } from 'ethers';\nimport { encodeRfqExecute, encodeRfqQuote, sortRfqLegs } from '../codecs/rfq';\nimport { SignedAction } from '../signing/action';\nimport { expiresIn, randomNonce, toE18, type DecimalLike } from '../signing/encoding';\nimport { domainSeparator } from '../signing/eip712';\nimport type { Direction, InstrumentPublicResponse, TransferPositionsWireResponse } from '../types';\nimport type { ClientContext } from './context';\n\n/** One priced position leg shared by both sides of a position transfer. */\nexport interface PositionTransferLeg {\n instrumentName: string;\n amount: DecimalLike;\n price: DecimalLike;\n direction: Direction;\n}\n\nexport interface TransferPositionsParams {\n /** Subaccount signing the maker quote. Must differ from `takerSubaccountId`. */\n makerSubaccountId: number;\n /** Subaccount signing the taker execute. Must differ from `makerSubaccountId`. */\n takerSubaccountId: number;\n /** Maker quote direction. The SDK derives the taker's opposite direction. */\n makerDirection: Direction;\n /** The exact priced package both sides authorize. */\n legs: PositionTransferLeg[];\n makerNonce?: string;\n takerNonce?: string;\n /** Shared signature expiry for both sides. Defaults to 700 seconds from now. */\n signatureExpirySec?: number;\n}\n\ninterface ResolvedPositionTransferLeg {\n instrumentName: string;\n assetAddress: string;\n subId: string;\n price: bigint;\n amount: bigint;\n direction: Direction;\n}\n\n/**\n * Transfers perp/option positions between two subaccounts owned by the same\n * wallet. The route executes an RFQ internally, so the SDK signs a zero-fee\n * maker quote and the matching opposite-direction taker execute.\n */\nexport class PositionTransfersApi {\n private readonly instruments = new Map<string, Promise<InstrumentPublicResponse>>();\n\n constructor(private readonly ctx: ClientContext) {}\n\n async transferPositions(params: TransferPositionsParams): Promise<TransferPositionsWireResponse> {\n if (params.makerSubaccountId === params.takerSubaccountId) {\n throw new Error('makerSubaccountId and takerSubaccountId must be different');\n }\n if (params.legs.length === 0) {\n throw new Error('transferPositions needs at least one leg');\n }\n\n const makerNonce = params.makerNonce ?? randomNonce();\n const takerNonce = params.takerNonce ?? randomNonce();\n if (makerNonce === takerNonce) {\n throw new Error('makerNonce and takerNonce must be different');\n }\n\n const expirySec = params.signatureExpirySec ?? expiresIn(700);\n const takerDirection: Direction = params.makerDirection === 'buy' ? 'sell' : 'buy';\n const legs = await this.resolveLegs(params.legs);\n const maker = this.signAction(\n params.makerSubaccountId,\n makerNonce,\n expirySec,\n encodeRfqQuote({ maxFee: 0n, direction: params.makerDirection, legs }),\n );\n const taker = this.signAction(\n params.takerSubaccountId,\n takerNonce,\n expirySec,\n encodeRfqExecute({ maxFee: 0n, direction: takerDirection, legs }),\n );\n const wireLegs = legs.map(wireLeg);\n\n return this.ctx.send('private/transfer_positions', {\n wallet: this.ctx.credentials().ownerAddress,\n maker_params: {\n subaccount_id: params.makerSubaccountId,\n direction: params.makerDirection,\n legs: wireLegs,\n max_fee: formatUnits(0n, 18),\n nonce: makerNonce,\n signer: maker.signer,\n signature: maker.signature,\n signature_expiry_sec: expirySec,\n },\n taker_params: {\n subaccount_id: params.takerSubaccountId,\n direction: takerDirection,\n legs: wireLegs,\n max_fee: formatUnits(0n, 18),\n nonce: takerNonce,\n signer: taker.signer,\n signature: taker.signature,\n signature_expiry_sec: expirySec,\n },\n });\n }\n\n private async resolveLegs(legs: PositionTransferLeg[]): Promise<ResolvedPositionTransferLeg[]> {\n return sortRfqLegs(\n await Promise.all(\n legs.map(async (leg) => {\n const instrument = await this.instrument(leg.instrumentName);\n return {\n instrumentName: leg.instrumentName,\n assetAddress: instrument.base_asset_address,\n subId: instrument.base_asset_sub_id,\n price: toE18(leg.price),\n amount: toE18(leg.amount),\n direction: leg.direction,\n };\n }),\n ),\n );\n }\n\n private instrument(name: string): Promise<InstrumentPublicResponse> {\n let lookup = this.instruments.get(name);\n if (!lookup) {\n lookup = this.ctx.send('public/get_instrument', { instrument_name: name });\n lookup.catch(() => this.instruments.delete(name));\n this.instruments.set(name, lookup);\n }\n return lookup;\n }\n\n private signAction(\n subaccountId: number,\n nonce: string,\n expirySec: number,\n data: string,\n ): { signer: string; signature: string } {\n const { ownerAddress, signer } = this.ctx.credentials();\n const action = new SignedAction(\n {\n subaccountId,\n nonce,\n module: this.ctx.network.modules.rfq,\n data,\n expirySec,\n owner: ownerAddress,\n signer: signer.address,\n },\n domainSeparator(this.ctx.network),\n ).sign(signer);\n return { signer: action.fields.signer, signature: action.signature! };\n }\n}\n\nfunction wireLeg(leg: ResolvedPositionTransferLeg): {\n amount: string;\n direction: Direction;\n instrument_name: string;\n price: string;\n} {\n return {\n amount: formatUnits(leg.amount, 18),\n direction: leg.direction,\n instrument_name: leg.instrumentName,\n price: formatUnits(leg.price, 18),\n };\n}\n","import { AbiCoder, getAddress, keccak256 } from 'ethers';\nimport { assertE12Precision, toE18, unsignedE18, type DecimalLike } from '../signing/encoding';\nimport type { Direction } from '../types';\n\n/**\n * RFQ action-data codecs.\n *\n * Maker and taker must hash byte-identical leg bundles: legs are sorted\n * lexicographically by instrument name, and each signed leg amount is\n * `amount × legDirectionSign × directionSign × perspectiveSign`. The maker\n * encodes with their own quote direction (perspective +1); the taker\n * executes with the opposite direction and perspective −1, which cancels\n * back to the maker's exact values — the server rebuilds the taker's\n * order hash from the maker's stored quote.\n */\n\n/** A quoted leg carrying everything the signature commits to. */\nexport interface RfqSignedLeg {\n /** Canonical ordering key — both sides sign legs sorted by this. */\n instrumentName: string;\n /** Protocol asset contract for the instrument (option or perp). */\n assetAddress: string;\n /** Asset sub id: '0' for perps, the option's encoded sub id otherwise. */\n subId: string | bigint;\n /** Per-unit price, always positive; e18-scaled into the signed bytes. */\n price: DecimalLike;\n /** Unsigned size — direction carries the sign. */\n amount: DecimalLike;\n direction: Direction;\n}\n\nexport interface RfqQuoteFields {\n /** Worst fee the signer accepts, in USD; e18 in the signed bytes. */\n maxFee: DecimalLike;\n /** The maker's quote direction (taker execute: the taker's own direction). */\n direction: Direction;\n legs: RfqSignedLeg[];\n}\n\n/** Sorts legs into the canonical order both counterparties sign and send. */\nexport function sortRfqLegs<T extends { instrumentName: string }>(legs: readonly T[]): T[] {\n return [...legs].sort((a, b) =>\n a.instrumentName < b.instrumentName ? -1 : a.instrumentName > b.instrumentName ? 1 : 0,\n );\n}\n\nconst LEGS_ABI = '(address,uint256,uint256,int256)[]';\n\n/**\n * Maker quote data: `abi.encode(RfqOrder{ maxFee, trades[] })` —\n * `[0x20][maxFee][0x40][N][4 words per leg]`. Unlike the trade codec's\n * low-16-byte i128 amount words, a negative leg amount here is a full\n * sign-extended int256 (high 16 bytes 0xff), which is standard AbiCoder\n * output.\n */\nexport function encodeRfqQuote(fields: RfqQuoteFields): string {\n return AbiCoder.defaultAbiCoder().encode(\n [`(uint256,${LEGS_ABI})`],\n [[maxFeeE18(fields.maxFee), legTuples(fields, 1n)]],\n );\n}\n\n/**\n * Taker execute data: `abi.encode(bytes32 orderHash, uint256 maxFee)` where\n * `orderHash = keccak256(abi.encode(trades[]))` — the maker's legs only,\n * maker maxFee excluded. `fields.direction` is the TAKER's direction\n * (opposite of the quote's); `fields.maxFee` is the taker's own fee cap.\n */\nexport function encodeRfqExecute(fields: RfqQuoteFields): string {\n const coder = AbiCoder.defaultAbiCoder();\n const orderHash = keccak256(coder.encode([LEGS_ABI], [legTuples(fields, -1n)]));\n return coder.encode(['bytes32', 'uint256'], [orderHash, maxFeeE18(fields.maxFee)]);\n}\n\nfunction maxFeeE18(maxFee: DecimalLike): bigint {\n return unsignedE18(maxFee, 'rfq maxFee');\n}\n\nfunction legTuples(\n fields: RfqQuoteFields,\n perspectiveSign: 1n | -1n,\n): Array<readonly [string, bigint, bigint, bigint]> {\n const directionSign = fields.direction === 'buy' ? 1n : -1n;\n return sortRfqLegs(fields.legs).map((leg) => {\n const price = unsignedE18(leg.price, `rfq leg price (${leg.instrumentName})`);\n const amount = toE18(leg.amount);\n if (amount <= 0n)\n throw new Error(`rfq leg amount must be positive (direction carries the sign): ${leg.instrumentName}`);\n assertE12Precision(amount, `rfq leg amount (${leg.instrumentName})`);\n const legSign = leg.direction === 'buy' ? 1n : -1n;\n return [\n getAddress(leg.assetAddress),\n BigInt(leg.subId),\n price,\n amount * legSign * directionSign * perspectiveSign,\n ] as const;\n });\n}\n","import { formatUnits, getAddress } from 'ethers';\nimport { encodeRfqExecute, encodeRfqQuote, sortRfqLegs } from '../codecs/rfq';\nimport { SignedAction } from '../signing/action';\nimport { domainSeparator } from '../signing/eip712';\nimport { expiresIn, randomNonce, toE18, type DecimalLike } from '../signing/encoding';\nimport type {\n CancelBatchResult,\n CancelRfqResponse,\n Direction,\n InstrumentPublicResponse,\n QuoteExecuteWireResponse,\n QuotePollWireResponse,\n QuotePrivateWireResponse,\n QuoteResultPublic,\n RFQPollWireResponse,\n RFQPrivateWireResponse,\n RfqGetBestQuoteWireResponse,\n} from '../types';\nimport type { ClientContext } from './context';\n\n/** A leg of an RFQ as requested by the taker — unpriced; makers quote the price. */\nexport interface RfqLeg {\n instrumentName: string;\n amount: DecimalLike;\n direction: Direction;\n}\n\n/** A priced leg as signed by the maker (`sendQuote`). */\nexport interface PricedRfqLeg extends RfqLeg {\n price: DecimalLike;\n}\n\n/** Maker quote against an open RFQ — see `sendQuote` / `sendQuoteDebug`. */\nexport interface SendQuoteParams {\n /** The maker's subaccount. */\n subaccountId: number;\n rfqId: string;\n direction: Direction;\n legs: PricedRfqLeg[];\n /** Worst execution fee the maker accepts, in USD. */\n maxFee: DecimalLike;\n mmp?: boolean;\n label?: string;\n nonce?: string;\n signatureExpirySec?: number;\n}\n\n/** Taker execution of a maker quote — see `executeQuote` / `executeQuoteDebug`. */\nexport interface ExecuteQuoteParams {\n /** The taker's subaccount. */\n subaccountId: number;\n quote: Pick<QuoteResultPublic, 'rfq_id' | 'quote_id' | 'direction' | 'legs'>;\n /** Worst execution fee the taker accepts, in USD. */\n maxFee: DecimalLike;\n /** Reject the fill if the quote is no longer the best available price. */\n enableTakerProtection?: boolean;\n label?: string;\n nonce?: string;\n signatureExpirySec?: number;\n}\n\n/** A leg with resolved asset identity and e18-normalized numbers — the single source for both the signed bytes and the wire legs. */\ninterface ResolvedLeg {\n instrumentName: string;\n assetAddress: string;\n subId: string;\n price: bigint;\n amount: bigint;\n direction: Direction;\n}\n\n/**\n * The API rejects quote signatures expiring before the RFQ's full 600s\n * quoting window + 60s buffer; 700s covers a quote sent at RFQ creation.\n */\nconst DEFAULT_QUOTE_EXPIRY_SEC = 700;\n\n/**\n * RFQ trading: takers request quotes on multi-leg packages, makers answer\n * with signed quotes, and the taker executes one — the only two signed\n * operations are `sendQuote` (maker) and `executeQuote` (taker), both\n * against the RFQ module. Requesting, polling and cancelling are auth-only.\n */\nexport class RfqApi {\n /** Asset address/subId per instrument name are immutable — cache the lookups. */\n private readonly instruments = new Map<string, Promise<InstrumentPublicResponse>>();\n\n constructor(private readonly ctx: ClientContext) {}\n\n // ── Taker ──────────────────────────────────────────────────────────\n\n /** Requests quotes for a package of legs. Unsigned — only the eventual execute is. */\n async sendRfq(params: {\n subaccountId: number;\n legs: RfqLeg[];\n label?: string;\n /** Reject fills costing the taker more than this (buy-side cap). */\n maxTotalCost?: DecimalLike;\n /** Reject fills earning the taker less than this (sell-side floor). */\n minTotalCost?: DecimalLike;\n /** Restrict quoting to these maker wallets. */\n counterparties?: string[];\n partialFillStep?: DecimalLike;\n }): Promise<RFQPrivateWireResponse> {\n return this.ctx.send('private/send_rfq', {\n subaccount_id: params.subaccountId,\n legs: unpricedWireLegs(params.legs),\n label: params.label,\n max_total_cost: params.maxTotalCost === undefined ? undefined : wireDecimal(params.maxTotalCost),\n min_total_cost: params.minTotalCost === undefined ? undefined : wireDecimal(params.minTotalCost),\n counterparties: params.counterparties?.map((wallet) => getAddress(wallet)),\n partial_fill_step: params.partialFillStep === undefined ? undefined : wireDecimal(params.partialFillStep),\n });\n }\n\n /** Polls quotes received for the taker's RFQs (e.g. `status: 'open'`). */\n async pollQuotes(params: {\n subaccountId: number;\n rfqId?: string;\n quoteId?: string;\n status?: string;\n fromTimestamp?: number;\n toTimestamp?: number;\n page?: number;\n pageSize?: number;\n }): Promise<QuotePollWireResponse> {\n return this.ctx.send('private/poll_quotes', {\n subaccount_id: params.subaccountId,\n rfq_id: params.rfqId,\n quote_id: params.quoteId,\n status: params.status,\n from_timestamp: params.fromTimestamp,\n to_timestamp: params.toTimestamp,\n page: params.page,\n page_size: params.pageSize,\n });\n }\n\n /** The exchange's pick of the best open quote for an RFQ, with margin/cost estimates. */\n async getBestQuote(params: {\n subaccountId: number;\n /** The open RFQ whose quotes should be evaluated. */\n rfqId: string;\n /** The direction the taker wants to trade. */\n direction: Direction;\n legs: RfqLeg[];\n }): Promise<RfqGetBestQuoteWireResponse> {\n return this.ctx.send('private/rfq_get_best_quote', {\n subaccount_id: params.subaccountId,\n rfq_id: params.rfqId,\n direction: params.direction,\n legs: unpricedWireLegs(params.legs),\n } as never);\n }\n\n /**\n * Executes a maker quote (from `pollQuotes` / `getBestQuote`). The taker\n * trades opposite the quote's direction and signs a commitment to the\n * maker's exact leg bundle, so legs and prices come from the quote itself.\n */\n async executeQuote(params: ExecuteQuoteParams): Promise<QuoteExecuteWireResponse> {\n return this.ctx.send('private/execute_quote', await this.buildExecutePayload(params));\n }\n\n /**\n * Debug helper: signs the execute exactly like `executeQuote` but submits it\n * to `public/execute_quote_debug`, returning the server-computed encoded data\n * and hashes instead of filling. Use it to verify your client-side signing.\n */\n async executeQuoteDebug(params: ExecuteQuoteParams) {\n return this.ctx.send('public/execute_quote_debug', (await this.buildExecutePayload(params)) as never);\n }\n\n private async buildExecutePayload(params: ExecuteQuoteParams) {\n const direction: Direction = params.quote.direction === 'buy' ? 'sell' : 'buy';\n const maxFee = toE18(params.maxFee);\n const legs = await this.resolveLegs(\n params.quote.legs.map((leg) => ({\n instrumentName: leg.instrument_name,\n amount: leg.amount,\n price: leg.price,\n direction: leg.direction,\n })),\n );\n const nonce = params.nonce ?? randomNonce();\n const expirySec = params.signatureExpirySec ?? expiresIn(DEFAULT_QUOTE_EXPIRY_SEC);\n const signed = this.signRfqAction(\n params.subaccountId,\n encodeRfqExecute({ maxFee, direction, legs }),\n nonce,\n expirySec,\n );\n return {\n subaccount_id: params.subaccountId,\n rfq_id: params.quote.rfq_id,\n quote_id: params.quote.quote_id,\n direction,\n legs: legs.map(pricedWireLeg),\n max_fee: formatUnits(maxFee, 18),\n nonce,\n signer: signed.signer,\n signature: signed.signature,\n signature_expiry_sec: expirySec,\n enable_taker_protection: params.enableTakerProtection,\n label: params.label,\n };\n }\n\n async cancelRfq(params: { subaccountId: number; rfqId: string }): Promise<CancelRfqResponse> {\n return this.ctx.send('private/cancel_rfq', {\n subaccount_id: params.subaccountId,\n rfq_id: params.rfqId,\n });\n }\n\n // ── Maker ──────────────────────────────────────────────────────────\n\n /** Polls RFQs open for quoting (e.g. `status: 'open'`). */\n async pollRfqs(params: {\n subaccountId: number;\n rfqId?: string;\n status?: string;\n fromTimestamp?: number;\n toTimestamp?: number;\n page?: number;\n pageSize?: number;\n }): Promise<RFQPollWireResponse> {\n return this.ctx.send('private/poll_rfqs', {\n subaccount_id: params.subaccountId,\n rfq_id: params.rfqId,\n status: params.status,\n from_timestamp: params.fromTimestamp,\n to_timestamp: params.toTimestamp,\n page: params.page,\n page_size: params.pageSize,\n });\n }\n\n /**\n * Signs and sends a quote against an open RFQ. Legs must match the RFQ's\n * legs with prices added; `direction: 'sell'` quotes the package to a\n * buying taker.\n */\n async sendQuote(params: SendQuoteParams): Promise<QuotePrivateWireResponse> {\n return this.ctx.send('private/send_quote', await this.buildSendQuotePayload(params));\n }\n\n /**\n * Debug helper: signs the quote exactly like `sendQuote` but submits it to\n * `public/send_quote_debug`, returning the server-computed encoded data and\n * hashes instead of posting. Use it to verify your client-side signing.\n */\n async sendQuoteDebug(params: SendQuoteParams) {\n return this.ctx.send('public/send_quote_debug', (await this.buildSendQuotePayload(params)) as never);\n }\n\n private async buildSendQuotePayload(params: SendQuoteParams) {\n const maxFee = toE18(params.maxFee);\n const legs = await this.resolveLegs(params.legs);\n const nonce = params.nonce ?? randomNonce();\n const expirySec = params.signatureExpirySec ?? expiresIn(DEFAULT_QUOTE_EXPIRY_SEC);\n const signed = this.signRfqAction(\n params.subaccountId,\n encodeRfqQuote({ maxFee, direction: params.direction, legs }),\n nonce,\n expirySec,\n );\n return {\n subaccount_id: params.subaccountId,\n rfq_id: params.rfqId,\n direction: params.direction,\n legs: legs.map(pricedWireLeg),\n max_fee: formatUnits(maxFee, 18),\n // The generated stub types nonce as number; the wire value is the decimal-string nanosecond nonce (> 2^53).\n nonce: nonce as unknown as number,\n signer: signed.signer,\n signature: signed.signature,\n signature_expiry_sec: expirySec,\n mmp: params.mmp,\n label: params.label,\n };\n }\n\n async cancelQuote(params: {\n subaccountId: number;\n quoteId: string;\n rfqId?: string;\n }): Promise<QuotePrivateWireResponse> {\n return this.ctx.send('private/cancel_quote', {\n subaccount_id: params.subaccountId,\n quote_id: params.quoteId,\n rfq_id: params.rfqId,\n });\n }\n\n /** Cancels all the subaccount's open quotes, optionally scoped to one RFQ. */\n async cancelBatchQuotes(params: { subaccountId: number; rfqId?: string }): Promise<CancelBatchResult> {\n return this.ctx.send('private/cancel_batch_quotes', {\n subaccount_id: params.subaccountId,\n rfq_id: params.rfqId,\n });\n }\n\n /** Cancels all the subaccount's open RFQs, optionally scoped to one RFQ id. */\n async cancelBatchRfqs(params: { subaccountId: number; rfqId?: string }) {\n return this.ctx.send('private/cancel_batch_rfqs', {\n subaccount_id: params.subaccountId,\n rfq_id: params.rfqId,\n } as never);\n }\n\n /** Paginated quote history/read for the subaccount, filterable by rfq/quote/status. */\n async getQuotes(params: {\n subaccountId: number;\n rfqId?: string;\n quoteId?: string;\n status?: string;\n page?: number;\n pageSize?: number;\n fromTimestamp?: number;\n toTimestamp?: number;\n }) {\n return this.ctx.send('private/get_quotes', {\n subaccount_id: params.subaccountId,\n rfq_id: params.rfqId,\n quote_id: params.quoteId,\n status: params.status,\n page: params.page,\n page_size: params.pageSize,\n from_timestamp: params.fromTimestamp,\n to_timestamp: params.toTimestamp,\n } as never);\n }\n\n /**\n * Atomically cancels an existing quote and signs+sends a replacement on the\n * same RFQ. Legs/price/maxFee sign the new quote exactly like `sendQuote`;\n * identify the quote to cancel by `quoteIdToCancel` or `nonceToCancel`.\n */\n async replaceQuote(params: {\n subaccountId: number;\n rfqId: string;\n direction: Direction;\n legs: PricedRfqLeg[];\n maxFee: DecimalLike;\n quoteIdToCancel?: string;\n nonceToCancel?: string;\n mmp?: boolean;\n label?: string;\n nonce?: string;\n signatureExpirySec?: number;\n }) {\n const maxFee = toE18(params.maxFee);\n const legs = await this.resolveLegs(params.legs);\n const nonce = params.nonce ?? randomNonce();\n const expirySec = params.signatureExpirySec ?? expiresIn(DEFAULT_QUOTE_EXPIRY_SEC);\n const signed = this.signRfqAction(\n params.subaccountId,\n encodeRfqQuote({ maxFee, direction: params.direction, legs }),\n nonce,\n expirySec,\n );\n return this.ctx.send('private/replace_quote', {\n subaccount_id: params.subaccountId,\n rfq_id: params.rfqId,\n direction: params.direction,\n legs: legs.map(pricedWireLeg),\n max_fee: formatUnits(maxFee, 18),\n nonce: nonce as unknown as number,\n signer: signed.signer,\n signature: signed.signature,\n signature_expiry_sec: expirySec,\n quote_id_to_cancel: params.quoteIdToCancel,\n nonce_to_cancel: params.nonceToCancel as unknown as number,\n mmp: params.mmp,\n label: params.label,\n } as never);\n }\n\n // ── Shared signing plumbing ────────────────────────────────────────\n\n /** Attaches each leg's protocol asset address + sub id and sorts into the canonical signed order. */\n private async resolveLegs(legs: PricedRfqLeg[]): Promise<ResolvedLeg[]> {\n return sortRfqLegs(\n await Promise.all(\n legs.map(async (leg) => {\n const instrument = await this.instrument(leg.instrumentName);\n return {\n instrumentName: leg.instrumentName,\n assetAddress: instrument.base_asset_address,\n subId: instrument.base_asset_sub_id,\n price: toE18(leg.price),\n amount: toE18(leg.amount),\n direction: leg.direction,\n };\n }),\n ),\n );\n }\n\n private instrument(name: string): Promise<InstrumentPublicResponse> {\n let lookup = this.instruments.get(name);\n if (!lookup) {\n lookup = this.ctx.send('public/get_instrument', { instrument_name: name });\n lookup.catch(() => this.instruments.delete(name)); // never cache failures\n this.instruments.set(name, lookup);\n }\n return lookup;\n }\n\n private signRfqAction(\n subaccountId: number,\n data: string,\n nonce: string,\n expirySec: number,\n ): { signer: string; signature: string } {\n const { ownerAddress, signer } = this.ctx.credentials();\n const action = new SignedAction(\n {\n subaccountId,\n nonce,\n module: this.ctx.network.modules.rfq,\n data,\n expirySec,\n owner: ownerAddress,\n signer: signer.address,\n },\n domainSeparator(this.ctx.network),\n ).sign(signer);\n // sign() above guarantees the signature is set\n return { signer: signer.address, signature: action.signature! };\n }\n}\n\n/**\n * Wire decimals are decimal strings in human units; round-tripping through\n * e18 both validates the input and normalizes bigints back down.\n */\nfunction wireDecimal(value: DecimalLike): string {\n return formatUnits(toE18(value), 18);\n}\n\n/** Unpriced wire legs (sendRfq / getBestQuote), in the canonical sorted order. */\nfunction unpricedWireLegs(legs: RfqLeg[]): Array<{ amount: string; direction: Direction; instrument_name: string }> {\n return sortRfqLegs(legs).map((leg) => {\n const amount = toE18(leg.amount);\n if (amount <= 0n) {\n throw new Error(`rfq leg amount must be positive (direction carries the sign): ${leg.instrumentName}`);\n }\n return { amount: formatUnits(amount, 18), direction: leg.direction, instrument_name: leg.instrumentName };\n });\n}\n\n/** Wire decimals are formatted from the signed e18 words so the exchange re-derives the exact signed bytes. */\nfunction pricedWireLeg(leg: ResolvedLeg): {\n amount: string;\n direction: Direction;\n instrument_name: string;\n price: string;\n} {\n return {\n amount: formatUnits(leg.amount, 18),\n direction: leg.direction,\n instrument_name: leg.instrumentName,\n price: formatUnits(leg.price, 18),\n };\n}\n","import { getAddress, type BaseWallet } from 'ethers';\nimport { OffchainScope, ProtocolScopeWireString, type ProtocolScopeCode } from '../auth/scopes';\nimport { encodeCreateSessionKeyActionData } from '../codecs/sessionKey';\nimport { SignedAction } from '../signing/action';\nimport { domainSeparator } from '../signing/eip712';\nimport { expiresIn, randomNonce } from '../signing/encoding';\nimport type { PrivateCreateSessionKeyEdgeRPCResponse, SessionKeyResponse } from '../types';\nimport type { ClientContext } from './context';\n\nexport interface CreateSessionKeyParams {\n /** The key being authorized: an address, or an ethers wallet (e.g. `Wallet.createRandom()`). */\n publicSessionKey: string | BaseWallet;\n /**\n * The KEY's lifetime as a unix-seconds timestamp, committed in the signed\n * data — not to be confused with `signatureExpirySec`, which only bounds\n * how long this registration request itself stays valid.\n */\n expirySec: number;\n /**\n * Protocol scopes granted (numeric codes; the wire strings are derived).\n * Defaults to NONE — the key can then only authenticate and use its\n * offchain scopes. Grant `ProtocolScopeCode.Admin` deliberately, never\n * by default.\n */\n protocolScopes?: ProtocolScopeCode[];\n /** Off-chain scopes, e.g. `[OffchainScope.AccountInfo]`. Defaults to account_info. */\n offchainScopes?: OffchainScope[];\n /** Subaccounts the key may act on. Omit for ALL current and future subaccounts. */\n subaccountIds?: number[];\n label?: string;\n /** Source IPs the key may be used from; omit for no restriction. */\n ipWhitelist?: string[];\n /** Envelope expiry of the registration signature. Defaults to 10 minutes. */\n signatureExpirySec?: number;\n nonce?: string;\n}\n\nexport interface EditSessionKeyParams {\n publicSessionKey: string;\n /** Omitted fields are left unchanged (the endpoint is a patch). */\n label?: string;\n /** Requires the request to be authorized by the owner or an admin-scoped key. */\n ipWhitelist?: string[];\n /** Requires the request to be authorized by the owner or an admin-scoped key. */\n offchainScopes?: OffchainScope[];\n}\n\n/**\n * Session-key registration and management. Keys are wallet-level: actions\n * are signed on subaccount 0 and the granted subaccount list lives inside\n * the signed data, not the envelope.\n */\nexport class SessionKeysApi {\n constructor(private readonly ctx: ClientContext) {}\n\n /**\n * Registers a scoped session key. The action must be authorized by the\n * account owner or by a registered session key holding the\n * `create_session_key` scope — a child key must then be a subset of its\n * creator (scopes, subaccounts, and expiry no later than the creator's).\n * Signs with the client's action signer, so a client configured with an\n * unscoped session key will be rejected server-side.\n */\n async create(params: CreateSessionKeyParams): Promise<PrivateCreateSessionKeyEdgeRPCResponse> {\n const publicSessionKey = getAddress(\n typeof params.publicSessionKey === 'string' ? params.publicSessionKey : params.publicSessionKey.address,\n );\n const scopes = params.protocolScopes ?? [];\n const offchainScopes = params.offchainScopes ?? [OffchainScope.AccountInfo];\n const { ownerAddress, signer } = this.ctx.credentials();\n const action = new SignedAction(\n {\n subaccountId: 0,\n nonce: params.nonce ?? randomNonce(),\n module: this.ctx.network.modules.createSessionKey,\n data: encodeCreateSessionKeyActionData({\n sessionKey: publicSessionKey,\n expirySec: params.expirySec,\n scopes,\n subaccountIds: params.subaccountIds ?? [],\n }),\n expirySec: params.signatureExpirySec ?? expiresIn(600),\n owner: ownerAddress,\n signer: signer.address,\n },\n domainSeparator(this.ctx.network),\n ).sign(signer);\n\n return this.ctx.send('private/create_session_key', {\n wallet: ownerAddress,\n public_session_key: publicSessionKey,\n expiry_sec: params.expirySec,\n subaccount_ids: params.subaccountIds ?? null,\n nonce: action.fields.nonce,\n signer: action.fields.signer,\n // sign() above guarantees the signature is set\n signature: action.signature!,\n signature_expiry_sec: action.fields.expirySec,\n protocol_scopes: scopes.map((code) => ProtocolScopeWireString[code]),\n offchain_scopes: offchainScopes,\n label: params.label,\n ip_whitelist: params.ipWhitelist,\n });\n }\n\n /** All registered session keys of the owner wallet. */\n async list(): Promise<SessionKeyResponse[]> {\n const result = await this.ctx.send('private/session_keys', {\n wallet: this.ctx.credentials().ownerAddress,\n });\n return result.public_session_keys;\n }\n\n /**\n * Patches a key's OFF-CHAIN attributes. Protocol scopes, subaccounts,\n * and expiry are committed in the signed registration and cannot be\n * edited — register a replacement key instead. The public API has no\n * revoke endpoint: a key stops working at its signed `expiry_sec`.\n */\n async edit(params: EditSessionKeyParams): Promise<SessionKeyResponse> {\n return this.ctx.send('private/edit_session_key', {\n wallet: this.ctx.credentials().ownerAddress,\n public_session_key: getAddress(params.publicSessionKey),\n label: params.label,\n ip_whitelist: params.ipWhitelist,\n offchain_scopes: params.offchainScopes,\n });\n }\n}\n","/**\n * Session-key scopes.\n *\n * Protocol scopes exist in two encodings that must stay in sync: the\n * numeric byte codes below are packed into the SIGNED create-session-key\n * action data (codecs/sessionKey.ts), while the colon-delimited wire\n * strings travel in RPC params.\n *\n * Grants form an Allows-hierarchy checked server-side: `admin` subsumes\n * every scope, and each `:all` subsumes its branch — `trade:all` covers\n * both venues, `trade:orderbook:all` / `trade:rfq:all` cover their\n * per-asset variants, `transfer:all` and `vault:all` likewise. A key's\n * grant set allows a request iff any single grant does.\n */\nexport const ProtocolScopeCode = {\n /** Superuser grant — allows every protocol action. Grant deliberately. */\n Admin: 0,\n /** Withdrawals, restricted to the account's whitelisted recipients. */\n Withdraw: 1,\n\n TradeAll: 2,\n TradeOrderbookAll: 3,\n TradeOrderbookSpot: 4,\n TradeOrderbookPerp: 5,\n TradeOrderbookOption: 6,\n TradeRfqAll: 7,\n TradeRfqSpot: 8,\n TradeRfqPerp: 9,\n TradeRfqOption: 10,\n\n TransferAll: 11,\n /** Between subaccounts of the same owner (spot, and positions via RFQ). */\n TransferExistingSubaccount: 12,\n /** Spot transfer that creates a new subaccount under the owner. */\n TransferNewSubaccount: 13,\n /** Spot transfer to a whitelisted different-owner wallet. */\n TransferDifferentOwnerSubaccount: 14,\n\n /** Create child session keys; the child must be a subset of this key. */\n CreateSessionKey: 15,\n Liquidate: 16,\n\n VaultAll: 17,\n VaultCuratorCreate: 18,\n VaultCuratorMintAndBurn: 19,\n VaultUserDeposit: 20,\n VaultUserWithdraw: 21,\n VaultUserCancel: 22,\n} as const;\n\nexport type ProtocolScopeCode = (typeof ProtocolScopeCode)[keyof typeof ProtocolScopeCode];\n\n/** Wire-string form for each numeric protocol scope code. */\nexport const ProtocolScopeWireString = {\n [ProtocolScopeCode.Admin]: 'admin',\n [ProtocolScopeCode.Withdraw]: 'withdraw',\n [ProtocolScopeCode.TradeAll]: 'trade:all',\n [ProtocolScopeCode.TradeOrderbookAll]: 'trade:orderbook:all',\n [ProtocolScopeCode.TradeOrderbookSpot]: 'trade:orderbook:spot',\n [ProtocolScopeCode.TradeOrderbookPerp]: 'trade:orderbook:perp',\n [ProtocolScopeCode.TradeOrderbookOption]: 'trade:orderbook:option',\n [ProtocolScopeCode.TradeRfqAll]: 'trade:rfq:all',\n [ProtocolScopeCode.TradeRfqSpot]: 'trade:rfq:spot',\n [ProtocolScopeCode.TradeRfqPerp]: 'trade:rfq:perp',\n [ProtocolScopeCode.TradeRfqOption]: 'trade:rfq:option',\n [ProtocolScopeCode.TransferAll]: 'transfer:all',\n [ProtocolScopeCode.TransferExistingSubaccount]: 'transfer:existing_subaccount',\n [ProtocolScopeCode.TransferNewSubaccount]: 'transfer:new_subaccount',\n [ProtocolScopeCode.TransferDifferentOwnerSubaccount]: 'transfer:different_owner_subaccount',\n [ProtocolScopeCode.CreateSessionKey]: 'create_session_key',\n [ProtocolScopeCode.Liquidate]: 'liquidate',\n [ProtocolScopeCode.VaultAll]: 'vault:all',\n [ProtocolScopeCode.VaultCuratorCreate]: 'vault:curator_create',\n [ProtocolScopeCode.VaultCuratorMintAndBurn]: 'vault:curator_mint_and_burn',\n [ProtocolScopeCode.VaultUserDeposit]: 'vault:user_deposit',\n [ProtocolScopeCode.VaultUserWithdraw]: 'vault:user_withdraw',\n [ProtocolScopeCode.VaultUserCancel]: 'vault:user_cancel',\n} as const satisfies Record<ProtocolScopeCode, string>;\n\nexport type ProtocolScope = (typeof ProtocolScopeWireString)[ProtocolScopeCode];\n\n/**\n * Off-chain scopes validated by the server only (never signed into the\n * action data). Exact-match semantics — no hierarchy — but a key holding\n * any protocol scope bypasses them.\n */\nexport const OffchainScope = {\n AccountInfo: 'account_info',\n DeleteSessionKey: 'delete_session_key',\n} as const;\n\nexport type OffchainScope = (typeof OffchainScope)[keyof typeof OffchainScope];\n","import { concat, getAddress, toBeHex, zeroPadValue } from 'ethers';\nimport type { ProtocolScopeCode } from '../auth/scopes';\n\nexport interface CreateSessionKeyData {\n /** Address of the key being authorized. */\n sessionKey: string;\n /**\n * The KEY's lifetime as a unix-seconds timestamp — distinct from the\n * envelope's signature expiry. The key stops working once `expirySec <= now`;\n * pass 0 to deactivate an existing key of this address.\n */\n expirySec: number;\n /**\n * Scope codes granted to the key (auth/scopes.ts). Typed as `number` at\n * this low level so raw codes pass through — the typed\n * `ProtocolScopeCode` enum guides callers, and the server is the\n * authority on which codes are valid.\n */\n scopes: readonly (ProtocolScopeCode | number)[];\n /** Subaccounts the key may act on; empty = ALL current and future subaccounts. */\n subaccountIds: readonly (number | bigint)[];\n}\n\n/**\n * Encodes the create-session-key action data.\n *\n * Hand-packed 32-byte words — NOT standard dynamic ABI (no offset or\n * length-prefix head): `[session_key][expiry_sec][S][A][scope codes…]\n * [subaccount ids…]`, every value right-aligned in its word.\n */\nexport function encodeCreateSessionKeyActionData(data: CreateSessionKeyData): string {\n if (!Number.isInteger(data.expirySec) || data.expirySec < 0) {\n throw new Error(`session key expirySec must be a non-negative unix-seconds integer, got ${data.expirySec}`);\n }\n return concat([\n zeroPadValue(getAddress(data.sessionKey), 32),\n uintWord(data.expirySec),\n uintWord(data.scopes.length),\n uintWord(data.subaccountIds.length),\n ...data.scopes.map((code) => uintWord(code)),\n ...data.subaccountIds.map((id) => uintWord(id)),\n ]);\n}\n\nfunction uintWord(value: number | bigint): string {\n const valid = typeof value === 'bigint' ? value >= 0n : Number.isSafeInteger(value) && value >= 0;\n if (!valid) throw new Error(`expected a non-negative integer, got ${value}`);\n return zeroPadValue(toBeHex(value), 32);\n}\n","import { formatUnits, getAddress } from 'ethers';\nimport { encodeExternalTransfer } from '../codecs/externalTransfer';\nimport { encodeTransfer } from '../codecs/transfer';\nimport { encodeUpdateWhitelistedRecipients } from '../codecs/whitelistedRecipients';\nimport { SignedAction } from '../signing/action';\nimport { DEFAULT_SIGNATURE_EXPIRY_SEC, expiresIn, randomNonce, toE18, type DecimalLike } from '../signing/encoding';\nimport { domainSeparator } from '../signing/eip712';\nimport type {\n PrivateTransferSpotEdgeRpcResponse,\n PrivateTransferSpotExternalEdgeRpcResponse,\n UpdateWhitelistedRecipientsEdgeRpcResponse,\n} from '../types';\nimport type { ClientContext } from './context';\n\n/**\n * A spot asset as the exchange resolves it: `name` is what the wire takes\n * as `asset_name`, `address` is what signatures commit to, `decimals` is\n * the underlying ERC-20 scale withdrawal amounts are signed at.\n */\nexport interface SpotAssetInfo {\n name: string;\n address: string;\n decimals: number;\n}\n\n/**\n * Resolves a currency name (e.g. \"USDC\") or protocol asset address to the\n * deposit-enabled spot asset. The exchange reconstructs signed transfer and\n * withdrawal payloads from `asset_name` using this asset's address, so\n * signing any other address of the currency (e.g. a \"-NL\" variant without\n * ERC-20 metadata) can never verify.\n */\nexport async function resolveSpotAsset(ctx: ClientContext, asset: string): Promise<SpotAssetInfo> {\n const wanted = asset.trim();\n const wantedAddress = wanted.startsWith('0x') ? getAddress(wanted) : undefined;\n const currencies = await ctx.send('public/get_all_currencies', null);\n for (const currency of currencies) {\n // ERC-20 metadata is only reported for assets with a deposit (spot) config.\n const enabled = currency.spot.filter((s) => s.erc20.underlying_erc20 != null || s.erc20.decimals > 0);\n let match;\n if (wantedAddress) {\n match = enabled.find((s) => getAddress(s.address) === wantedAddress);\n } else if (currency.currency.toUpperCase() === wanted.toUpperCase()) {\n if (enabled.length > 1) {\n throw new Error(\n `currency ${currency.currency} has multiple deposit-enabled spot assets — pass the protocol asset address`,\n );\n }\n match = enabled[0];\n if (!match) throw new Error(`currency ${currency.currency} has no deposit-enabled spot asset`);\n }\n if (match) {\n return { name: currency.currency, address: getAddress(match.address), decimals: match.erc20.decimals };\n }\n }\n throw new Error(\n `unknown asset ${asset} — expected a currency name (e.g. \"USDC\") or the address of a deposit-enabled spot asset`,\n );\n}\n\n/**\n * Formats a wire amount: the JSON wire carries human-unit decimal strings;\n * e18/native scaling exists only inside signed action data. Already-scaled\n * bigint inputs (see `DecimalLike`) are converted back at `scale`.\n */\nexport function decimalString(value: DecimalLike, scale = 18): string {\n return typeof value === 'bigint' ? formatUnits(value, scale) : String(value).trim();\n}\n\nexport interface InternalSpotTransferParams {\n /** Sender subaccount. */\n subaccountId: number;\n /** Existing destination subaccount; omit (or 0) when creating one via `newSubaccountManager`. */\n toSubaccountId?: number;\n /** Set to a manager id to create a new subaccount as the destination instead of `toSubaccountId`. */\n newSubaccountManager?: number;\n /** Currency name (e.g. \"USDC\") or protocol spot-asset address. */\n asset: string;\n subId?: number;\n amount: DecimalLike;\n /**\n * Fee cap in USD, default \"0\": transfers between existing subaccounts\n * are free. Creating a subaccount charges a transfer fee (1 USD\n * standard), so raise the cap when `newSubaccountManager` is set.\n */\n maxFeeUsd?: DecimalLike;\n nonce?: string;\n signatureExpirySec?: number;\n}\n\nexport interface ExternalSpotTransferParams {\n /** Sender subaccount. */\n subaccountId: number;\n /** Destination owner wallet. Must be on the sender's whitelist of recipients. */\n recipient: string;\n /** Recipient's existing subaccount; omit (or 0) to create one for them via `newSubaccountManager`. */\n toSubaccountId?: number;\n /** Manager id for the recipient's new subaccount when `toSubaccountId` is omitted. */\n newSubaccountManager?: number;\n /** Currency name (e.g. \"USDC\") or protocol spot-asset address. */\n asset: string;\n subId?: number;\n amount: DecimalLike;\n /**\n * Fee cap in USD. Required: external transfers always charge a transfer\n * fee (1 USD standard) plus, when a subaccount is created, the\n * protocol's subaccount-creation fee on top.\n */\n maxFeeUsd: DecimalLike;\n nonce?: string;\n signatureExpirySec?: number;\n}\n\n/**\n * Spot transfers between subaccounts and to other wallets. Position\n * transfers are not covered here: `private/transfer_positions` takes a\n * maker and a taker RFQ-style signed quote, i.e. two signatures over the\n * RFQ leg encoding.\n */\nexport class SpotTransfersApi {\n constructor(private readonly ctx: ClientContext) {}\n\n /**\n * Moves a spot balance between the owner's OWN subaccounts\n * (`private/transfer_spot`). Destination is either an existing\n * `toSubaccountId` or, when `newSubaccountManager` is set, a freshly\n * created sender-owned subaccount under that manager. For a transfer\n * to another wallet use `transferExternal`.\n */\n async transferInternal(params: InternalSpotTransferParams): Promise<PrivateTransferSpotEdgeRpcResponse> {\n const toSubaccountId = params.toSubaccountId ?? 0;\n const newSubaccountManager = params.newSubaccountManager ?? 0;\n if (toSubaccountId === 0 && newSubaccountManager === 0) {\n throw new Error('specify toSubaccountId or, to create a new subaccount, newSubaccountManager');\n }\n const subId = params.subId ?? 0;\n const maxFeeUsd = params.maxFeeUsd ?? '0';\n // Creating a subaccount charges a fee; a zero cap is ACKed then rejected\n // asynchronously by the exchange, so fail loudly up front.\n if (newSubaccountManager !== 0 && toE18(maxFeeUsd) === 0n) {\n throw new Error(\n 'creating a subaccount charges a transfer fee — set maxFeeUsd (>= 1) when newSubaccountManager is used',\n );\n }\n const asset = await resolveSpotAsset(this.ctx, params.asset);\n const action = this.signAction(\n params.subaccountId,\n this.ctx.network.modules.transfer,\n encodeTransfer({\n toSubaccountId,\n newSubaccountManager,\n asset: asset.address,\n subId,\n amount: params.amount,\n maxFeeUsd,\n }),\n params,\n );\n return this.ctx.send('private/transfer_spot', {\n subaccount_id: params.subaccountId,\n to_subaccount_id: toSubaccountId,\n new_subaccount_manager: newSubaccountManager,\n asset_name: asset.name,\n sub_id: subId,\n amount: decimalString(params.amount),\n max_fee_usd: decimalString(maxFeeUsd),\n // Nonces are UTC-nanosecond decimal strings beyond 2^53; the API accepts string-or-number despite the generated `number`.\n nonce: action.fields.nonce as unknown as number,\n signer: action.fields.signer,\n signature: action.signature!,\n signature_expiry_sec: action.fields.expirySec,\n });\n }\n\n /**\n * Adds/removes recipient wallets on the owner's external-transfer\n * whitelist (`private/update_whitelisted_recipients`). The resulting\n * list is `(current ∪ add) \\ remove`. Required before `transferExternal`\n * can send to a given wallet.\n */\n async updateWhitelistedRecipients(params: {\n add?: string[];\n remove?: string[];\n nonce?: string;\n signatureExpirySec?: number;\n }): Promise<UpdateWhitelistedRecipientsEdgeRpcResponse> {\n const add = params.add ?? [];\n const remove = params.remove ?? [];\n if (add.length === 0 && remove.length === 0) {\n throw new Error('updateWhitelistedRecipients needs at least one address to add or remove');\n }\n const { ownerAddress } = this.ctx.credentials();\n // The whitelist is a wallet-level list, so the action is signed on subaccount 0.\n const action = this.signAction(\n 0,\n this.ctx.network.modules.whitelistedRecipient,\n encodeUpdateWhitelistedRecipients({ add, remove }),\n params,\n );\n return this.ctx.send('private/update_whitelisted_recipients', {\n wallet: ownerAddress,\n add: add.map((a) => getAddress(a)),\n remove: remove.map((a) => getAddress(a)),\n // Nonces are UTC-nanosecond decimal strings beyond 2^53; the API accepts string-or-number despite the generated `number`.\n nonce: action.fields.nonce as unknown as number,\n signer: action.fields.signer,\n signature: action.signature!,\n signature_expiry_sec: action.fields.expirySec,\n });\n }\n\n /**\n * Moves a spot balance to another owner's wallet\n * (`private/transfer_spot_external`). The recipient must already be on\n * the sender's whitelist — call `updateWhitelistedRecipients` first;\n * otherwise the exchange rejects with RPC error 11033 \"Transfer\n * recipient not whitelisted\".\n */\n async transferExternal(params: ExternalSpotTransferParams): Promise<PrivateTransferSpotExternalEdgeRpcResponse> {\n const recipient = getAddress(params.recipient);\n const toSubaccountId = params.toSubaccountId ?? 0;\n const newSubaccountManager = params.newSubaccountManager ?? 0;\n if (toSubaccountId === 0 && newSubaccountManager === 0) {\n throw new Error(\"specify the recipient's toSubaccountId or, to create one for them, newSubaccountManager\");\n }\n const subId = params.subId ?? 0;\n const asset = await resolveSpotAsset(this.ctx, params.asset);\n const action = this.signAction(\n params.subaccountId,\n this.ctx.network.modules.externalTransfer,\n encodeExternalTransfer({\n toSubaccountId,\n newSubaccountManager,\n asset: asset.address,\n subId,\n amount: params.amount,\n maxFeeUsd: params.maxFeeUsd,\n recipient,\n }),\n params,\n );\n return this.ctx.send('private/transfer_spot_external', {\n subaccount_id: params.subaccountId,\n recipient_address: recipient,\n to_subaccount_id: toSubaccountId,\n new_subaccount_manager: newSubaccountManager,\n asset_name: asset.name,\n sub_id: subId,\n amount: decimalString(params.amount),\n max_fee_usd: decimalString(params.maxFeeUsd),\n // Nonces are UTC-nanosecond decimal strings beyond 2^53; the API accepts string-or-number despite the generated `number`.\n nonce: action.fields.nonce as unknown as number,\n signer: action.fields.signer,\n signature: action.signature!,\n signature_expiry_sec: action.fields.expirySec,\n });\n }\n\n private signAction(\n subaccountId: number,\n module: string,\n data: string,\n overrides: { nonce?: string; signatureExpirySec?: number },\n ): SignedAction {\n const { ownerAddress, signer } = this.ctx.credentials();\n return new SignedAction(\n {\n subaccountId,\n nonce: overrides.nonce ?? randomNonce(),\n module,\n data,\n expirySec: overrides.signatureExpirySec ?? expiresIn(DEFAULT_SIGNATURE_EXPIRY_SEC),\n owner: ownerAddress,\n signer: signer.address,\n },\n domainSeparator(this.ctx.network),\n ).sign(signer);\n }\n}\n","import { concat, getAddress, zeroPadValue } from 'ethers';\nimport { encodeTransfer, type TransferFields } from './transfer';\n\n/**\n * Spot transfer to another owner's wallet, verified by the external\n * transfer module: the six transfer words plus a seventh holding the\n * recipient wallet.\n */\nexport interface ExternalTransferFields extends TransferFields {\n /**\n * Destination owner wallet. `toSubaccountId` must be one of its existing\n * subaccounts, or 0 to create one for it under `newSubaccountManager`.\n */\n recipient: string;\n}\n\n/**\n * All seven words are static, so the encoding is exactly the transfer\n * payload with the recipient appended as a left-padded address word.\n */\nexport function encodeExternalTransfer(fields: ExternalTransferFields): string {\n return concat([encodeTransfer(fields), zeroPadValue(getAddress(fields.recipient), 32)]);\n}\n","import { AbiCoder, getAddress } from 'ethers';\nimport { nonNegativeId, unsignedE18, type DecimalLike } from '../signing/encoding';\n\n/**\n * Spot transfer between subaccounts of the same owner, verified by the\n * transfer module. Position transfers are booked as RFQ trades — this\n * action only ever moves a single spot asset.\n */\nexport interface TransferFields {\n toSubaccountId: number | bigint;\n /**\n * Routing sentinel: 0 credits the existing `toSubaccountId`; non-zero\n * creates a new subaccount under this manager id instead (the\n * destination id is then ignored).\n */\n newSubaccountManager: number | bigint;\n /** Protocol spot-asset address (not the underlying ERC-20). */\n asset: string;\n subId: number | bigint;\n /** Strictly positive; signed at e18. */\n amount: DecimalLike;\n /** Maximum fee the signer authorises, in USD; signed at e18. */\n maxFeeUsd: DecimalLike;\n}\n\nconst TRANSFER_ABI = ['uint256', 'uint256', 'address', 'uint256', 'uint256', 'uint256'];\n\n/** ABI-encodes transfer action data: six static 32-byte words. */\nexport function encodeTransfer(fields: TransferFields): string {\n const amount = unsignedE18(fields.amount, 'amount');\n if (amount === 0n) throw new Error('transfer amount must be strictly positive');\n return AbiCoder.defaultAbiCoder().encode(TRANSFER_ABI, [\n nonNegativeId(fields.toSubaccountId, 'toSubaccountId'),\n nonNegativeId(fields.newSubaccountManager, 'newSubaccountManager'),\n getAddress(fields.asset),\n nonNegativeId(fields.subId, 'subId'),\n amount,\n unsignedE18(fields.maxFeeUsd, 'maxFeeUsd'),\n ]);\n}\n","import { concat, getAddress, toBeHex, zeroPadValue } from 'ethers';\n\n/**\n * Whitelisted-recipient delta, verified by the whitelisted-recipient\n * module: the resulting list is `(current ∪ add) \\ remove`.\n */\nexport interface WhitelistedRecipientsFields {\n add: string[];\n remove: string[];\n}\n\n/**\n * Hand-packed layout (2 + A + R words), NOT standard ABI dynamic arrays:\n * word 0 : add count A\n * word 1 : remove count R\n * word 2+i : add[i] (address, left-padded)\n * word 2+A+j : remove[j] (address, left-padded)\n */\nexport function encodeUpdateWhitelistedRecipients(fields: WhitelistedRecipientsFields): string {\n const add = fields.add.map((a) => getAddress(a));\n const remove = fields.remove.map((a) => getAddress(a));\n return concat([\n zeroPadValue(toBeHex(add.length), 32),\n zeroPadValue(toBeHex(remove.length), 32),\n ...add.map((a) => zeroPadValue(a, 32)),\n ...remove.map((a) => zeroPadValue(a, 32)),\n ]);\n}\n","import type {\n InterestHistoryResult,\n OptionSettlementHistoryResponse,\n PaginatedTradesResult,\n PaginationInfo,\n PrivateChangeSubaccountLabelRPCResponse,\n PrivateGetAccountEdgeRPCResponse,\n PrivateGetPositionsRPCResponse,\n PrivateGetSubaccountRPCResponseFor_OrderWireResponseAnd_VaultDepositHoldResponse as SubaccountPortfolio,\n RpcMethod,\n TransferHistoryResult,\n} from '../types';\nimport type { ClientContext } from './context';\n\nexport interface TradeHistoryQuery {\n subaccountId?: number;\n instrumentName?: string;\n orderId?: string;\n quoteId?: string;\n /** UTC-millisecond bounds. */\n fromTimestamp?: number;\n toTimestamp?: number;\n page?: number;\n pageSize?: number;\n}\n\n/**\n * Window over a wallet's history. Omit `subaccountId` to query the whole\n * authenticated wallet; set it to scope to one subaccount.\n */\nexport interface WalletHistoryQuery {\n subaccountId?: number;\n /** UTC-millisecond bounds. */\n startTimestamp?: number;\n endTimestamp?: number;\n}\n\nexport interface LiquidatorHistoryQuery {\n subaccountId: number;\n /** UTC-millisecond bounds. */\n startTimestamp?: number;\n endTimestamp?: number;\n page?: number;\n pageSize?: number;\n}\n\n/** A single simulated perp/option position change for `getMargin`. Amounts are decimal strings. */\nexport interface SimulatedPositionChange {\n instrumentName: string;\n amount: string;\n /** Perps only; mark price is used when omitted. */\n entryPrice?: string;\n}\n\n/** A single simulated collateral (ERC-20) change for `getMargin`. Amount is a decimal string. */\nexport interface SimulatedCollateralChange {\n assetName: string;\n amount: string;\n}\n\nexport interface MarginQuery {\n subaccountId: number;\n simulatedPositionChanges?: SimulatedPositionChange[];\n simulatedCollateralChanges?: SimulatedCollateralChange[];\n}\n\n/** Margin figures before and after the (optionally simulated) trade. All figures are decimal strings. */\nexport interface MarginResult {\n is_valid_trade: boolean;\n post_initial_margin: string;\n post_maintenance_margin: string;\n pre_initial_margin: string;\n pre_maintenance_margin: string;\n subaccount_id: number;\n}\n\n/** One liquidator bid within an auction. Amounts/PnL are decimal strings keyed by asset. */\nexport interface AuctionBidEvent {\n amounts_liquidated: Record<string, string>;\n cash_received: string;\n discount_pnl: string;\n percent_liquidated: string;\n positions_realized_pnl: Record<string, string>;\n positions_realized_pnl_excl_fees: Record<string, string>;\n realized_pnl: string;\n realized_pnl_excl_fees: string;\n timestamp: number;\n tx_hash: string;\n}\n\n/** One auction a subaccount was liquidated in, with the bids that filled it. */\nexport interface AuctionHistory {\n auction_id: string;\n auction_type: 'solvent' | 'insolvent';\n bids: AuctionBidEvent[];\n /** Auction end, UTC milliseconds; `null` while still live. */\n end_timestamp: number | null;\n fee: string;\n start_timestamp: number;\n subaccount_id: number;\n tx_hash: string;\n}\n\nexport interface LiquidatorHistoryResult {\n bids: AuctionBidEvent[];\n pagination: PaginationInfo;\n}\n\n/** Subaccount portfolio and history endpoints — authenticated, no signing. */\nexport class SubaccountsApi {\n constructor(private readonly ctx: ClientContext) {}\n\n /** Ids of all subaccounts owned by the authenticated wallet. */\n async list(): Promise<number[]> {\n const result = await this.ctx.send('private/get_subaccounts', {\n wallet: this.ctx.credentials().ownerAddress,\n });\n return result.subaccount_ids;\n }\n\n /**\n * Full portfolio snapshot: collaterals, positions, open orders, and\n * the margin figures (there is no separate margin endpoint).\n */\n get(subaccountId: number): Promise<SubaccountPortfolio> {\n return this.ctx.send('private/get_subaccount', { subaccount_id: subaccountId });\n }\n\n /** Account-level info for the authenticated wallet: fee tiers, subaccount ids, and rate limits. */\n getAccount(): Promise<PrivateGetAccountEdgeRPCResponse> {\n return this.ctx.send('private/get_account', {\n wallet: this.ctx.credentials().ownerAddress,\n });\n }\n\n /** Full portfolio snapshot for every subaccount owned by the authenticated wallet. */\n getAllPortfolios(): Promise<SubaccountPortfolio[]> {\n return this.ctx.send('private/get_all_portfolios', {\n wallet: this.ctx.credentials().ownerAddress,\n });\n }\n\n /** Open positions for a subaccount. */\n getPositions(subaccountId: number): Promise<PrivateGetPositionsRPCResponse> {\n return this.ctx.send('private/get_positions', { subaccount_id: subaccountId });\n }\n\n /** Rename a subaccount. */\n changeLabel(params: { subaccountId: number; label: string }): Promise<PrivateChangeSubaccountLabelRPCResponse> {\n return this.ctx.send('private/change_subaccount_label', {\n subaccount_id: params.subaccountId,\n label: params.label,\n });\n }\n\n /** Filtered and paginated fills; defaults to all of the wallet's subaccounts. */\n getTradeHistory(query: TradeHistoryQuery = {}): Promise<PaginatedTradesResult> {\n return this.ctx.send('private/get_trade_history', {\n subaccount_id: query.subaccountId ?? null,\n instrument_name: query.instrumentName ?? null,\n order_id: query.orderId ?? null,\n quote_id: query.quoteId ?? null,\n from_timestamp: query.fromTimestamp ?? null,\n to_timestamp: query.toTimestamp ?? null,\n page: query.page ?? null,\n page_size: query.pageSize ?? null,\n });\n }\n\n /** Realized interest settlements, newest first; defaults to the whole wallet. Capped at 1000 rows. */\n getInterestHistory(query: WalletHistoryQuery = {}): Promise<InterestHistoryResult> {\n // The API rejects an explicit `wallet: null` / `subaccount_id: null` (\"Unable to\n // parse …\") — the unused filter must be OMITTED, so use undefined (dropped by JSON), not null.\n return this.ctx.send('private/get_interest_history', {\n wallet: query.subaccountId == null ? this.ctx.credentials().ownerAddress : undefined,\n subaccount_id: query.subaccountId ?? undefined,\n start_timestamp: query.startTimestamp ?? undefined,\n end_timestamp: query.endTimestamp ?? undefined,\n });\n }\n\n /** Internal ERC-20 transfers touching the wallet's subaccounts; defaults to the whole wallet. Capped at 1000 rows. */\n getErc20TransferHistory(query: WalletHistoryQuery = {}): Promise<TransferHistoryResult> {\n return this.ctx.send('private/get_erc20_transfer_history', {\n wallet: query.subaccountId == null ? this.ctx.credentials().ownerAddress : undefined,\n subaccount_id: query.subaccountId ?? undefined,\n start_timestamp: query.startTimestamp ?? undefined,\n end_timestamp: query.endTimestamp ?? undefined,\n });\n }\n\n /** Settled option positions; defaults to the whole wallet, pass `subaccountId` to scope to one. */\n getOptionSettlementHistory(query: { subaccountId?: number } = {}): Promise<OptionSettlementHistoryResponse> {\n return this.ctx.send('private/get_option_settlement_history', {\n wallet: query.subaccountId == null ? this.ctx.credentials().ownerAddress : undefined,\n subaccount_id: query.subaccountId ?? undefined,\n });\n }\n\n /**\n * Margin figures for a subaccount, optionally under simulated position/collateral changes.\n * Predates the schema, so it is absent from the generated EndpointMap and sent untyped.\n */\n getMargin(query: MarginQuery): Promise<MarginResult> {\n return this.ctx.send(\n 'private/get_margin' as RpcMethod,\n {\n subaccount_id: query.subaccountId,\n simulated_position_changes:\n query.simulatedPositionChanges?.map((p) => ({\n instrument_name: p.instrumentName,\n amount: p.amount,\n entry_price: p.entryPrice ?? null,\n })) ?? null,\n simulated_collateral_changes:\n query.simulatedCollateralChanges?.map((c) => ({\n asset_name: c.assetName,\n amount: c.amount,\n })) ?? null,\n } as never,\n ) as Promise<MarginResult>;\n }\n\n /**\n * Auctions in which a subaccount (or the whole wallet) was liquidated.\n * Predates the schema, so it is absent from the generated EndpointMap and sent untyped.\n */\n getLiquidationHistory(query: WalletHistoryQuery = {}): Promise<AuctionHistory[]> {\n return this.ctx.send(\n 'private/get_liquidation_history' as RpcMethod,\n {\n wallet: query.subaccountId == null ? this.ctx.credentials().ownerAddress : undefined,\n subaccount_id: query.subaccountId ?? undefined,\n start_timestamp: query.startTimestamp ?? undefined,\n end_timestamp: query.endTimestamp ?? undefined,\n } as never,\n ) as Promise<AuctionHistory[]>;\n }\n\n /**\n * Paginated auctions a subaccount participated in as the liquidator.\n * Predates the schema, so it is absent from the generated EndpointMap and sent untyped.\n */\n getLiquidatorHistory(query: LiquidatorHistoryQuery): Promise<LiquidatorHistoryResult> {\n return this.ctx.send(\n 'private/get_liquidator_history' as RpcMethod,\n {\n subaccount_id: query.subaccountId,\n start_timestamp: query.startTimestamp ?? null,\n end_timestamp: query.endTimestamp ?? null,\n page: query.page ?? null,\n page_size: query.pageSize ?? null,\n } as never,\n ) as Promise<LiquidatorHistoryResult>;\n }\n}\n","import { formatUnits, getAddress } from 'ethers';\nimport {\n encodeVaultBurnShares,\n encodeVaultCancel,\n encodeVaultCreate,\n encodeVaultDeposit,\n encodeVaultMintShares,\n encodeVaultWithdraw,\n} from '../codecs/vault';\nimport { SignedAction } from '../signing/action';\nimport { domainSeparator } from '../signing/eip712';\nimport { DEFAULT_SIGNATURE_EXPIRY_SEC, expiresIn, randomNonce, toE18, type DecimalLike } from '../signing/encoding';\nimport type { PerformanceResolution, VaultRequestId } from '../types';\nimport type { ClientContext } from './context';\n\n/**\n * Shareholder deposits/withdrawals are queued intents settled later by\n * the curator, so their signatures default to a longer 10-minute\n * validity (the API caps it at 30 days). Curator actions execute\n * immediately and use the standard default expiry.\n */\nconst SHAREHOLDER_INTENT_TTL_SEC = 600;\n\n/** Caller overrides for the signed-action envelope. */\nexport interface VaultActionOverrides {\n nonce?: string;\n signatureExpirySec?: number;\n}\n\nexport interface VaultDepositRequest extends VaultActionOverrides {\n /** The user's source subaccount the deposited funds leave (the action is signed on it). */\n subaccountId: number;\n vaultSubaccountId: number;\n /** Must equal the vault's configured deposit asset (protocol spot-asset address). */\n depositSpotAsset: string;\n /** Amount of the deposit asset; max 12 decimal places. */\n amount: DecimalLike;\n}\n\nexport interface VaultWithdrawRequest extends VaultActionOverrides {\n /** The user's destination subaccount that receives the redeemed funds. */\n subaccountId: number;\n vaultSubaccountId: number;\n /** Vault shares to redeem; max 12 decimal places. */\n sharesToBurn: DecimalLike;\n}\n\nexport interface VaultCancelRequest extends VaultActionOverrides {\n /** Any subaccount the caller owns (the action is signed on it). */\n subaccountId: number;\n vaultSubaccountId: number;\n}\n\nexport interface CreateVaultRequest extends VaultActionOverrides {\n /** The curator's funding subaccount the initial deposit is signed from. */\n subaccountId: number;\n managerId: number;\n depositSpotAsset: string;\n /** Initial deposit in the vault's deposit asset; max 12 decimal places. */\n initialDeposit: DecimalLike;\n managementFeeBps: number;\n performanceFeeBps: number;\n maxSlippageBps: number;\n cooldownSec: number;\n /** Maximum settlement fee authorised, in USD; max 12 decimal places. */\n maxFeeUsd: DecimalLike;\n /** Share price the vault is seeded at, in USD; must lie within the protocol's permitted range. */\n initialSharePriceUsd: DecimalLike;\n /** Spot asset to denominate the high-water mark in; omit for the feed-less USD default. */\n benchmarkAsset?: string;\n}\n\nexport interface MintVaultSharesRequest extends VaultActionOverrides {\n /** The vault subaccount the curator signs the approval on. */\n vaultSubaccountId: number;\n /** Quoted share price in USD per share; max 12 decimal places. */\n sharePrice: DecimalLike;\n /** keccak256 of the user's exact encoded deposit action (0x hex, 32 bytes). */\n depositHash: string;\n /** The queued request being settled, as returned by the vault request reads. */\n requestId: VaultRequestId;\n}\n\nexport interface BurnVaultSharesRequest extends VaultActionOverrides {\n /** The vault subaccount the curator signs the approval on. */\n vaultSubaccountId: number;\n /** Quoted share price in USD per share; max 12 decimal places. */\n sharePrice: DecimalLike;\n /** keccak256 of the user's exact encoded withdraw action (0x hex, 32 bytes). */\n withdrawHash: string;\n /** The queued request being settled, as returned by the vault request reads. */\n requestId: VaultRequestId;\n}\n\nexport interface UpdateVaultInfoRequest {\n vaultSubaccountId: number;\n name?: string;\n description?: string;\n /** Advisory mark-to-market cap in USD. */\n mtmCap?: DecimalLike;\n whitelistOnly?: boolean;\n}\n\nfunction signVaultAction(\n ctx: ClientContext,\n subaccountId: number,\n data: string,\n overrides: VaultActionOverrides,\n defaultTtlSec: number,\n): SignedAction {\n const { ownerAddress, signer } = ctx.credentials();\n const action = new SignedAction(\n {\n subaccountId,\n nonce: overrides.nonce ?? randomNonce(),\n module: ctx.network.modules.vault,\n data,\n expirySec: overrides.signatureExpirySec ?? expiresIn(defaultTtlSec),\n owner: ownerAddress,\n signer: signer.address,\n },\n domainSeparator(ctx.network),\n );\n return action.sign(signer);\n}\n\n/** The flattened signed-envelope fields every signed vault endpoint takes. */\nfunction signedEnvelope(action: SignedAction) {\n return {\n subaccount_id: Number(action.fields.subaccountId),\n // The API deserializes nonce via string_or_number; nanosecond nonces\n // exceed 2^53, so send the decimal string despite the generated type.\n nonce: action.fields.nonce as unknown as number,\n signature_expiry_sec: action.fields.expirySec,\n signer: action.fields.signer,\n signature: action.signature as string, // set by sign() above\n };\n}\n\n/** The share-holding side: queued deposit/withdraw intents plus the wallet's vault reads. */\nexport class ShareholderVaultsApi {\n constructor(private readonly ctx: ClientContext) {}\n\n /** The vault subaccount ids the wallet holds shares in. */\n async getShareholderVaults() {\n return this.ctx.send('private/get_shareholder_vaults', { wallet: this.ctx.credentials().ownerAddress });\n }\n\n /** The wallet's share balance plus the full vault row for every vault it holds shares in. */\n async getShares() {\n return this.ctx.send('private/get_vault_shares', { wallet: this.ctx.credentials().ownerAddress });\n }\n\n /** The wallet's queued deposit/withdraw intents still awaiting curator settlement. */\n async getLiveRequests() {\n return this.ctx.send('private/get_live_vault_requests', { wallet: this.ctx.credentials().ownerAddress });\n }\n\n /** The wallet's full vault action history (every lifecycle status). */\n async getRequestHistory(options: { page?: number; pageSize?: number } = {}) {\n return this.ctx.send('private/get_vault_request_history', {\n wallet: this.ctx.credentials().ownerAddress,\n page: options.page,\n page_size: options.pageSize,\n });\n }\n\n /**\n * Queues a deposit into a vault. The curator later mints shares at a\n * quoted price committed to this exact signed payload; funds are held\n * from the source subaccount until then (or until cancelled).\n */\n async requestDeposit(request: VaultDepositRequest) {\n // Encode from the e18 value so the signed bytes and the wire decimal\n // string are guaranteed to describe the same amount.\n const amountE18 = toE18(request.amount);\n const data = encodeVaultDeposit({\n vaultSubaccountId: request.vaultSubaccountId,\n depositSpotAsset: request.depositSpotAsset,\n amount: amountE18,\n });\n const action = signVaultAction(this.ctx, request.subaccountId, data, request, SHAREHOLDER_INTENT_TTL_SEC);\n return this.ctx.send('private/request_vault_deposit', {\n ...signedEnvelope(action),\n vault_subaccount_id: request.vaultSubaccountId,\n deposit_spot_asset: getAddress(request.depositSpotAsset),\n amount: formatUnits(amountE18, 18),\n });\n }\n\n /** Queues a share redemption; the curator later burns the shares at a quoted price. */\n async requestWithdraw(request: VaultWithdrawRequest) {\n const sharesE18 = toE18(request.sharesToBurn);\n const data = encodeVaultWithdraw({\n vaultSubaccountId: request.vaultSubaccountId,\n sharesToBurn: sharesE18,\n });\n const action = signVaultAction(this.ctx, request.subaccountId, data, request, SHAREHOLDER_INTENT_TTL_SEC);\n return this.ctx.send('private/request_vault_withdraw', {\n ...signedEnvelope(action),\n vault_subaccount_id: request.vaultSubaccountId,\n shares_to_burn: formatUnits(sharesE18, 18),\n });\n }\n\n /** Cancels ALL of the wallet's pending intents for a vault (deposits and withdrawals). */\n async cancelAllRequests(request: VaultCancelRequest) {\n const data = encodeVaultCancel(request.vaultSubaccountId);\n const action = signVaultAction(this.ctx, request.subaccountId, data, request, SHAREHOLDER_INTENT_TTL_SEC);\n return this.ctx.send('private/cancel_all_vault_requests', {\n ...signedEnvelope(action),\n vault_subaccount_id: request.vaultSubaccountId,\n });\n }\n}\n\n/**\n * The curating side — open to any wallet in v3 (curating is not a\n * privileged role): vault creation, metadata updates, and the settle\n * approvals that execute queued shareholder intents at a quoted price.\n */\nexport class CuratorVaultsApi {\n constructor(private readonly ctx: ClientContext) {}\n\n /** The vault subaccount ids this wallet curates. */\n async getCuratedVaults() {\n return this.ctx.send('private/get_curated_vaults', { wallet: this.ctx.credentials().ownerAddress });\n }\n\n /**\n * Creates a vault funded from the signer's subaccount; the signer\n * becomes its curator. Fee rates and max slippage are immutable\n * afterwards.\n */\n async createVault(request: CreateVaultRequest) {\n const initialDepositE18 = toE18(request.initialDeposit);\n const maxFeeUsdE18 = toE18(request.maxFeeUsd);\n const sharePriceUsdE18 = toE18(request.initialSharePriceUsd);\n const benchmarkAsset = request.benchmarkAsset === undefined ? undefined : getAddress(request.benchmarkAsset);\n const data = encodeVaultCreate({\n managerId: request.managerId,\n depositSpotAsset: request.depositSpotAsset,\n initialDeposit: initialDepositE18,\n managementFeeBps: request.managementFeeBps,\n performanceFeeBps: request.performanceFeeBps,\n maxSlippageBps: request.maxSlippageBps,\n cooldownSec: request.cooldownSec,\n maxFeeUsd: maxFeeUsdE18,\n initialSharePriceUsd: sharePriceUsdE18,\n benchmarkAsset,\n });\n const action = signVaultAction(this.ctx, request.subaccountId, data, request, DEFAULT_SIGNATURE_EXPIRY_SEC);\n return this.ctx.send('private/create_vault', {\n ...signedEnvelope(action),\n manager_id: request.managerId,\n deposit_spot_asset: getAddress(request.depositSpotAsset),\n initial_deposit: formatUnits(initialDepositE18, 18),\n management_fee_bps: request.managementFeeBps,\n performance_fee_bps: request.performanceFeeBps,\n max_slippage_bps: request.maxSlippageBps,\n cooldown_sec: request.cooldownSec,\n max_fee_usd: formatUnits(maxFeeUsdE18, 18),\n initial_share_price_usd: formatUnits(sharePriceUsdE18, 18),\n // Presence drives the signed hasBenchmark flag; the exchange derives it the same way.\n benchmark_asset: benchmarkAsset ?? null,\n });\n }\n\n /** Settles one queued shareholder deposit, minting shares at the quoted price. */\n async mintShares(request: MintVaultSharesRequest) {\n const sharePriceE18 = toE18(request.sharePrice);\n const data = encodeVaultMintShares({ sharePrice: sharePriceE18, depositHash: request.depositHash });\n const action = signVaultAction(this.ctx, request.vaultSubaccountId, data, request, DEFAULT_SIGNATURE_EXPIRY_SEC);\n return this.ctx.send('private/mint_vault_shares', {\n ...signedEnvelope(action),\n share_price: formatUnits(sharePriceE18, 18),\n deposit_hash: request.depositHash,\n request_id: request.requestId,\n });\n }\n\n /** Settles one queued shareholder withdrawal, burning shares at the quoted price. */\n async burnShares(request: BurnVaultSharesRequest) {\n const sharePriceE18 = toE18(request.sharePrice);\n const data = encodeVaultBurnShares({ sharePrice: sharePriceE18, withdrawHash: request.withdrawHash });\n const action = signVaultAction(this.ctx, request.vaultSubaccountId, data, request, DEFAULT_SIGNATURE_EXPIRY_SEC);\n return this.ctx.send('private/burn_vault_shares', {\n ...signedEnvelope(action),\n share_price: formatUnits(sharePriceE18, 18),\n withdraw_hash: request.withdrawHash,\n request_id: request.requestId,\n });\n }\n\n /** Updates the vault's advisory metadata (unsigned; an ownership check gates it to the curator). */\n async updateInfo(request: UpdateVaultInfoRequest) {\n return this.ctx.send('private/update_vault_info', {\n subaccount_id: request.vaultSubaccountId,\n name: request.name,\n description: request.description,\n mtm_cap: request.mtmCap === undefined ? undefined : formatUnits(toE18(request.mtmCap), 18),\n whitelist_only: request.whitelistOnly,\n });\n }\n\n /** The vault's queued deposit intents awaiting a `mintShares` settlement, FIFO-ordered with the queue total. */\n async getLiveMintRequests(vaultSubaccountId: number, limit = 100) {\n return this.ctx.send('private/get_live_mint_requests', { subaccount_id: vaultSubaccountId, limit });\n }\n\n /** The vault's queued withdraw intents awaiting a `burnShares` settlement, FIFO-ordered with the queue total. */\n async getLiveBurnRequests(vaultSubaccountId: number, limit = 100) {\n return this.ctx.send('private/get_live_burn_requests', { subaccount_id: vaultSubaccountId, limit });\n }\n\n /** Rejects a queued deposit intent, releasing the holder's funds without minting shares. */\n async rejectDepositRequest(requestId: VaultRequestId, reason?: string) {\n // The API auth layer binds the call to the caller via a top-level `wallet`\n // (the handler itself only reads request_id/reason); it is absent from the\n // generated params type, so attach it explicitly.\n return this.ctx.send('private/reject_deposit_request', {\n request_id: requestId,\n reason,\n wallet: this.ctx.credentials().ownerAddress,\n } as { request_id: VaultRequestId; reason?: string });\n }\n\n /**\n * Force-exits a holder at mark-to-market with no curator price quote (unsigned;\n * an ownership check gates it to the curator of `vaultSubaccountId`).\n */\n async forceBurn(vaultSubaccountId: number, holder: string) {\n return this.ctx.send('private/force_burn', { subaccount_id: vaultSubaccountId, holder });\n }\n}\n\n/** Vault discovery and stats, plus the role-scoped `shareholder` and `curator` flows. */\nexport class VaultsApi {\n readonly shareholder: ShareholderVaultsApi;\n readonly curator: CuratorVaultsApi;\n\n constructor(private readonly ctx: ClientContext) {\n this.shareholder = new ShareholderVaultsApi(ctx);\n this.curator = new CuratorVaultsApi(ctx);\n }\n\n async getVault(vaultSubaccountId: number) {\n return this.ctx.send('public/get_vault', { subaccount_id: vaultSubaccountId });\n }\n\n async listVaults(options: { page?: number; pageSize?: number } = {}) {\n return this.ctx.send('public/get_vaults', { page: options.page, page_size: options.pageSize });\n }\n\n async getActionHistory(\n vaultSubaccountId: number,\n options: { eventType?: string; page?: number; pageSize?: number } = {},\n ) {\n return this.ctx.send('public/get_vault_action_history', {\n subaccount_id: vaultSubaccountId,\n event_type: options.eventType,\n page: options.page,\n page_size: options.pageSize,\n });\n }\n\n async getPerformanceHistory(\n vaultSubaccountId: number,\n resolution: PerformanceResolution,\n options: { from?: number; to?: number; limit?: number } = {},\n ) {\n return this.ctx.send('public/get_vault_performance_history', {\n subaccount_id: vaultSubaccountId,\n resolution,\n ...options,\n });\n }\n}\n","import { AbiCoder, ZeroAddress, getAddress, isHexString } from 'ethers';\nimport { assertE12Precision, toE18, unsignedE18, type DecimalLike } from '../signing/encoding';\n\n/**\n * Vault action encodings — shareholder intents (deposit/withdraw/cancel)\n * and curator actions (create, and the mint/burn settle approvals; in v3\n * anyone can curate a vault). Every vault action is signed under the\n * single vault module; word 0 is a uint256 kind word — the protocol's\n * ONLY discriminator between vault action types, so its high bytes must\n * be exactly zero. Deposits and withdrawals are queued intents the\n * curator later settles at a quoted share price committed to the\n * keccak256 of these exact bytes.\n */\n\nconst abi = AbiCoder.defaultAbiCoder();\n\n/** Word-0 kind discriminators. */\nexport const VAULT_ACTION_KIND = {\n create: 0,\n deposit: 1,\n withdraw: 2,\n cancel: 3,\n mintShares: 4,\n burnShares: 5,\n} as const;\n\n/**\n * Vault amounts are signed at e18 but held at e12 by the protocol,\n * which rejects (not truncates) sub-1e12 precision, and requires\n * strictly positive values.\n */\nfunction positiveE18(label: string, value: DecimalLike): bigint {\n const e18 = toE18(value);\n if (e18 <= 0n) throw new Error(`${label} must be positive`);\n assertE12Precision(e18, label);\n return e18;\n}\n\nexport interface VaultDepositFields {\n vaultSubaccountId: number | bigint;\n /** Must equal the vault's configured deposit asset (protocol spot-asset address). */\n depositSpotAsset: string;\n /** Deposit amount in the deposit asset's units; max 12 decimal places. */\n amount: DecimalLike;\n}\n\n/** VaultDepositData (kind = 1, 4 words): [kind, vaultSubaccountId, depositSpotAsset, amountE18]. */\nexport function encodeVaultDeposit(fields: VaultDepositFields): string {\n return abi.encode(\n ['uint256', 'uint256', 'address', 'uint256'],\n [\n VAULT_ACTION_KIND.deposit,\n fields.vaultSubaccountId,\n getAddress(fields.depositSpotAsset),\n positiveE18('amount', fields.amount),\n ],\n );\n}\n\nexport interface VaultWithdrawFields {\n vaultSubaccountId: number | bigint;\n /** Vault shares to redeem; max 12 decimal places. */\n sharesToBurn: DecimalLike;\n}\n\n/** VaultWithdrawData (kind = 2, 3 words): [kind, vaultSubaccountId, sharesToBurnE18]. */\nexport function encodeVaultWithdraw(fields: VaultWithdrawFields): string {\n return abi.encode(\n ['uint256', 'uint256', 'uint256'],\n [VAULT_ACTION_KIND.withdraw, fields.vaultSubaccountId, positiveE18('sharesToBurn', fields.sharesToBurn)],\n );\n}\n\n/**\n * VaultCancelData (kind = 3, 2 words): [kind, vaultSubaccountId].\n * Invalidates ALL of the signer's pending intents for the vault by\n * bumping their per-(vault, holder) nonce to the envelope's nonce.\n */\nexport function encodeVaultCancel(vaultSubaccountId: number | bigint): string {\n return abi.encode(['uint256', 'uint256'], [VAULT_ACTION_KIND.cancel, vaultSubaccountId]);\n}\n\nexport interface VaultCreateFields {\n managerId: number;\n depositSpotAsset: string;\n /** Initial deposit moved funding subaccount → vault; max 12 decimal places. */\n initialDeposit: DecimalLike;\n managementFeeBps: number;\n performanceFeeBps: number;\n maxSlippageBps: number;\n cooldownSec: number | bigint;\n /** Maximum settlement fee authorised, in USD; max 12 decimal places. */\n maxFeeUsd: DecimalLike;\n /** Share price the vault is seeded at, in USD; max 12 decimal places. */\n initialSharePriceUsd: DecimalLike;\n /**\n * Spot asset the high-water mark is denominated in. Omit for the\n * feed-less USD default — presence drives the encoded hasBenchmark\n * flag, exactly as the exchange derives it from the wire param.\n */\n benchmarkAsset?: string;\n}\n\n/**\n * Create-vault action data (kind = 0, 12 words):\n * [kind, managerId, depositSpotAsset, initialDepositE18,\n * managementFeeBps, performanceFeeBps, maxSlippageBps, cooldownSec,\n * maxFeeUsdE18, initialSharePriceUsdE18, benchmarkAsset, hasBenchmark].\n * bps rates and cooldownSec are plain integers, not e18.\n */\nexport function encodeVaultCreate(fields: VaultCreateFields): string {\n const benchmark = fields.benchmarkAsset;\n return abi.encode(\n // prettier-ignore\n ['uint256', 'uint256', 'address', 'uint256', 'uint256', 'uint256', 'uint256', 'uint256', 'uint256', 'uint256', 'address', 'bool'],\n [\n VAULT_ACTION_KIND.create,\n fields.managerId,\n getAddress(fields.depositSpotAsset),\n unsignedE18(fields.initialDeposit, 'initialDeposit'),\n fields.managementFeeBps,\n fields.performanceFeeBps,\n fields.maxSlippageBps,\n fields.cooldownSec,\n unsignedE18(fields.maxFeeUsd, 'maxFeeUsd'),\n unsignedE18(fields.initialSharePriceUsd, 'initialSharePriceUsd'),\n benchmark === undefined ? ZeroAddress : getAddress(benchmark),\n benchmark !== undefined,\n ],\n );\n}\n\nexport interface VaultMintSharesFields {\n /** Quoted share price in USD per share; max 12 decimal places. */\n sharePrice: DecimalLike;\n /** keccak256 of the user's exact encoded deposit action (0x hex, 32 bytes). */\n depositHash: string;\n}\n\n/** MintSharesActionData (kind = 4): the curator's approval to settle one queued deposit. */\nexport function encodeVaultMintShares(fields: VaultMintSharesFields): string {\n return encodeSettleApproval(VAULT_ACTION_KIND.mintShares, fields.sharePrice, 'depositHash', fields.depositHash);\n}\n\nexport interface VaultBurnSharesFields {\n /** Quoted share price in USD per share; max 12 decimal places. */\n sharePrice: DecimalLike;\n /** keccak256 of the user's exact encoded withdraw action (0x hex, 32 bytes). */\n withdrawHash: string;\n}\n\n/** BurnSharesActionData (kind = 5): the curator's approval to settle one queued withdrawal. */\nexport function encodeVaultBurnShares(fields: VaultBurnSharesFields): string {\n return encodeSettleApproval(VAULT_ACTION_KIND.burnShares, fields.sharePrice, 'withdrawHash', fields.withdrawHash);\n}\n\n/**\n * Shared mint/burn layout (3 words): [kind, sharePriceE18, userActionHash].\n * The hash commits the quoted price to one exact user action, so the\n * exchange cannot pair it with a different deposit/withdrawal.\n */\nfunction encodeSettleApproval(kind: number, sharePrice: DecimalLike, hashLabel: string, hash: string): string {\n if (!isHexString(hash, 32)) throw new Error(`${hashLabel} must be a 0x-prefixed 32-byte hex string`);\n return abi.encode(['uint256', 'uint256', 'bytes32'], [kind, unsignedE18(sharePrice, 'sharePrice'), hash]);\n}\n","import { getAddress } from 'ethers';\nimport { encodeWithdrawal } from '../codecs/withdrawal';\nimport { SignedAction } from '../signing/action';\nimport { DEFAULT_SIGNATURE_EXPIRY_SEC, expiresIn, randomNonce, type DecimalLike } from '../signing/encoding';\nimport { domainSeparator } from '../signing/eip712';\nimport type { PrivateWithdrawEdgeRpcResponse } from '../types';\nimport type { ClientContext } from './context';\nimport { decimalString, resolveSpotAsset } from './spotTransfers';\n\nexport interface WithdrawParams {\n subaccountId: number;\n /** Currency name (e.g. \"USDC\") or protocol spot-asset address. */\n asset: string;\n /** Amount in human units. Signed at the ERC-20's native decimals — the protocol's only non-e18 amount. */\n amount: DecimalLike;\n /**\n * Guard for the ERC-20's decimals. The exchange scales the signed amount\n * with its own asset metadata, so a value differing from the exchange's\n * is rejected client-side rather than producing a doomed signature.\n */\n decimals?: number;\n /** Fee cap in USD. Defaults to the standard withdrawal fee: 1 USD, or 10 USD with `forceBatch`. */\n maxFeeUsd?: DecimalLike;\n /**\n * Guard for the L1 payout address. The exchange always pays out to the\n * action signer, so any other value is rejected client-side.\n */\n recipient?: string;\n /** Pay the higher fee to have the batch proven immediately. */\n forceBatch?: boolean;\n nonce?: string;\n signatureExpirySec?: number;\n}\n\n/**\n * Withdrawals to L1 (`private/withdraw`).\n *\n * The exchange reconstructs the signed payload with the payout recipient\n * fixed to the action signer's address — withdrawals always pay out to\n * the key that signs them. NOTE: when a session key signs, funds go to\n * the session key's address, not the owner's.\n */\nexport class WithdrawalsApi {\n constructor(private readonly ctx: ClientContext) {}\n\n /** Builds the signed wire payload shared by `withdraw` and `withdrawDebug`. */\n private async buildWithdrawPayload(params: WithdrawParams) {\n const { ownerAddress, signer } = this.ctx.credentials();\n const recipient = getAddress(params.recipient ?? signer.address);\n if (recipient !== getAddress(signer.address)) {\n throw new Error(\n `the exchange pays withdrawals out to the action signer (${signer.address}); recipient ${recipient} cannot be honored`,\n );\n }\n const asset = await resolveSpotAsset(this.ctx, params.asset);\n if (params.decimals !== undefined && params.decimals !== asset.decimals) {\n throw new Error(\n `decimals ${params.decimals} does not match the exchange's metadata for ${asset.name} (${asset.decimals}) — the signature would be rejected`,\n );\n }\n const forceBatch = params.forceBatch ?? false;\n const maxFeeUsd = params.maxFeeUsd ?? (forceBatch ? '10' : '1');\n const data = encodeWithdrawal({\n protocolAsset: asset.address,\n maxFeeUsd,\n recipient,\n amount: params.amount,\n decimals: asset.decimals,\n forceBatch,\n });\n const action = new SignedAction(\n {\n subaccountId: params.subaccountId,\n nonce: params.nonce ?? randomNonce(),\n module: this.ctx.network.modules.withdrawal,\n data,\n expirySec: params.signatureExpirySec ?? expiresIn(DEFAULT_SIGNATURE_EXPIRY_SEC),\n owner: ownerAddress,\n signer: signer.address,\n },\n domainSeparator(this.ctx.network),\n ).sign(signer);\n return {\n subaccount_id: params.subaccountId,\n asset_name: asset.name,\n amount_in_underlying: decimalString(params.amount, asset.decimals),\n max_fee_usd: decimalString(maxFeeUsd),\n force_batch: forceBatch,\n // Nonces are UTC-nanosecond decimal strings beyond 2^53; the API accepts string-or-number despite the generated `number`.\n nonce: action.fields.nonce as unknown as number,\n signer: action.fields.signer,\n signature: action.signature!,\n signature_expiry_sec: action.fields.expirySec,\n };\n }\n\n async withdraw(params: WithdrawParams): Promise<PrivateWithdrawEdgeRpcResponse> {\n return this.ctx.send('private/withdraw', await this.buildWithdrawPayload(params));\n }\n\n /**\n * Debug helper: signs the withdrawal exactly like `withdraw` but submits it\n * to `public/withdraw_debug`, which returns the server-computed encoded data\n * and action/typed-data hashes instead of executing. Use it to verify your\n * client-side signing matches the exchange's.\n */\n async withdrawDebug(params: WithdrawParams) {\n return this.ctx.send('public/withdraw_debug', (await this.buildWithdrawPayload(params)) as never);\n }\n\n /**\n * Withdrawal history rows (up to 1000). Scoped to one subaccount when\n * `subaccountId` is given, otherwise to the whole owner wallet.\n * Timestamps are unix milliseconds.\n */\n async getHistory(options: { subaccountId?: number; startTimestampMs?: number; endTimestampMs?: number } = {}) {\n return this.ctx.send('private/get_withdrawal_history', {\n subaccount_id: options.subaccountId,\n wallet: options.subaccountId === undefined ? this.ctx.credentials().ownerAddress : undefined,\n start_timestamp: options.startTimestampMs,\n end_timestamp: options.endTimestampMs,\n });\n }\n}\n","import { AbiCoder, getAddress } from 'ethers';\nimport { toScaled, unsignedE18, type DecimalLike } from '../signing/encoding';\n\n/** Withdrawal to L1, verified by the withdrawal module. */\nexport interface WithdrawalFields {\n /** Protocol asset contract address (not the underlying ERC-20). */\n protocolAsset: string;\n /** Maximum fee the signer authorises, in USD; signed at e18 like every other action value. */\n maxFeeUsd: DecimalLike;\n /** L1 payout recipient. The exchange only constructs withdrawals paying out to the action signer. */\n recipient: string;\n /**\n * Withdrawal amount in the ERC-20's NATIVE decimals (USDC = 6) — the\n * protocol's only never-scaled amount, since it is the L1 payout value.\n */\n amount: DecimalLike;\n /** The underlying ERC-20's decimals, used to scale `amount`. */\n decimals: number;\n /** Pay a higher fee for immediate batch proving. */\n forceBatch: boolean;\n}\n\nconst WITHDRAWAL_ABI = ['address', 'uint256', 'address', 'uint256', 'bool'];\n\n/** ABI-encodes withdrawal action data: five static 32-byte words. */\nexport function encodeWithdrawal(fields: WithdrawalFields): string {\n if (!Number.isInteger(fields.decimals) || fields.decimals < 0 || fields.decimals > 255) {\n throw new Error('decimals must be an integer between 0 and 255');\n }\n const amount = toScaled(fields.amount, fields.decimals);\n if (amount <= 0n) throw new Error('withdrawal amount must be strictly positive');\n return AbiCoder.defaultAbiCoder().encode(WITHDRAWAL_ABI, [\n getAddress(fields.protocolAsset),\n unsignedE18(fields.maxFeeUsd, 'maxFeeUsd'),\n getAddress(fields.recipient),\n amount,\n fields.forceBatch,\n ]);\n}\n","import type { BaseWallet } from 'ethers';\n\n/**\n * The minimal signer the auth flow needs: anything that can EIP-191\n * `signMessage` (an ethers Wallet, an HD wallet, a provider-backed\n * signer, a hardware-wallet adapter…). Kept structural so any\n * ethers-compatible signer works, not just this SDK's `ethers` instance.\n */\nexport interface AuthSigner {\n signMessage(message: string): Promise<string>;\n}\n\n/**\n * Who a request acts as: the account owner's address plus the wallet\n * that actually signs (the owner itself, or a registered session key).\n */\nexport interface AuthCredentials {\n ownerAddress: string;\n signer: BaseWallet;\n}\n\n/**\n * The exchange authenticates requests with an EIP-191 personal_sign\n * over the current unix-millisecond timestamp as a decimal string.\n * Owner-wallet signatures must be fresh; session-key signatures skip\n * the freshness window but the key must be registered and unexpired.\n *\n * Note: header names are `X-Lyra*` — the live wire format predates the\n * Derive rebrand.\n */\nexport async function authHeaders(credentials: {\n ownerAddress: string;\n signer: AuthSigner;\n}): Promise<Record<string, string>> {\n const timestamp = Date.now().toString();\n const signature = await credentials.signer.signMessage(timestamp);\n return {\n 'X-LyraWallet': credentials.ownerAddress,\n 'X-LyraTimestamp': timestamp,\n 'X-LyraSignature': signature,\n };\n}\n\n/** `public/login` takes the same wallet/timestamp/signature triple as the REST headers. */\nexport async function loginParams(credentials: {\n ownerAddress: string;\n signer: AuthSigner;\n}): Promise<{ wallet: string; timestamp: string; signature: string }> {\n const timestamp = Date.now().toString();\n return {\n wallet: credentials.ownerAddress,\n timestamp,\n signature: await credentials.signer.signMessage(timestamp),\n };\n}\n","/**\n * Canonical EIP-712 action module addresses. Every signed action's\n * `module` field commits to one of these — the same set on every\n * network (mainnet, testnet, local).\n */\nexport const V3_MODULE_ADDRESSES = {\n trade: '0xB8D20c2B7a1Ad2EE33Bc50eF10876eD3035b5e7b',\n transfer: '0x01259207A40925b794C8ac320456F7F6c8FE2636',\n withdrawal: '0x9d0E8f5b25384C7310CB8C6aE32C8fbeb645d083',\n rfq: '0x9371352CCef6f5b36EfDFE90942fFE622Ab77F1D',\n externalTransfer: '0x8F9B8f12ddA05FB1F0DDDDe8f5af8cECF54f8aC9',\n whitelistedRecipient: '0xB86D6DE1b76c9839e4BA860848CD98A1dABd6B54',\n vault: '0x2885c174ebf5524aED9c721d60c12b1537685186',\n liquidation: '0x66d23e59DaEEF13904eFA2D4B8658aeD05f59a92',\n createSessionKey: '0xe330CF64ff6EbF41699aad344Cb21d78db1D2bb6',\n} as const;\n","import { V3_MODULE_ADDRESSES } from '../signing/modules';\nimport type { NetworkConfig, NetworkName } from './types';\n\n/**\n * Network presets for the v3 API. chainId + contracts.matching are the\n * inputs to the computed EIP-712 domain separator; the values here\n * reproduce the separators the deployed contracts accept (unit-tested in\n * test/unit/eip712.test.ts).\n *\n * The EIP-712 domain separator is computed from `chainId` and the\n * constant Matching verifying contract (signing/eip712.ts).\n */\nexport const NETWORKS: Record<NetworkName, NetworkConfig> = {\n mainnet: {\n name: 'mainnet',\n httpUrl: 'https://api.derive.xyz/v3',\n wsUrl: 'wss://api.derive.xyz/v3/ws',\n chainId: 1, // Ethereum L1\n modules: { ...V3_MODULE_ADDRESSES },\n contracts: {\n // Placeholder — set the mainnet ActionManager address once published.\n actionManager: '0x0000000000000000000000000000000000000000',\n usdc: '0x6879287835A86F50f784313dBEd5E5cCC5bb8481',\n cash: '0x57B03E14d409ADC7fAb6CFc44b5886CAD2D5f02b',\n },\n },\n testnet: {\n name: 'testnet',\n httpUrl: 'https://testnet.api.derive.xyz/v3',\n wsUrl: 'wss://testnet.api.derive.xyz/v3/ws',\n chainId: 11155111, // Sepolia\n modules: { ...V3_MODULE_ADDRESSES },\n contracts: {\n actionManager: '0xcd84E4CC2996787D2F6794Ce99FeCda5Edb10E86',\n usdc: '0x7F4B9B80863b937340202f26Ad555CC7D3ABD2BA',\n },\n },\n local: {\n name: 'local',\n httpUrl: 'http://localhost:8080',\n wsUrl: 'ws://localhost:3000/ws',\n chainId: 31337, // anvil\n modules: { ...V3_MODULE_ADDRESSES },\n contracts: {\n actionManager: '0x0165878A594ca255338adfa4d48449f69242Eb8F',\n usdc: '0xA51c1fc2f0D1a1b8494Ed1FE312d7C3a78Ed91C0',\n },\n },\n};\n\nexport function resolveNetwork(network: NetworkName | NetworkConfig): NetworkConfig {\n if (typeof network !== 'string') return network;\n const preset = NETWORKS[network];\n if (!preset) {\n throw new Error(`unknown network preset '${network}' — pass a full NetworkConfig instead`);\n }\n return preset;\n}\n","import type { ClientContext } from '../api/context';\nimport type { WsTransport } from '../transport/ws';\nimport type { TypedChannel } from './channels';\n\n/** A live channel subscription; `unsubscribe` is idempotent. */\nexport interface Subscription {\n channel: string;\n unsubscribe(): Promise<void>;\n}\n\n/** Streams buffer at most this many unconsumed notifications; beyond it the oldest are dropped. */\nconst STREAM_BUFFER_LIMIT = 10_000;\n\n/**\n * Pub/sub over the websocket transport. Owns notification routing:\n * every `subscription` message the transport receives is dispatched to\n * the handlers registered for its channel. The exchange keys\n * subscriptions to the connection, so the client calls `resubscribeAll`\n * from its reconnect hook to restore them on a fresh socket.\n */\nexport class Subscriptions {\n private readonly handlers = new Map<string, Set<(data: unknown) => void>>();\n\n constructor(\n private readonly ctx: ClientContext,\n private readonly ws: WsTransport,\n ) {\n ws.onNotification = (channelName, data) => this.dispatch(channelName, data);\n }\n\n /**\n * Subscribes to a channel and registers `handler` for its\n * notifications. Multiple handlers share one wire subscription per\n * channel: the `subscribe` RPC is sent only for the first handler on a\n * channel, and `unsubscribe` only when the last is removed.\n */\n async subscribe<D>(ch: TypedChannel<D>, handler: (data: D) => void): Promise<Subscription> {\n // A fresh wrapper per call keeps each Subscription independently\n // removable even when the same handler function is registered twice.\n const entry = (data: unknown): void => handler(data as D);\n const existing = this.handlers.get(ch.name);\n if (existing) {\n existing.add(entry);\n } else {\n const set = new Set([entry]);\n this.handlers.set(ch.name, set);\n try {\n await this.sendChannelRpc('subscribe', [ch.name]);\n } catch (error) {\n set.delete(entry);\n if (set.size === 0) this.handlers.delete(ch.name);\n throw error;\n }\n }\n return {\n channel: ch.name,\n unsubscribe: async () => {\n const current = this.handlers.get(ch.name);\n if (!current?.delete(entry)) return;\n if (current.size === 0) {\n this.handlers.delete(ch.name);\n await this.sendChannelRpc('unsubscribe', [ch.name]);\n }\n },\n };\n }\n\n /**\n * The channel as an async iterator: subscribes on the first `next()`,\n * buffers notifications the consumer has not yet read (dropping the\n * oldest beyond `STREAM_BUFFER_LIMIT`), and unsubscribes when the\n * loop ends (`break` / `return()` / `throw()`).\n */\n stream<D>(ch: TypedChannel<D>): AsyncIterableIterator<D> {\n const queue: D[] = [];\n const waiters: Array<(result: IteratorResult<D>) => void> = [];\n let subscribing: Promise<Subscription> | undefined;\n let done = false;\n let overflowWarned = false;\n\n const onData = (data: D): void => {\n if (done) return;\n const waiter = waiters.shift();\n if (waiter) {\n waiter({ value: data, done: false });\n return;\n }\n queue.push(data);\n if (queue.length > STREAM_BUFFER_LIMIT) {\n queue.shift();\n if (!overflowWarned) {\n overflowWarned = true;\n this.ctx.logger(\n 'warn',\n `stream ${ch.name}: buffer exceeded ${STREAM_BUFFER_LIMIT} notifications; dropping oldest`,\n );\n }\n }\n };\n\n const finish = async (): Promise<void> => {\n if (done) return;\n done = true;\n for (const waiter of waiters.splice(0)) waiter({ value: undefined, done: true });\n // A failed subscribe is swallowed here: next() already surfaced it.\n const subscription = await subscribing?.catch(() => undefined);\n await subscription?.unsubscribe();\n };\n\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n next: async (): Promise<IteratorResult<D>> => {\n if (done) return { value: undefined, done: true };\n subscribing ??= this.subscribe(ch, onData);\n await subscribing;\n if (done) return { value: undefined, done: true };\n if (queue.length > 0) return { value: queue.shift()!, done: false };\n return new Promise((resolve) => waiters.push(resolve));\n },\n return: async (): Promise<IteratorResult<D>> => {\n await finish();\n return { value: undefined, done: true };\n },\n throw: async (error?: unknown): Promise<IteratorResult<D>> => {\n await finish();\n throw error;\n },\n };\n }\n\n /** Re-sends `subscribe` for every active channel; the client calls this after a websocket reconnect. */\n async resubscribeAll(): Promise<void> {\n const channels = [...this.handlers.keys()];\n if (channels.length === 0) return;\n const result = await this.ws.send('subscribe', { channels });\n for (const name of channels) {\n const status = result.status[name];\n // 'already subscribed' is fine here; only a genuine failure is logged.\n // Logged rather than thrown: one bad channel must not abort the reconnect flow.\n if (status !== 'ok' && status !== 'already subscribed') {\n this.ctx.logger('error', `resubscribe to ${name} failed`, status);\n }\n }\n }\n\n /**\n * `subscribe`/`unsubscribe` exist only over the websocket, so they go\n * straight to the ws transport (never the client's HTTP fallback). A\n * per-channel `status` other than 'ok'/'already subscribed' throws.\n */\n private async sendChannelRpc(method: 'subscribe' | 'unsubscribe', channels: string[]): Promise<void> {\n const result = await this.ws.send(method, { channels });\n for (const name of channels) {\n const status = result.status[name];\n if (status !== 'ok' && status !== 'already subscribed') {\n throw new Error(`${method} ${name} failed: ${String(status)}`);\n }\n }\n }\n\n private dispatch(channelName: string, data: unknown): void {\n const set = this.handlers.get(channelName);\n if (!set || set.size === 0) {\n this.ctx.logger('debug', `dropping notification for unhandled channel ${channelName}`);\n return;\n }\n for (const handler of set) {\n try {\n handler(data);\n } catch (error) {\n this.ctx.logger('error', `subscription handler for ${channelName} threw`, error);\n }\n }\n }\n}\n","export const PUBLIC_METHOD_PREFIXES: readonly string[] = ['public/', 'private/'];\n\nexport const WS_CONTROL_METHODS: ReadonlySet<string> = new Set(['subscribe', 'unsubscribe']);\n\nexport function isPublicApiMethod(method: string): boolean {\n return PUBLIC_METHOD_PREFIXES.some((prefix) => method.startsWith(prefix));\n}\n","import { DeriveRpcError } from '../errors';\nimport { isPublicApiMethod, WS_CONTROL_METHODS } from '../methodGuard';\n\nexport interface RpcErrorShape {\n code: number;\n message: string;\n data?: unknown;\n}\n\n/** The raw JSON-RPC response envelope as it arrives off the wire. */\nexport interface RawRpcResponse {\n id?: number | string | null;\n result?: unknown;\n error?: RpcErrorShape;\n}\n\n/**\n * A well-formed public method is `namespace/name`, both lowercase\n * snake-case. Rejecting anything else stops a crafted string containing\n * path traversal from escaping the path when the HTTP transport\n * interpolates the method into the request URL.\n */\nconst METHOD_FORMAT = /^[a-z]+\\/[a-z0-9_]+$/;\n\n/**\n * Runtime companion to the compile-time EndpointMap restriction: even a\n * raw string can only address a `public/`/`private/` method, and can never\n * escape the request path, through the SDK.\n */\nexport function assertPublicMethod(method: string): void {\n if (WS_CONTROL_METHODS.has(method)) return;\n if (!METHOD_FORMAT.test(method)) {\n throw new Error(`invalid method '${method}': expected the form namespace/name`);\n }\n if (!isPublicApiMethod(method)) {\n throw new Error(`${method} is not part of the public Derive API`);\n }\n}\n\n/** Unwraps a JSON-RPC response, throwing `DeriveRpcError` on the error variant. */\nexport function unwrapResponse<T>(method: string, raw: RawRpcResponse): T {\n if (raw.error) throw new DeriveRpcError(method, raw.error);\n if (!('result' in raw)) throw new Error(`${method}: malformed response — neither result nor error present`);\n return raw.result as T;\n}\n","import type { Logger } from '../config/types';\nimport { DeriveTimeoutError } from '../errors';\nimport { SDK_VERSION } from '../version';\nimport { assertPublicMethod, unwrapResponse, type RawRpcResponse } from './jsonrpc';\nimport type { ParamsOf, ResultFor, RpcMethod } from '../types';\n\nexport interface HttpTransportOptions {\n baseUrl: string;\n timeoutMs: number;\n logger: Logger;\n /** Produces auth headers for private methods; absent for public-only clients. */\n authHeaders?: () => Promise<Record<string, string>>;\n}\n\n/**\n * REST transport: each method is POSTed to `<baseUrl>/<method>` with the\n * params object as the JSON body; the response body is the JSON-RPC\n * response envelope. Private methods carry signed auth headers.\n */\nexport class HttpTransport {\n constructor(private readonly options: HttpTransportOptions) {}\n\n async send<M extends RpcMethod>(method: M, params: ParamsOf<M>): Promise<ResultFor<M>> {\n assertPublicMethod(method);\n const { baseUrl, timeoutMs, logger, authHeaders } = this.options;\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n // The API rejects UA-less requests; browsers ignore this\n // (the browser UA is a forbidden header) and send their own.\n 'user-agent': `derive-ts/${SDK_VERSION}`,\n };\n if (method.startsWith('private/')) {\n if (!authHeaders) {\n throw new Error(`${method} requires authentication — construct the client with a wallet or session key`);\n }\n Object.assign(headers, await authHeaders());\n }\n\n logger('debug', `HTTP ${method}`, params);\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/${method}`, {\n method: 'POST',\n headers,\n body: JSON.stringify(params),\n // Never follow a redirect: it would forward the signed X-Lyra*\n // auth headers to the redirect target.\n redirect: 'error',\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (cause) {\n if (cause instanceof DOMException && cause.name === 'TimeoutError') {\n throw new DeriveTimeoutError(`${method}: no response within ${timeoutMs}ms`);\n }\n throw cause;\n }\n\n let body: RawRpcResponse;\n try {\n body = (await response.json()) as RawRpcResponse;\n } catch {\n throw new Error(`${method}: non-JSON response with HTTP status ${response.status}`);\n }\n return unwrapResponse<ResultFor<M>>(method, body);\n }\n}\n","import type { Logger } from '../config/types';\nimport { DeriveConnectionError, DeriveTimeoutError } from '../errors';\nimport { assertPublicMethod, unwrapResponse, type RawRpcResponse } from './jsonrpc';\nimport type { ParamsOf, ResultFor, RpcMethod } from '../types';\n\n/** The subset of the WebSocket interface the SDK relies on; satisfied by both `ws` and the browser WebSocket. */\nexport interface WebSocketLike {\n readonly readyState: number;\n send(data: string): void;\n close(code?: number, reason?: string): void;\n onopen: ((event?: unknown) => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n onclose: ((event: { code?: number; reason?: unknown }) => void) | null;\n onerror: ((event: unknown) => void) | null;\n}\n\nexport type WebSocketFactory = (url: string) => WebSocketLike | Promise<WebSocketLike>;\n\nconst WS_OPEN = 1;\nconst RECONNECT_MAX_ATTEMPTS = 5;\nconst RECONNECT_BASE_DELAY_MS = 500;\nconst RECONNECT_MAX_DELAY_MS = 8_000;\n\nasync function defaultWebSocketFactory(url: string): Promise<WebSocketLike> {\n const globalWs = (globalThis as { WebSocket?: new (url: string) => WebSocketLike }).WebSocket;\n if (globalWs) return new globalWs(url);\n const { WebSocket: nodeWs } = await import('ws');\n return new nodeWs(url) as unknown as WebSocketLike;\n}\n\nexport interface WsTransportOptions {\n url: string;\n timeoutMs: number;\n logger: Logger;\n wsFactory?: WebSocketFactory;\n}\n\ninterface PendingRequest {\n method: string;\n resolve: (raw: RawRpcResponse) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * WebSocket transport with id-correlated request/response handling and\n * automatic reconnect. On an unexpected close every in-flight request is\n * rejected (mutating requests are never silently replayed); after the\n * socket is re-established `onReconnected` lets the client re-login and\n * re-subscribe.\n */\nexport class WsTransport {\n /** Set by the subscriptions layer; receives every pub/sub notification. */\n onNotification?: (channel: string, data: unknown) => void;\n /** Set by the client; runs after an automatic reconnect succeeds. */\n onReconnected?: () => Promise<void>;\n\n private socket?: WebSocketLike;\n private nextId = 0;\n private readonly pending = new Map<number, PendingRequest>();\n private intentionallyClosed = false;\n private connecting?: Promise<void>;\n\n constructor(private readonly options: WsTransportOptions) {}\n\n get connected(): boolean {\n return this.socket?.readyState === WS_OPEN;\n }\n\n async connect(): Promise<void> {\n if (this.connected) return;\n // Coalesce concurrent connect() calls so they can't open rival sockets.\n this.connecting ??= (async () => {\n this.intentionallyClosed = false;\n this.socket = await this.open();\n })().finally(() => {\n this.connecting = undefined;\n });\n return this.connecting;\n }\n\n private async open(): Promise<WebSocketLike> {\n const factory = this.options.wsFactory ?? defaultWebSocketFactory;\n const socket = await factory(this.options.url);\n await new Promise<void>((resolve, reject) => {\n if (socket.readyState === WS_OPEN) return resolve();\n socket.onopen = () => resolve();\n socket.onerror = (event) =>\n reject(new DeriveConnectionError(`failed to connect to ${this.options.url}`, { cause: event }));\n });\n socket.onerror = (event) => this.options.logger('warn', 'websocket error', event);\n socket.onmessage = (event) => this.handleMessage(event.data);\n socket.onclose = (event) => this.handleClose(event.code);\n return socket;\n }\n\n async send<M extends RpcMethod>(method: M, params: ParamsOf<M>): Promise<ResultFor<M>> {\n assertPublicMethod(method);\n if (!this.connected) {\n throw new DeriveConnectionError('websocket is not connected — call connect() first');\n }\n const id = ++this.nextId;\n const raw = await new Promise<RawRpcResponse>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n reject(new DeriveTimeoutError(`${method}: no response within ${this.options.timeoutMs}ms`));\n }, this.options.timeoutMs);\n this.pending.set(id, { method, resolve, reject, timer });\n this.options.logger('debug', `WS ${method}`, params);\n try {\n this.socket!.send(JSON.stringify({ id, method, params }));\n } catch (cause) {\n clearTimeout(timer);\n this.pending.delete(id);\n reject(new DeriveConnectionError('websocket send failed', { cause }));\n }\n });\n return unwrapResponse<ResultFor<M>>(method, raw);\n }\n\n async close(): Promise<void> {\n this.intentionallyClosed = true;\n const socket = this.socket;\n if (!socket || socket.readyState !== WS_OPEN) return;\n this.rejectAllPending(new DeriveConnectionError('websocket closed by client'));\n await new Promise<void>((resolve) => {\n // Resolve on the close frame, but don't hang if the peer is slow to\n // complete the closing handshake — detach handlers and move on.\n const timer = setTimeout(() => {\n socket.onclose = null;\n socket.onerror = null;\n resolve();\n }, 1_000);\n socket.onclose = () => {\n clearTimeout(timer);\n resolve();\n };\n socket.close();\n });\n }\n\n private handleMessage(payload: unknown): void {\n let message: RawRpcResponse & { method?: string; params?: { channel?: string; data?: unknown } };\n try {\n message = JSON.parse(String(payload));\n } catch {\n this.options.logger('warn', 'ignoring non-JSON websocket message');\n return;\n }\n if (typeof message.id === 'number' && this.pending.has(message.id)) {\n const request = this.pending.get(message.id)!;\n this.pending.delete(message.id);\n clearTimeout(request.timer);\n request.resolve(message);\n return;\n }\n if (message.method === 'subscription' && message.params?.channel) {\n this.onNotification?.(message.params.channel, message.params.data);\n return;\n }\n this.options.logger('debug', 'unmatched websocket message', message);\n }\n\n private handleClose(code?: number): void {\n this.rejectAllPending(new DeriveTimeoutError('websocket closed before a response was received'));\n if (this.intentionallyClosed) return;\n this.options.logger('warn', `websocket closed unexpectedly (code ${code}); reconnecting`);\n void this.reconnect();\n }\n\n private rejectAllPending(error: Error): void {\n for (const request of this.pending.values()) {\n clearTimeout(request.timer);\n request.reject(error);\n }\n this.pending.clear();\n }\n\n private async reconnect(): Promise<void> {\n for (let attempt = 1; attempt <= RECONNECT_MAX_ATTEMPTS; attempt++) {\n const delay = Math.min(RECONNECT_BASE_DELAY_MS * 2 ** (attempt - 1), RECONNECT_MAX_DELAY_MS);\n await new Promise((resolve) => setTimeout(resolve, delay));\n if (this.intentionallyClosed) return;\n let socket: WebSocketLike | undefined;\n try {\n socket = await this.open();\n this.socket = socket;\n await this.onReconnected?.();\n this.options.logger('info', `websocket reconnected after ${attempt} attempt(s)`);\n return;\n } catch (error) {\n // Close the socket opened this attempt so a failing onReconnected\n // (e.g. re-login) can't leave an orphaned live socket behind.\n try {\n socket?.close();\n } catch {\n /* already closing */\n }\n this.options.logger('warn', `reconnect attempt ${attempt}/${RECONNECT_MAX_ATTEMPTS} failed`, error);\n }\n }\n this.options.logger('error', 'websocket reconnection failed; connection abandoned');\n }\n}\n","import type { ChannelDataOf, ChannelParamsOf, ChannelSchemaMap, ChannelTemplate } from '../types';\n\n/**\n * A concrete channel name carrying its notification payload type as a\n * phantom parameter, so `Subscriptions.subscribe`/`stream` can type the\n * data without the caller restating it.\n */\nexport interface TypedChannel<Data> {\n name: string;\n /** Phantom type marker — never present at runtime. */\n readonly __data?: Data;\n}\n\n/**\n * Builds a concrete channel name from a template in the generated\n * `ChannelSchemaMap`, e.g.\n * `channel('orderbook.{instrument_name}.{group}.{depth}', { instrument_name: 'ETH-PERP', group: '1', depth: '10' })`\n * → `orderbook.ETH-PERP.1.10`. Channel address params are always\n * strings on the wire, so values are stringified even when numeric.\n * Missing, empty, and unknown params are rejected.\n */\nexport function channel<T extends ChannelTemplate>(\n template: T,\n params: ChannelParamsOf<ChannelSchemaMap[T]>,\n): TypedChannel<ChannelDataOf<ChannelSchemaMap[T]>> {\n const values = params as Record<string, unknown>;\n const used = new Set<string>();\n const name = template.replace(/\\{(\\w+)\\}/g, (_token, key: string) => {\n const value = values[key];\n if (value === undefined || value === null || String(value) === '') {\n throw new Error(`channel ${template}: missing value for {${key}}`);\n }\n used.add(key);\n return String(value);\n });\n for (const key of Object.keys(values)) {\n if (!used.has(key)) {\n throw new Error(`channel ${template}: unknown param '${key}'`);\n }\n }\n return { name };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,cAAc;;;ACA3B,IAAAA,kBAAwC;;;ACAxC,IAAAC,iBAAkD;;;ACQ3C,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AACF;;;ACVO,IAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACLO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,QAAgB,OAA0D;AACpF;AAAA,MACE,GAAG,MAAM,MAAM,MAAM,IAAI,KAAK,MAAM,OAAO,GACzC,MAAM,SAAS,SAAY,WAAM,KAAK,UAAU,MAAM,IAAI,CAAC,KAAK,EAClE;AAAA,IACF;AACA,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OA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,QAAgB;AACnE,UAAM,QAAQ,OAAO,GAAG;AACxB,QAAI,UAAU,UAAa,UAAU,QAAQ,OAAO,KAAK,MAAM,IAAI;AACjE,YAAM,IAAI,MAAM,WAAW,QAAQ,wBAAwB,GAAG,GAAG;AAAA,IACnE;AACA,SAAK,IAAI,GAAG;AACZ,WAAO,OAAO,KAAK;AAAA,EACrB,CAAC;AACD,aAAW,OAAO,OAAO,KAAK,MAAM,GAAG;AACrC,QAAI,CAAC,KAAK,IAAI,GAAG,GAAG;AAClB,YAAM,IAAI,MAAM,WAAW,QAAQ,oBAAoB,GAAG,GAAG;AAAA,IAC/D;AAAA,EACF;AACA,SAAO,EAAE,KAAK;AAChB;","names":["import_ethers","import_ethers","import_ethers","import_ethers","assertE12Precision","import_ethers","import_ethers","domainSeparator","import_ethers","import_ethers","import_ethers","import_ethers","import_ethers","uintWord","import_ethers","import_ethers","import_ethers","import_ethers","module","import_ethers","import_ethers","import_ethers","import_ethers","authHeaders"]}