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:
| Field | Type | Meaning |
|---|---|---|
builder_address | string | The builder's dydx1... address, where the fee is paid |
fee_ppm | uint32 | The 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
- 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).
- Show your users the fee before they sign: it is part of their cost.
- Set
builder_code_parameterson every order you build, short-term, long-term and conditional. Cancels carry no code. - Reconcile from the indexer:
/v4/ordersreturns each order'sbuilderAddressandfeePpm, and/v4/fillseach fill'sbuilderAddressandbuilderFee(indexer HTTP API). On chain, each fill'smatchevent 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);
});# The market buy of market_order.py, 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... python builder_code.py
import asyncio
import os
import random
import httpx
from dydx_v4_client import OrderFlags
from dydx_v4_client.key_pair import KeyPair
from dydx_v4_client.network import NodeConfig, secure_channel
from dydx_v4_client.node.client import NodeClient
from dydx_v4_client.node.message import builder_code_parameters, order, order_id
from dydx_v4_client.wallet import Wallet
from v4_proto.dydxprotocol.clob.order_pb2 import Order
GRPC = os.environ.get("FA_GRPC", "grpc.testnet.firstaccess.exchange:443")
REST = os.environ.get("FA_REST", "https://api.testnet.firstaccess.exchange")
TICKER = os.environ.get("FA_TICKER", "TESTCOPERP-USD")
def accepted(response):
# A synchronous broadcast returns CheckTx's answer: code 0 is accepted.
if response.tx_response.code != 0:
raise RuntimeError(response.tx_response.raw_log)
return response.tx_response.txhash
def get(path):
r = httpx.get(REST + path)
r.raise_for_status()
return r.json()
async def main():
# USDC is asset 0; its denom is read from the chain.
usdc_denom = get("/dydxprotocol/assets/asset/0")["asset"]["denom"]
node = await NodeClient.connect(
NodeConfig(
"firstaccess-testnet-1",
chaintoken_denom="adv4tnt",
usdc_denom=usdc_denom,
channel=secure_channel(GRPC),
)
)
# dydx_v4_client prices gas only in dYdX's own USDC denom or the chain
# token, so fees are paid in the chain token (adv4tnt).
node.builder.denomination = "adv4tnt"
mnemonic = os.environ["MNEMONIC"]
address = Wallet(KeyPair.from_mnemonic(mnemonic), 0, 0).address
wallet = await Wallet.from_mnemonic(node, mnemonic, address)
perps = get("/dydxprotocol/perpetuals/perpetual?pagination.limit=1000")["perpetual"]
perp = next(p["params"] for p in perps if p["params"]["ticker"] == TICKER)
books = get("/dydxprotocol/clob/clob_pair?pagination.limit=1000")["clob_pair"]
book = next(c for c in books if c["perpetual_clob_metadata"]["perpetual_id"] == perp["id"])
index = int(get(f"/dydxprotocol/prices/market/{perp['market_id']}")["market_price"]["price"])
# 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.
tick = int(book["subticks_per_tick"])
band_ppm = perp["chain_market"].get("price_band_ppm") or 20_000
half_width = max(-(-index * band_ppm // 1_000_000), tick)
worst_price = (index + half_width) // tick * tick
height = await node.latest_block_height()
oid = order_id(address, perp["id"] + 1, random.randint(0, 2**32 - 1), book["id"], OrderFlags.SHORT_TERM)
sent = await node.place_order(
wallet,
order(
oid,
Order.Side.SIDE_BUY,
quantums=1,
subticks=worst_price,
time_in_force=Order.TimeInForce.TIME_IN_FORCE_IOC,
reduce_only=False,
# 500 ppm = 0.05% of each fill's notional; at most 10,000 (1%).
builder_code_parameters=builder_code_parameters(os.environ["BUILDER"], 500),
twap_parameters=None,
order_router_address=None,
good_til_block=height + 10,
),
)
print("sent", oid.client_id, "worst price", worst_price / 1e6, accepted(sent))
asyncio.run(main())# A short-term order with a builder code from the chain's CLI:
# place-order owner subaccount client-id clob-pair-id side(1 buy, 2 sell) quantums subticks good-til-block
dydxprotocold tx clob place-order dydx1... 1 42 0 1 1 55000000 123456 \
--builder-address dydx1... --builder-ppm 500 \
--from KEY --chain-id firstaccess-testnet-1 --node https://rpc.testnet.firstaccess.exchange:443Both 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.