### Copy Example Service Template Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/README.md Copies the example service template to create a new service. Update package.json, README.md, and run pnpm install. ```sh cp -r services/example-service services/ ``` -------------------------------- ### Copy Example Package Template Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/README.md Copies the example package template to create a new package. Remember to update package.json, README.md, and run pnpm install. ```sh cp -r packages/example-package packages/ ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/README.md Run this command to install all necessary project dependencies. ```bash make install ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/README.md Installs all project dependencies using pnpm. This command should be run after cloning the repository or updating packages. ```sh pnpm install ``` -------------------------------- ### Subscribe to Websocket Channels Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/README.md Example using interactive-websocket-cli (wscli) to connect to a local indexer and subscribe to the v4_trades channel for BTC-USD. Other subscription examples are provided. ```bash wscli connect http://localhost:3003 { "type": "subscribe", "channel": "v4_trades", "id": "BTC-USD" } ``` ```json { "type": "subscribe", "channel": "v4_candles", "id": "BTC-USD/1MIN" } ``` ```json { "type": "subscribe", "channel": "v4_markets" } ``` ```json { "type": "subscribe", "channel": "v4_orderbook", "id": "BTC-USD" } ``` ```json { "type": "subscribe", "channel": "v4_subaccounts", "id": "address/0" } ``` ```json { "type": "subscribe", "channel": "v4_block_height" } ``` -------------------------------- ### Start Local Network Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/README.md Starts a local dYdX Chain network. This command first compiles changes into a docker image and then runs the local network. It resets the chain to genesis. Use `make localnet-startd` to run headlessly. ```bash make localnet-start ``` -------------------------------- ### Example Output of Proto Event Deserializer Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/scripts/debugging/README.md Presents an example of the script's output, showing the file being processed and deserialized event details including message type and formatted proto fields. ```text Reading events from: events.json --- Event Index: 23, Transaction Index: 0, Subtype: order_fill --- Message Type: OrderFillEventV1 maker_order: client_id:1622718733 clob_pair_id:27 > side:SIDE_BUY quantums:2266000000 subticks:710000000 good_til_block:1044 > order: client_id:507483497 clob_pair_id:27 > side:SIDE_SELL quantums:2271000000 subticks:709000000 good_til_block:1048 > fill_amount:2261000000 maker_fee:-779 taker_fee:3191 total_filled_maker:2261000000 total_filled_taker:2271000000 ``` -------------------------------- ### Fetch Orders using Python Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Use this Python snippet to fetch order data from the dYdX v4 indexer. Ensure you have the 'requests' library installed. The example uses a testnet base URL. ```python import requests baseURL = 'https://indexer.v4testnet.dydx.exchange/v4' r = requests.get(f'{baseURL}/orders/parentSubaccountNumber', params={ 'address': 'string', 'parentSubaccountNumber': '0.1' }, headers = headers) print(r.json()) ``` -------------------------------- ### Get Historical Funding Response Example Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Example JSON response for the GetHistoricalFunding endpoint, showing the structure of historical funding data. ```json { "historicalFunding": [ { "ticker": "string", "rate": "string", "price": "string", "effectiveAt": "string", "effectiveAtHeight": "string" } ] } ``` -------------------------------- ### Run Containerized Environment Source: https://github.com/dydxprotocol/v4-chain/blob/main/e2e-testing/README.md Starts a containerized environment with network and Indexer services. Run this in one terminal. ```bash ./run-containerized-env.sh ``` -------------------------------- ### Install pnpm Package Manager Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/README.md Installs the pnpm package manager globally. pnpm is recommended for its efficiency with monorepos. ```sh npm i -g pnpm@6 ``` -------------------------------- ### Install and Configure Node Version Manager Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/README.md Installs and configures Node Version Manager (nvm) for managing Node.js versions. Ensure nvm is installed and active before proceeding. ```sh nvm install nvm use nvm alias default $(nvm version) # optional ``` -------------------------------- ### Example Order Response Schema (JSON) Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md This is an example JSON response for a successful order retrieval, detailing the structure and possible values for order properties. ```json { "id": "string", "subaccountId": "string", "clientId": "string", "clobPairId": "string", "side": "BUY", "size": "string", "totalFilled": "string", "price": "string", "type": "LIMIT", "reduceOnly": true, "orderFlags": "string", "goodTilBlock": "string", "goodTilBlockTime": "string", "createdAtHeight": "string", "createdAt": "string", "clientMetadata": "string", "triggerPrice": "string", "builderAddress": "string", "feePpm": "string", "orderRouterAddress": "string", "duration": "string", "interval": "string", "priceTolerance": "string", "timeInForce": "GTT", "status": "OPEN", "postOnly": true, "ticker": "string", "updatedAt": "string", "updatedAtHeight": "string", "subaccountNumber": 0 } ``` -------------------------------- ### Example Market Subscription Response Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/websocket-documentation.md An example JSON response after subscribing to the 'v4_markets' channel. It contains market data for BTC-USD and ETH-USD, including ticker, status, pricing, and margin information. ```json { "type": "subscribed", "connection_id": "6e0af39b-5937-459a-b7ac-cc8abe1049db", "message_id": 1, "channel": "v4_markets", "contents": { "markets": { "BTC-USD": { "clobPairId": "0", "ticker": "BTC-USD", "status": "ACTIVE", "baseAsset": "", "quoteAsset": "", "oraclePrice": "27752.92", "priceChange24H": "0", "volume24H": "63894023.044245577", "trades24H": 143820, "nextFundingRate": "0", "initialMarginFraction": "0.050000", "maintenanceMarginFraction": "0.030000", "basePositionSize": "0", "incrementalPositionSize": "0", "maxPositionSize": "0", "openInterest": "1891.473716288", "atomicResolution": -10, "quantumConversionExponent": -8, "tickSize": "1", "stepSize": "0.000000001", "stepBaseQuantums": 10, "subticksPerTick": 10000 }, "ETH-USD": { "clobPairId": "1", "ticker": "ETH-USD", "status": "ACTIVE", "baseAsset": "", "quoteAsset": "", "oraclePrice": "1808.2", "priceChange24H": "0", "volume24H": "67487133.70842158", "trades24H": 137552, "nextFundingRate": "0", "initialMarginFraction": "0.050000", "maintenanceMarginFraction": "0.030000", "basePositionSize": "0", "incrementalPositionSize": "0", "maxPositionSize": "0", "openInterest": "44027.853711", "atomicResolution": -9, "quantumConversionExponent": -9, "tickSize": "0.01", "stepSize": "0.000001", "stepBaseQuantums": 1000, "subticksPerTick": 10000 } } } } ``` -------------------------------- ### Example 200 Response for GetFills Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md This is an example of a successful response when retrieving fills. It includes details such as page size, total results, and a list of individual fill objects. ```json { "pageSize": 0, "totalResults": 0, "offset": 0, "fills": [ { "id": "string", "side": "BUY", "liquidity": "TAKER", "type": "LIMIT", "market": "string", "marketType": "PERPETUAL", "price": "string", "size": "string", "fee": "string", "affiliateRevShare": "string", "createdAt": "string", "createdAtHeight": "string", "orderId": "string", "clientMetadata": "string", "subaccountNumber": 0, "builderFee": "string", "builderAddress": "string", "orderRouterAddress": "string", "orderRouterFee": "string", "positionSizeBefore": "string", "entryPriceBefore": "string", "positionSideBefore": "string" } ] } ``` -------------------------------- ### Start Local Network Headless Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/README.md Starts a local dYdX Chain network in headless mode. This command first compiles changes into a docker image and then runs the local network. It resets the chain to genesis. ```bash make localnet-startd ``` -------------------------------- ### Example JSON Response for Perpetual Positions Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md This is an example of a successful JSON response when querying for perpetual positions. It includes details for each position such as market, side, size, entry price, and PnL. ```json { "positions": [ { "market": "string", "status": "OPEN", "side": "LONG", "size": "string", "maxSize": "string", "entryPrice": "string", "realizedPnl": "string", "createdAt": "string", "createdAtHeight": "string", "sumOpen": "string", "sumClose": "string", "netFunding": "string", "unrealizedPnl": "string", "closedAt": "string", "exitPrice": "string", "subaccountNumber": 0 } ] } ``` -------------------------------- ### Run Unit Tests with Docker Compose Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/README.md Starts Docker Compose services and runs all unit tests in a separate terminal. This setup is necessary for tests that rely on external services like databases. ```sh # In session / terminal 1 docker-compose up # In session / terminal 2 pnpm run test:all ``` -------------------------------- ### Example JSON Response for Orders Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md This is an example of a successful JSON response when fetching order data. It outlines the structure and possible fields for an order object. ```json [ { "id": "string", "subaccountId": "string", "clientId": "string", "clobPairId": "string", "side": "BUY", "size": "string", "totalFilled": "string", "price": "string", "type": "LIMIT", "reduceOnly": true, "orderFlags": "string", "goodTilBlock": "string", "goodTilBlockTime": "string", "createdAtHeight": "string", "createdAt": "string", "clientMetadata": "string", "triggerPrice": "string", "builderAddress": "string", "feePpm": "string", "orderRouterAddress": "string", "duration": "string", "interval": "string", "priceTolerance": "string", "timeInForce": "GTT", "status": "OPEN", "postOnly": true, "ticker": "string", "updatedAt": "string", "updatedAtHeight": "string", "subaccountNumber": 0 } ] ``` -------------------------------- ### Build and Run Tests Source: https://github.com/dydxprotocol/v4-chain/blob/main/e2e-testing/README.md Builds the project and runs the end-to-end tests. Execute this in a separate terminal after starting the environment. ```bash pnpm build && pnpm test ``` -------------------------------- ### Example: Deserialize Events After Building Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/scripts/debugging/README.md Shows how to deserialize events from a JSON file named 'cloudwatch_events.json' after building the executable. ```bash # Or after building ./deserialize_proto cloudwatch_events.json ``` -------------------------------- ### Get Affiliate Snapshot (Python) Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Retrieves a snapshot of affiliate data. Requires setting up the base URL and headers. ```python import requests headers = { 'Accept': 'application/json' } # For the deployment by DYDX token holders, use # baseURL = 'https://indexer.dydx.trade/v4'aseURL = 'https://indexer.v4testnet.dydx.exchange/v4' r = requests.get(f'{baseURL}/affiliates/snapshot', headers = headers) print(r.json()) ``` -------------------------------- ### Example JSON Response for Perpetual Markets Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md This is an example of a successful JSON response when querying for perpetual markets. It details various market properties such as ticker, status, oracle price, and volume. ```json { "markets": { "property1": { "clobPairId": "string", "ticker": "string", "status": "ACTIVE", "oraclePrice": "string", "priceChange24H": "string", "volume24H": "string", "trades24H": 0, "nextFundingRate": "string", "initialMarginFraction": "string", "maintenanceMarginFraction": "string", "openInterest": "string", "atomicResolution": 0, "quantumConversionExponent": 0, "tickSize": "string", "stepSize": "string", "stepBaseQuantums": 0, "subticksPerTick": 0, "marketType": "CROSS", "openInterestLowerCap": "string", "openInterestUpperCap": "string", "baseOpenInterest": "string", "defaultFundingRate1H": "string" }, "property2": { "clobPairId": "string", "ticker": "string", "status": "ACTIVE", "oraclePrice": "string", "priceChange24H": "string", "volume24H": "string", "trades24H": 0, "nextFundingRate": "string", "initialMarginFraction": "string", "maintenanceMarginFraction": "string", "openInterest": "string", "atomicResolution": 0, "quantumConversionExponent": 0, "tickSize": "string", "stepSize": "string", "stepBaseQuantums": 0, "subticksPerTick": 0, "marketType": "CROSS", "openInterestLowerCap": "string", "openInterestUpperCap": "string", "baseOpenInterest": "string", "defaultFundingRate1H": "string" } } } ``` -------------------------------- ### Get Trades Response Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Example response structure for the Get Trades endpoint, detailing trade information. ```json { "pageSize": 0, "totalResults": 0, "offset": 0, "trades": [ { "id": "string", "side": "BUY", "size": "string", "price": "string", "type": "LIMIT", "createdAt": "string", "createdAtHeight": "string" } ] } ``` -------------------------------- ### Get Transfers Response Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Example response structure for the Get Transfers endpoint, detailing individual transfer information. ```json { "pageSize": 0, "totalResults": 0, "offset": 0, "transfers": [ { "id": "string", "sender": { "subaccountNumber": 0, "address": "string" }, "recipient": { "subaccountNumber": 0, "address": "string" }, "size": "string", "createdAt": "string", "createdAtHeight": "string", "symbol": "string", "type": "TRANSFER_IN", "transactionHash": "string" } ] } ``` -------------------------------- ### Basic Testnet Structure Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/testing/containertest/README.md Illustrates the fundamental structure for writing containerized tests. It shows how to initialize a testnet, start the network, and defer cleanup. Interaction with nodes is demonstrated via accessing a specific node and calling generic Query/BroadcastTx functions. ```go testnet, err := NewTestnet() require.NoError(t, err) // Do things prior to network start if needed, such as setting prices. // Start the network err = testnet.Start() require.NoError(t, err) defer testnet.MustCleanUp() // Interact with the chain node := testnet.Nodes["alice"] Query(node, ...) BroadcastTx(node, ...) ``` -------------------------------- ### Get Historical PNL Response Example Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Example JSON response for the GetHistoricalPnl endpoint, detailing PNL metrics and timestamps. ```json { "pageSize": 0, "totalResults": 0, "offset": 0, "historicalPnl": [ { "equity": "string", "totalPnl": "string", "netTransfers": "string", "createdAt": "string", "blockHeight": "string", "blockTime": "string" } ] } ``` -------------------------------- ### Build Source Code Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/README.md Execute this command to build the project's source code. ```bash make build ``` -------------------------------- ### Get Megavault Positions (Python) Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Use this Python snippet to make a GET request to the /vault/v1/megavault/positions endpoint. It includes setup for headers and base URL, with options for testnet or mainnet. ```python import requests headers = { 'Accept': 'application/json' } # For the deployment by DYDX token holders, use # baseURL = 'https://indexer.dydx.trade/v4' baseURL = 'https://indexer.v4testnet.dydx.exchange/v4' r = requests.get(f'{baseURL}/vault/v1/megavault/positions', headers = headers) print(r.json()) ``` -------------------------------- ### Get Transfers by Parent Subaccount Number (Python) Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Use this snippet to retrieve transfer history associated with a specific parent subaccount. Ensure the 'requests' library is installed. ```python import requests headers = { 'Accept': 'application/json' } # For the deployment by DYDX token holders, use # baseURL = 'https://indexer.dydx.trade/v4'aseURL = 'https://indexer.v4testnet.dydx.exchange/v4' r = requests.get(f'{baseURL}/transfers/parentSubaccountNumber', params={ 'address': 'string', 'parentSubaccountNumber': '0.1' }, headers = headers) print(r.json()) ``` -------------------------------- ### Example: Deserialize Events from File Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/scripts/debugging/README.md Demonstrates how to deserialize events from a JSON file named 'events.json' using the 'make run' command. ```bash # Deserialize events from a specific file make run JSON=events.json ``` -------------------------------- ### Get Funding Payments for Parent Subaccount - JavaScript Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md This JavaScript example shows how to fetch funding payments for a parent subaccount via the dYdX API. Use the appropriate baseURL for your deployment. ```javascript const headers = { 'Accept':'application/json' }; // For the deployment by DYDX token holders, use // const baseURL = 'https://indexer.dydx.trade/v4'; const baseURL = 'https://indexer.v4testnet.dydx.exchange/v4'; fetch(`${baseURL}/fundingPayments/parentSubaccount?address=string&parentSubaccountNumber=0.1`, { method: 'GET', headers: headers }) .then(function(res) { return res.json(); }).then(function(body) { console.log(body); }); ``` -------------------------------- ### Add Command to Root Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/command/README.md Demonstrates how to add a custom command package as a direct subcommand to the root `dydxprotocold` command. ```go rootCmd, _ := NewRootCmd(...) rootCmd.AddCommand(mycommandpkg.Command()) ``` -------------------------------- ### Connect and Subscribe to Trades using wscli Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/websocket-documentation.md Example of using the 'interactive-websocket-cli' to connect to the dYdX v4 Testnet WebSocket endpoint and subscribe to the 'v4_trades' channel for 'BTC-USD'. ```bash wscli connect wss://indexer.v4testnet.dydx.exchange/v4/ws { "type": "subscribe", "channel": "v4_trades", "id": "BTC-USD" } ``` -------------------------------- ### Build Protobufs Source: https://github.com/dydxprotocol/v4-chain/blob/main/proto/README.md Run this command in the root of the v4-chain directory to generate protobuf files after making changes. ```bash make proto-gen ``` -------------------------------- ### Configure Local Cosmos SDK Replace Directive Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/README.md Modify your project's go.mod file to use a local version of the Cosmos SDK. This ensures that `make localnet-start` uses your modified SDK. ```diff replace ( github.com/cosmos/cosmos-sdk v0.47.0-alpha2 => /Users/bryce/projects/cosmos-sdk github.com/keybase/go-keychain => github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 google.golang.org/grpc => google.golang.org/grpc v1.50.1 ) ``` -------------------------------- ### Example JSON Response for Transfers Between Addresses Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md This is an example of a successful JSON response when querying for transfers between specific addresses. ```json { "pageSize": 0, "totalResults": 0, "offset": 0, "transfersSubset": [ { "id": "string", "sender": { "subaccountNumber": 0, "address": "string" }, "recipient": { "subaccountNumber": 0, "address": "string" }, "size": "string", "createdAt": "string", "createdAtHeight": "string", "symbol": "string", "type": "TRANSFER_IN", "transactionHash": "string" } ], "totalNetTransfers": "string" } ``` -------------------------------- ### Build and Run Proto Event Deserializer Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/scripts/debugging/README.md Build the proto event deserializer Go script using 'make build', then execute the compiled binary with the JSON file path as an argument. ```bash make build ./deserialize_proto ``` -------------------------------- ### Import Test Account Private Keys Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/README.md Import private keys for test accounts like 'alice' and 'bob' using their mnemonics. This is necessary to run commands that require account authentication. ```sh ./build/dydxprotocold keys add alice --recover ``` ```sh ./build/dydxprotocold keys add bob --recover ``` -------------------------------- ### Example Orderbook Channel Data Payload Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/websocket-documentation.md An example JSON payload representing data received from the v4_orderbook channel. It includes bids with price and size information. ```json { "type": "channel_data", "connection_id": "ee5a4696-dce8-44ef-8d68-f0e0d0b06160", "message_id": 484, "id": "BTC-USD", "channel": "v4_orderbook", "version": "0.0.1", "contents": { "bids": [ [ "27773", "1.986168516" ] ] } } ``` -------------------------------- ### Build and Run Development/Staging Chain Locally Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/testing/README.md Builds the Docker image for the testnet and runs a specific validator node using the --home flag. The --home flag specifies the validator's data directory, with a new one created for each MONIKER. ```bash # dev docker build . --progress=plain --no-cache -f ./testing/testnet-dev/Dockerfile -t testnet && docker run testnet start --home /dydxprotocol/chain/.alice # staging docker build . --progress=plain --no-cache -f ./testing/testnet-staging/Dockerfile -t testnet && docker run testnet start --home /dydxprotocol/chain/.alice ``` -------------------------------- ### Create Knex Migration Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/packages/postgres/README.md Use this command to add a new knex migration file. Replace `` with your migration name. ```bash pnpm run migrate:make ``` -------------------------------- ### Run Unit Tests Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/README.md Execute this command to run all unit tests for the project. ```bash make test ``` -------------------------------- ### Run a Single Test File Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/README.md Executes a specific test file within a service. Navigate to the service directory, build it, and then run the test command. ```sh cd services/{service_name} && pnpm build && pnpm test -- {test_name} ``` -------------------------------- ### Example Trade Channel Data Payload Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/websocket-documentation.md An example JSON payload representing trade data received on the 'v4_trades' channel. It includes connection details and a list of individual trades with their properties. ```json { "type": "channel_data", "connection_id": "57844645-0b1d-4c3f-ad71-1c6154154a13", "message_id": 4, "id": "BTC-USD", "channel": "v4_trades", "version": "1.1.0", "contents": { "trades": [ { "id": "8ee6d90d-272d-5edd-bf0f-2e4d6ae3d3b7", "size": "0.000100431", "price": "27839", "side": "BUY", "createdAt": "2023-04-04T00:29:19.353Z", "type": "LIQUIDATED" }, { "id": "38e64479-af09-5417-a795-195f83879156", "size": "0.000000004", "price": "27839", "side": "BUY", "createdAt": "2023-04-04T00:29:19.353Z", "type": "LIQUIDATED" }, { "id": "d310c32c-f066-5ba8-a97d-10a29d9a6c84", "size": "0.000000005", "price": "27837", "side": "SELL", "createdAt": "2023-04-04T00:29:19.353Z", "type": "LIMIT" }, { "id": "dd1088b5-5cab-518f-a59c-4d5f735ab861", "size": "0.000118502", "price": "27837", "side": "SELL", "createdAt": "2023-04-04T00:29:19.353Z", "type": "LIMIT" }, ], }, } ``` -------------------------------- ### Run Proto Event Deserializer with Go Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/scripts/debugging/README.md Execute the proto event deserializer script directly using 'make run'. Ensure the JSON file path is provided via the JSON environment variable. ```bash make run JSON= ``` -------------------------------- ### Get Funding Payments - Python Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Use this Python snippet to fetch funding payments for a given address and subaccount. Ensure you use the correct baseURL for the deployment environment. ```python import requests headers = { 'Accept': 'application/json' } # For the deployment by DYDX token holders, use # baseURL = 'https://indexer.dydx.trade/v4' baseURL = 'https://indexer.v4testnet.dydx.exchange/v4' r = requests.get(f'{baseURL}/fundingPayments', params={ 'address': 'string', 'subaccountNumber': '0.1' }, headers = headers) print(r.json()) ``` -------------------------------- ### GET /height Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Retrieves the current blockchain height and time. ```APIDOC ## GET /height ### Description Retrieves the current blockchain height and time. ### Method GET ### Endpoint /height ### Response #### Success Response (200) - **height** (string) - none - **time** (string) - none #### Response Example ```json { "height": "string", "time": "string" } ``` ``` -------------------------------- ### Get Sparklines Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Retrieves sparkline data for a given time period. ```APIDOC ## GET /sparklines ### Description Retrieves sparkline data for a given time period. ### Method GET ### Endpoint /sparklines ### Parameters #### Query Parameters - **timePeriod** (string) - Required - The time period for the sparklines. Enumerated values: ONE_DAY, SEVEN_DAYS. ### Request Example ```json { "timePeriod": "ONE_DAY" } ``` ### Response #### Success Response (200) - **property1** (array) - Example response field. - **property2** (array) - Example response field. #### Response Example ```json { "property1": [ "string" ], "property2": [ "string" ] } ``` ``` -------------------------------- ### Query Indexer API for Trades Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/README.md Example using curl to fetch all BTC-USD trades from the locally run indexer API, which serves requests from http://localhost:3002. ```bash curl http://localhost:3002/v4/trades/perpetualMarket/BTC-USD ``` -------------------------------- ### Run Full-Node Locally Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/testing/README.md Builds the Docker image and runs the chain as a full-node, using a dedicated home directory for full-node data. ```bash $ docker build . --progress=plain --no-cache -f ./testing/testnet-dev/Dockerfile -t testnet && docker run testnet start --home /dydxprotocol/chain/.full-node ``` -------------------------------- ### GET /vault/v1/megavault/historicalPnl Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Retrieves historical Profit and Loss (Pnl) data for megavaults. ```APIDOC ## GET /vault/v1/megavault/historicalPnl ### Description Retrieves historical Profit and Loss (Pnl) data for megavaults. ### Method GET ### Endpoint /vault/v1/megavault/historicalPnl ### Parameters #### Query Parameters - **resolution** (PnlTickInterval) - Optional - none ### Response #### Success Response (200) - **megavaultPnl** (array) - - **equity** (string) - - **totalPnl** (string) - - **netTransfers** (string) - - **createdAt** (string) - - **blockHeight** (string) - - **blockTime** (string) - #### Response Example ```json { "megavaultPnl": [ { "equity": "string", "totalPnl": "string", "netTransfers": "string", "createdAt": "string", "blockHeight": "string", "blockTime": "string" } ] } ``` ``` -------------------------------- ### Orderbook Initial Response Example Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/websocket-documentation.md This JSON represents the initial response when subscribing to an orderbook. It includes connection details and the current state of bids and asks for a specified market. ```json { "type": "subscribed", "connection_id": "ee5a4696-dce8-44ef-8d68-f0e0d0b06160", "message_id": 2, "channel": "v4_orderbook", "id": "BTC-USD", "contents": { "bids": [ { "price": "28194", "size": "4.764826096" }, { "price": "28193", "size": "3.115323739" }, { "price": "28192", "size": "3.400340775" }, { "price": "28191", "size": "3.177700682" }, { "price": "28190", "size": "3.055502176" }, { "price": "28189", "size": "3.672892171" }, { "price": "28188", "size": "3.597672948" }, { "price": "28187", "size": "2.561597964" }, { "price": "28186", "size": "3.070490554" }, { "price": "28185", "size": "3.550128411" }, { "price": "28184", "size": "4.213369101" }, { "price": "28183", "size": "3.608880877" } ], "asks": [ { "price": "28195", "size": "3.219612343" }, { "price": "28196", "size": "2.387087565" }, { "price": "28197", "size": "2.698530469" }, { "price": "28198", "size": "2.590884421" }, { "price": "28199", "size": "3.192796678" } ] } } ``` -------------------------------- ### GET /time Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Retrieves the current server time. This endpoint does not require authentication. ```APIDOC ## GET /time ### Description Retrieves the current server time. ### Method GET ### Endpoint /v4/time ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **iso** (string) - The current time in ISO format. - **epoch** (number) - The current time in epoch format. #### Response Example ```json { "iso": "string", "epoch": 0.1 } ``` ``` -------------------------------- ### GET /historicalFunding/{ticker} Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Retrieves historical funding data for a specific ticker. ```APIDOC ## GET /historicalFunding/{ticker} ### Description Retrieves historical funding data for a specific ticker. ### Method GET ### Endpoint /historicalFunding/{ticker} ### Parameters #### Path Parameters - **ticker** (string) - Required - none ### Response #### Success Response (200) - **funding** (array) - none - **createdAt** (string) - none - **createdAtHeight** (string) - none - **perpetualId** (string) - none - **ticker** (string) - none - **oraclePrice** (string) - none - **size** (string) - none - **side** (string) - none - **rate** (string) - none - **payment** (string) - none - **subaccountNumber** (string) - none - **fundingIndex** (string) - none #### Response Example ```json { "funding": [ { "createdAt": "string", "createdAtHeight": "string", "perpetualId": "string", "ticker": "string", "oraclePrice": "string", "size": "string", "side": "string", "rate": "string", "payment": "string", "subaccountNumber": "string", "fundingIndex": "string" } ] } ``` ``` -------------------------------- ### GET /historicalBlockTradingRewards/{address} Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Retrieves historical trading rewards for a given address. ```APIDOC ## GET /historicalBlockTradingRewards/{address} ### Description Retrieves historical trading rewards for a given address. ### Method GET ### Endpoint /historicalBlockTradingRewards/{address} ### Parameters #### Path Parameters - **address** (string) - Required - none #### Query Parameters - **limit** (number(double)) - Optional - none - **startingBeforeOrAt** (IsoString) - Optional - none - **startingBeforeOrAtHeight** (string) - Optional - none ### Response #### Success Response (200) - **rewards** (array) - none - **tradingReward** (string) - none - **createdAt** (string) - none - **createdAtHeight** (string) - none #### Response Example ```json { "rewards": [ { "tradingReward": "string", "createdAt": "string", "createdAtHeight": "string" } ] } ``` ``` -------------------------------- ### POST /turnkey/signin Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Handles the sign-in process for users, allowing them to authenticate and obtain session details. ```APIDOC ## POST /turnkey/signin ### Description Initiates the sign-in process for a user. This endpoint is used to authenticate users and retrieve necessary session information. ### Method POST ### Endpoint /turnkey/signin ### Parameters #### Request Body - **signinMethod** (string) - Required - The method used for signing in (e.g., "email"). - **userEmail** (string) - Optional - The email address of the user. - **targetPublicKey** (string) - Optional - The public key of the target. - **provider** (string) - Optional - The authentication provider. - **oidcToken** (string) - Optional - The OIDC token. - **challenge** (string) - Optional - The challenge for authentication. - **attestation** (object) - Optional - Attestation details for authentication. - **transports** (array) - Optional - List of supported transports (e.g., ["AUTHENTICATOR_TRANSPORT_BLE"]). - **attestationObject** (string) - Optional - The attestation object. - **clientDataJson** (string) - Optional - The client data JSON. - **credentialId** (string) - Optional - The credential ID. - **magicLink** (string) - Optional - A magic link for sign-in. ### Request Example ```json { "signinMethod": "email", "userEmail": "string", "targetPublicKey": "string", "provider": "string", "oidcToken": "string", "challenge": "string", "attestation": { "transports": [ "AUTHENTICATOR_TRANSPORT_BLE" ], "attestationObject": "string", "clientDataJson": "string", "credentialId": "string" }, "magicLink": "string" } ``` ### Response #### Success Response (200) - **dydxAddress** (string) - The user's dYdX address. - **organizationId** (string) - The organization ID. - **apiKeyId** (string) - The API key ID. - **userId** (string) - The user ID. - **session** (string) - The user's session token. - **salt** (string) - A salt value for security. - **alreadyExists** (boolean) - Indicates if the user already exists. #### Response Example ```json { "dydxAddress": "string", "organizationId": "string", "apiKeyId": "string", "userId": "string", "session": "string", "salt": "string", "alreadyExists": true } ``` ``` -------------------------------- ### Clone and Checkout Cosmos SDK Version Source: https://github.com/dydxprotocol/v4-chain/blob/main/protocol/README.md Clone the Cosmos SDK repository and checkout the specific version required by your project's go.mod file. This is the first step to making local modifications. ```sh git clone git@github.com:cosmos/cosmos-sdk.git git checkout v0.47.0-alpha2 ``` -------------------------------- ### GET /funding Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Retrieves a list of funding payments with various filtering options. ```APIDOC ## GET /funding ### Description Retrieves a list of funding payments with various filtering options. ### Method GET ### Endpoint /funding ### Parameters #### Query Parameters - **address** (string) - Required - none - **parentSubaccountNumber** (number(double)) - Required - none - **limit** (number(double)) - Optional - none - **afterOrAt** (IsoString) - Optional - none - **page** (number(double)) - Optional - none - **zeroPayments** (boolean) - Optional - none ### Response #### Success Response (200) - **pageSize** (integer) - none - **totalResults** (integer) - none - **offset** (integer) - none - **fundingPayments** (array) - none - **createdAt** (string) - none - **createdAtHeight** (string) - none - **perpetualId** (string) - none - **ticker** (string) - none - **oraclePrice** (string) - none - **size** (string) - none - **side** (string) - none - **rate** (string) - none - **payment** (string) - none - **subaccountNumber** (string) - none - **fundingIndex** (string) - none #### Response Example ```json { "pageSize": 0, "totalResults": 0, "offset": 0, "fundingPayments": [ { "createdAt": "string", "createdAtHeight": "string", "perpetualId": "string", "ticker": "string", "oraclePrice": "string", "size": "string", "side": "string", "rate": "string", "payment": "string", "subaccountNumber": "string", "fundingIndex": "string" } ] } ``` ``` -------------------------------- ### GET /assetPositions Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md Retrieves the asset positions for a given address and subaccount number. ```APIDOC ## GET /assetPositions ### Description Retrieves the asset positions for a given address and subaccount number. ### Method GET ### Endpoint /assetPositions ### Parameters #### Query Parameters - **address** (string) - Required - The account address. - **subaccountNumber** (number(double)) - Required - The subaccount number. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **positions** (array) - A list of asset positions. - **symbol** (string) - The trading symbol of the asset. - **side** (string) - The side of the position (e.g., LONG, SHORT). - **size** (string) - The size of the position. - **assetId** (string) - The unique identifier for the asset. - **subaccountNumber** (number) - The subaccount number associated with the position. #### Response Example ```json { "positions": [ { "symbol": "string", "side": "LONG", "size": "string", "assetId": "string", "subaccountNumber": 0 } ] } ``` ``` -------------------------------- ### Example 200 Response for ListPositions Source: https://github.com/dydxprotocol/v4-chain/blob/main/indexer/services/comlink/public/api-documentation.md A sample JSON response for a successful (200 OK) request to the ListPositions endpoint, detailing open positions. ```json { "positions": [ { "market": "string", "status": "OPEN", "side": "LONG", "size": "string", "maxSize": "string", "entryPrice": "string", "realizedPnl": "string", "createdAt": "string", "createdAtHeight": "string", "sumOpen": "string", "sumClose": "string", "netFunding": "string", "unrealizedPnl": "string", "closedAt": "string", "exitPrice": "string", "subaccountNumber": 0 } ] } ```