Skip to content
markpaper

src/transport/weights.test.ts

v0.2.0 · 2.7 KB

Download file
import { describe, expect, it } from 'vitest';
import {
  chunkProductIds,
  DEFAULT_EXECUTE_WEIGHT,
  DEFAULT_QUERY_WEIGHT,
  EXECUTE_WEIGHTS,
  executeAction,
  executeWeight,
  QUERY_WEIGHTS,
  queryWeight,
} from './weights.js';

describe('queryWeight', () => {
  it('uses the documented weights per type', () => {
    expect(queryWeight({ type: 'contracts' })).toBe(1);
    expect(queryWeight({ type: 'market_price', product_id: 2 })).toBe(1);
    expect(queryWeight({ type: 'symbols', product_type: 'perp' })).toBe(2);
    expect(queryWeight({ type: 'subaccount_info', subaccount: '0x' })).toBe(2);
    expect(queryWeight({ type: 'nonces', address: '0x' })).toBe(2);
    expect(queryWeight({ type: 'linked_signer', subaccount: '0x' })).toBe(5);
    expect(queryWeight({ type: 'all_products' })).toBe(5);
    expect(QUERY_WEIGHTS.symbols).toBe(2);
  });

  it('orders weighs 2 per product id, market_prices ~1 per id', () => {
    expect(queryWeight({ type: 'orders', sender: '0x', product_ids: [2, 8, 18] })).toBe(6);
    expect(queryWeight({ type: 'orders', sender: '0x', product_ids: [] })).toBe(2);
    expect(queryWeight({ type: 'orders', sender: '0x', product_ids: new Array(40).fill(2) })).toBe(80);
    expect(queryWeight({ type: 'market_prices', product_ids: [2, 8] })).toBe(2);
    expect(queryWeight({ type: 'market_prices', product_ids: [] })).toBe(1);
  });

  it('falls back to the default weight for undocumented types', () => {
    expect(queryWeight({ type: 'fee_rates' })).toBe(DEFAULT_QUERY_WEIGHT);
  });
});

describe('executeWeight / executeAction', () => {
  it('reads the single action key', () => {
    expect(executeAction({ place_order: {} })).toBe('place_order');
    expect(executeAction({})).toBeUndefined();
    expect(executeAction({ a: 1, b: 2 })).toBeUndefined();
    expect(executeWeight({ place_order: {} })).toBe(1);
    expect(executeWeight({ cancel_orders: {} })).toBe(1);
    expect(executeWeight({ link_signer: {} })).toBe(30);
    expect(executeWeight({ something_else: {} })).toBe(DEFAULT_EXECUTE_WEIGHT);
    expect(EXECUTE_WEIGHTS.link_signer).toBe(30);
  });
});

describe('chunkProductIds', () => {
  it('chunks by an explicit caller-selected size', () => {
    const ids = Array.from({ length: 95 }, (_, i) => i + 1);
    const chunks = chunkProductIds(ids, 40);
    expect(chunks.map((c) => c.length)).toEqual([40, 40, 15]);
    expect(chunks.flat()).toEqual(ids);
    expect(chunkProductIds([], 40)).toEqual([]);
    expect(chunkProductIds([1, 2, 3], 2)).toEqual([[1, 2], [3]]);
    expect(() => (chunkProductIds as unknown as (ids: readonly number[]) => number[][])([1])).toThrow(
      'chunk size must be a positive integer',
    );
    expect(() => chunkProductIds([1], 0)).toThrow(RangeError);
  });
});
All files