Testnet quickstart
The testnet runs the full chain with test tokens only. You need a browser for the app, or
curl and a client library for the API.
1. Make a key
Open the trading app at app.testnet.firstaccess.exchange and go to Account. Create a key, or import a 24-word recovery phrase you already have.
- The app makes the key in your browser with cosmjs and keeps the phrase in the browser's
localStorage, unencrypted. Anyone with access to that browser profile can read it. Use it for the testnet only. - Addresses start with
dydx. The key is derived on the Cosmos pathm/44'/118'/0'/0/0, as dYdX's CLI and clients derive it, so the same phrase gives the same address in the app, indydxprotocold keys add --recover, in@dydxprotocol/v4-client-jsand indydx-v4-client.
2. Fund it from the faucet
The faucet sends $10,000 of test USDC and 5 native tokens to an address, at most once a day per address and per client IP (and a few times a day per network, and a fixed number of drips a day in all). Press Faucet on the Account page, or call it:
curl -s -X POST https://app.testnet.firstaccess.exchange/faucet/drip \
-H 'content-type: application/json' \
-d '{"address": "dydx1..."}'
# {"txhash": "...", "usdc": "10000000000", "native": "5000000000000000000"}GET https://app.testnet.firstaccess.exchange/faucet/status shows the faucet's address, its
balances, the amount of a drip and the window. The faucet allows a few requests a minute per
IP; a second drip within the day is refused. If the faucet answers that the transfer was sent
but isn't confirmed yet, check your balance before asking again: that address and network count
as served.
The native token (adv4tnt, 18 decimals) pays transfer fees. Order and cancel transactions
are free.
3. Deposit into a subaccount
The faucet pays your wallet (the bank balance of your address). Trading uses subaccounts: numbered accounts under your address that hold USDC and positions. Every chain market is isolated, so each market is traded from its own subaccount (accounts and subaccounts). The app uses subaccount perpetual id + 1 for each market and offers a deposit in the order ticket.
4. Place an order
Open the company (TESTCO on the testnet), pick the perpetual or an IPO expiry, and use the
order ticket: side, size in contracts, a limit price, and long-term (good until a time) or
short-term (good for a few blocks). The ticket shows the price band, the collateral the order
needs and what the subaccount holds.
By API, the same steps are a deposit and a MsgPlaceOrder:
// Deposits test USDC into a subaccount, rests a long-term post-only bid for
// one contract of TESTCOPERP-USD 1% under the index, then cancels it.
// Run: MNEMONIC="word1 ... word24" npx tsx place-order.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);
// The market: its perpetual, its order book (clob pair) and its oracle price.
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}`);
// Chain markets: one quantum is one contract; subticks are micro-dollars a
// contract; the tick is the book's subticks_per_tick: 10,000 ($0.01), or
// 1,000 ($0.001) on a binary's book.
const tick = BigInt(book.subticks_per_tick);
const index = BigInt(market_price.price);
const bid = ((index * 99n) / 100n / tick) * tick;
// One subaccount per chain market (they are isolated). The trading app uses
// perpetual id + 1, so it shows this order too.
const subaccount = SubaccountInfo.forLocalWallet(wallet, perp.params.id + 1);
// $100 of USDC (asset 0, in quote quantums: micro-USDC) from the wallet
// into the subaccount. Transfers pay a gas fee. The deposit is broadcast
// synchronously, so wait for its block: the long-term order after it
// reads the account's sequence.
const sequence = async () =>
Number((await get(`/cosmos/auth/v1beta1/accounts/${wallet.address}`)).account.sequence);
const before = await sequence();
await client.post.deposit(subaccount, 0, Long.fromNumber(100_000_000));
while ((await sequence()) === before) await new Promise((r) => setTimeout(r, 500));
const clientId = Math.floor(Math.random() * 2 ** 32);
const goodTilBlockTime = Math.floor(Date.now() / 1000) + 24 * 3600;
await client.post.placeOrder(
subaccount,
clientId,
book.id,
Order_Side.SIDE_BUY,
Long.fromNumber(1), // quantums: contracts
Long.fromString(bid.toString()), // subticks
Order_TimeInForce.TIME_IN_FORCE_POST_ONLY,
OrderFlags.LONG_TERM,
false, // reduce-only: short-term IOC orders only
undefined, // good-til-block: short-term orders only
goodTilBlockTime,
);
console.log('placed', clientId, 'at', Number(bid) / 1e6);
await client.post.cancelOrder(
subaccount,
clientId,
OrderFlags.LONG_TERM,
book.id,
undefined,
goodTilBlockTime,
);
console.log('cancelled');
}
main().catch((e) => {
console.error(e);
process.exit(1);
});# Deposits test USDC into a subaccount, rests a long-term post-only bid for
# one contract of TESTCOPERP-USD 1% under the index, then cancels it.
# Run: MNEMONIC="word1 ... word24" python place_order.py
import asyncio
import os
import random
import time
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 order, order_id, subaccount
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
async def in_block(node, address, sequence):
# Waits until the transaction sent at `sequence` is in a block: the
# client reads the account's sequence for the next one.
while (await node.get_account(address)).sequence == sequence:
await asyncio.sleep(0.5)
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)
# The market: its perpetual, its order book (clob pair), its oracle price.
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"])
# Chain markets: one quantum is one contract; subticks are micro-dollars
# a contract; the tick is the book's subticks_per_tick: 10,000 ($0.01), or
# 1,000 ($0.001) on a binary's book.
tick = int(book["subticks_per_tick"])
bid = index * 99 // 100 // tick * tick
# One subaccount per chain market; the trading app uses perpetual id + 1.
number = perp["id"] + 1
# $100 of USDC (asset 0, in quote quantums: micro-USDC) into the
# subaccount. Transfers pay a gas fee, here in the chain token.
sequence = (await node.get_account(address)).sequence
accepted(await node.deposit(wallet, address, subaccount(address, number), 0, 100_000_000))
await in_block(node, address, sequence)
oid = order_id(address, number, random.randint(0, 2**32 - 1), book["id"], OrderFlags.LONG_TERM)
good_til_block_time = int(time.time()) + 24 * 3600
placed = await node.place_order(
wallet,
order(
oid,
Order.Side.SIDE_BUY,
quantums=1,
subticks=bid,
time_in_force=Order.TimeInForce.TIME_IN_FORCE_POST_ONLY,
reduce_only=False,
builder_code_parameters=None,
twap_parameters=None,
order_router_address=None,
good_til_block_time=good_til_block_time,
),
)
print("placed", oid.client_id, "at", bid / 1e6, accepted(placed))
await in_block(node, address, sequence + 1)
cancelled = await node.cancel_order(wallet, oid, good_til_block_time=good_til_block_time)
print("cancelled", accepted(cancelled))
asyncio.run(main())Install the clients with npm install @dydxprotocol/v4-client-js@3.6.0 long@5.3.2 tsx@4.21.0
(in a CommonJS project) or pip install dydx-v4-client==1.1.6, and run with
MNEMONIC="..." npx tsx place-order.ts or python place_order.py.
Placing and cancelling orders explains each field.
Endpoints
| Chain id | firstaccess-testnet-1 |
| RPC (CometBFT) | https://rpc.testnet.firstaccess.exchange |
| REST (Cosmos SDK and dYdX modules) | https://api.testnet.firstaccess.exchange |
| gRPC | grpc.testnet.firstaccess.exchange:443 (TLS) |
| Indexer HTTP | https://indexer.testnet.firstaccess.exchange/v4 |
| Indexer WebSocket | wss://indexer.testnet.firstaccess.exchange/v4/ws |
| Explorer | https://explorer.testnet.firstaccess.exchange |
| Trading app and faucet | https://app.testnet.firstaccess.exchange, /faucet/ |
The public RPC answers a fixed list of methods: mempool queries (unconfirmed_txs,
num_unconfirmed_txs) are refused and it has no WebSocket, so pending transactions are not
public. Endpoints has the details.