Skip to content
First Access Exchange

Builder codes

A builder is anyone who sends orders for others: a trading front end, a wallet, a bot. A builder code is dYdX's mechanism for it to charge a fee for that: each order carries the builder's address and a fee rate, and the chain pays the fee to the builder on every fill. It works on every market, the chain markets included. No registration or governance proposal is needed. The exchange's own trading app sets no builder code.

The field

Order.builder_code_parameters (order field 13) is a BuilderCodeParameters:

FieldTypeMeaning
builder_addressstringThe builder's dydx1... address, where the fee is paid
fee_ppmuint32The fee in ppm of each fill's notional: above 0 and at most 10,000 (1%)

The chain refuses an order whose builder address isn't a valid bech32 address, or whose fee is 0 or above 10,000 ppm (MaxBuilderCodeFeePpm): "builder code fee ppm must be in the range (0, 10000]".

How the fee is paid

On each fill of an order with a builder code:

  • the fee is fee_ppm × the fill's notional (contracts × price, in quote quantums), rounded up to a quote quantum;
  • it is charged to the order's subaccount, on top of the trading fee (unlike revenue share, which splits the exchange's fee);
  • it is paid in USDC from the market's collateral pool to the builder's wallet (its bank balance, not a subaccount);
  • the maker's and the taker's codes are each charged on their own side: a fill between two orders with codes pays both builders;
  • a liquidation order carries no code;
  • while dYdX's withdrawal gate for that market's collateral pool is on (a subaccount with negative collateral, or a chain outage), builder fees are waived, since they leave the pool like a withdrawal.

Example: an order with fee_ppm 500 buys 1 contract of the perpetual at $50.52. The notional is $50.52, so the builder receives 50,520,000 × 500 / 1,000,000 = 25,260 quote quantums, $0.02526, and the trader pays that besides the trading fee.

Integrating

  1. Use a builder address whose key you control: fees accumulate in its wallet, and you withdraw them with an ordinary bank send (or bridge them out).
  2. Show your users the fee before they sign: it is part of their cost.
  3. Set builder_code_parameters on every order you build, short-term, long-term and conditional. Cancels carry no code.
  4. Reconcile from the indexer: /v4/orders returns each order's builderAddress and feePpm, and /v4/fills each fill's builderAddress and builderFee (indexer HTTP API). On chain, each fill's match event carries both sides' builder addresses and fees.
// The market buy of market-order.ts, sent with a builder code: on each fill
// the chain moves fee_ppm of the fill's notional from the trader's
// subaccount to BUILDER's wallet, on top of the exchange's trading fee.
// Run: MNEMONIC="..." BUILDER=dydx1... npx tsx builder-code.ts
import Long from 'long';
import {
  BECH32_PREFIX,
  LocalWallet,
  OrderFlags,
  Order_Side,
  Order_TimeInForce,
  SubaccountInfo,
  ValidatorClient,
  ValidatorConfig,
} from '@dydxprotocol/v4-client-js';
 
const RPC = process.env.FA_RPC ?? 'https://rpc.testnet.firstaccess.exchange';
const REST = process.env.FA_REST ?? 'https://api.testnet.firstaccess.exchange';
const TICKER = process.env.FA_TICKER ?? 'TESTCOPERP-USD';
 
const get = async (path: string) => {
  const r = await fetch(REST + path);
  if (!r.ok) throw new Error(`${path}: ${r.status}`);
  return r.json();
};
 
async function main() {
  // USDC is asset 0; its denom is read from the chain.
  const { asset } = await get('/dydxprotocol/assets/asset/0');
  const client = await ValidatorClient.connect(
    new ValidatorConfig(RPC, 'firstaccess-testnet-1', {
      USDC_DENOM: asset.denom,
      USDC_DECIMALS: 6,
      CHAINTOKEN_DENOM: 'adv4tnt',
      CHAINTOKEN_DECIMALS: 18,
    }),
  );
  const wallet = await LocalWallet.fromMnemonic(process.env.MNEMONIC!, BECH32_PREFIX);
 
  const { perpetual } = await get('/dydxprotocol/perpetuals/perpetual?pagination.limit=1000');
  const perp = perpetual.find((p: any) => p.params.ticker === TICKER);
  const { clob_pair } = await get('/dydxprotocol/clob/clob_pair?pagination.limit=1000');
  const book = clob_pair.find((c: any) => c.perpetual_clob_metadata.perpetual_id === perp.params.id);
  const { market_price } = await get(`/dydxprotocol/prices/market/${perp.params.market_id}`);
 
  // The band the chain prices orders and fills in: I +/- price_band_ppm of I
  // (at least a tick). A buy priced above it is refused.
  const tick = BigInt(book.subticks_per_tick);
  const index = BigInt(market_price.price);
  const bandPpm = BigInt(perp.params.chain_market.price_band_ppm || 20_000);
  let halfWidth = (index * bandPpm + 999_999n) / 1_000_000n;
  if (halfWidth < tick) halfWidth = tick;
  const worstPrice = ((index + halfWidth) / tick) * tick;
 
  const height = await client.get.latestBlockHeight();
  const subaccount = SubaccountInfo.forLocalWallet(wallet, perp.params.id + 1);
  const clientId = Math.floor(Math.random() * 2 ** 32);
  await client.post.placeOrder(
    subaccount,
    clientId,
    book.id,
    Order_Side.SIDE_BUY,
    Long.fromNumber(1),
    Long.fromString(worstPrice.toString()),
    Order_TimeInForce.TIME_IN_FORCE_IOC,
    OrderFlags.SHORT_TERM,
    false,
    height + 10,
    undefined, // good-til-block-time
    undefined, // client metadata
    undefined, // condition type
    undefined, // trigger subticks
    undefined, // TWAP parameters
    { builderAddress: process.env.BUILDER!, feePpm: 500 }, // 0.05%, at most 10,000 (1%)
  );
  console.log('sent', clientId, 'worst price', Number(worstPrice) / 1e6);
}
 
main().catch((e) => {
  console.error(e);
  process.exit(1);
});

Both examples are run against a local node in this site's tests, which check that the builder's wallet receives the fee.

Order routers

Order.order_router_address (field 14) is a different mechanism: dYdX's revenue share, which pays a router a share of the exchange's own fee. A router address must first be given a share by governance (x/revshare); an order naming an address without one is refused.