### Setup Complete Example Source: https://github.com/orderlynetwork/documentation-public/blob/main/llms-full.txt After setup, you can utilize the provided hooks. This example shows how to display the user's address. ```tsx const App = () => { const state = useOrderlyAccount(); return (
Address: {state.address}
); }; ``` -------------------------------- ### React Router Configuration Example Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/react/components/portfolio.mdx Configure routes for HistoryPage and SettingPage within a React Router setup. Ensure necessary modules and components are imported. ```typescript import { Routes, Route } from "react-router-dom"; import { HistoryModule, SettingModule } from "@orderly.network/portfolio"; const { HistoryPage } = HistoryModule; const { SettingPage } = SettingModule; function App() { return ( {/* Other routes */} } /> } /> } /> {/* New mobile page routes */} } /> } /> ); } ``` -------------------------------- ### Install Wallet Connector Dependencies Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/react/getting_started.mdx Install the necessary dependencies for the Orderly wallet connector. ```bash npm install @orderly.network/wallet-connector ``` -------------------------------- ### Install UI Scaffold Library Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/react/getting_started.mdx Install the UI scaffold library for built-in navigation and layout components. ```bash npm install @orderly.network/ui-scaffold ``` -------------------------------- ### Install Base Component Libraries Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/react/getting_started.mdx Install the core component libraries for the Orderly React SDK. ```bash npm install @orderly.network/ui @orderly.network/react-app ``` -------------------------------- ### Install Orderly Perp SDK Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/perp/overview.mdx Install the Orderly Perp SDK using npm. ```sh npm install @orderly.network/perp ``` -------------------------------- ### Full Example with Authentication Utility (Java) Source: https://github.com/orderlynetwork/documentation-public/blob/main/llms-full.txt A full example in Java demonstrating how to use the `signAndSendRequest` utility function to interact with the Orderly API. Requires Node.js environment for `@noble/ed25519` and environment variables for secret key. ```java // this is only necessary in Node.js to make `@noble/ed25519` dependency work if (!globalThis.crypto) globalThis.crypto = webcrypto as any; config(); async function main() { const baseUrl = 'https://testnet-api.orderly.org'; const orderlyAccountId = ''; const orderlyKey = bs58.decode(process.env.ORDERLY_SECRET!); const res = await signAndSendRequest(orderlyAccountId, orderlyKey, `${baseUrl}/v1/order`, { method: 'POST', body: JSON.stringify({ symbol: 'PERP_ETH_USDC', order_type: 'MARKET', order_quantity: 0.01, side: 'BUY' }) }); const response = await res.json(); console.log(response); } main(); ``` -------------------------------- ### cURL Example Source: https://github.com/orderlynetwork/documentation-public/blob/main/llms-full.txt Example of how to make a POST request to the Orderly API using cURL. ```APIDOC ## POST /v1/order (cURL) ### Description Sends an order to the Orderly API using cURL. ### Method POST ### Endpoint https://api.orderly.org/v1/order ### Headers - **Content-Type**: application/json - **orderly-account-id**: `` - **orderly-key**: `ed25519:8tm7dnKYkSc3FzgPuJaw1wztr79eeZpN35nHW5pL5XhX` - **orderly-signature**: `dG4bkKiqG0dUYLzViRZkvbI6Sy239JxAdNMIBxFZ4w030Jofr0ORV06GHtvXZkaZaWUXE+XAU3fnzKN/5fDeBQ==` - **orderly-timestamp**: `1649920583000` ### Request Body ```json { "symbol": "", "order_type": "", "side": "", "reduce_only": false } ``` ``` -------------------------------- ### Minimal Example (TypeScript) Source: https://github.com/orderlynetwork/documentation-public/blob/main/llms-full.txt A concise, single-file TypeScript example demonstrating how to sign and send a request to the Orderly API using the `@noble/ed25519` library. ```APIDOC ## POST /v1/order ### Description Sends an order to the Orderly API. ### Method POST ### Endpoint /v1/order ### Request Body - **symbol** (string) - Required - The trading symbol. - **order_type** (string) - Required - The type of order (e.g., 'MARKET', 'LIMIT'). - **order_quantity** (number) - Required - The quantity of the order. - **side** (string) - Required - The side of the order ('BUY' or 'SELL'). ### Request Example ```json { "symbol": "PERP_ETH_USDC", "order_type": "MARKET", "order_quantity": 0.01, "side": "BUY" } ``` ### Headers - **Content-Type**: application/json - **orderly-account-id**: Your Orderly account ID. - **orderly-key**: Your public key in the format 'ed25519:'. - **orderly-timestamp**: The timestamp of the request in milliseconds. - **orderly-signature**: The base64url encoded ed25519 signature of the request. ### Response #### Success Response (200) - **data** (object) - Contains the response data from the API. ### Response Example ```json { "data": { ... } } ``` ``` -------------------------------- ### Register Account with EIP712 Signature (Python) Source: https://github.com/orderlynetwork/documentation-public/blob/main/build-on-omnichain/user-flows/accounts.mdx This Python example shows how to register an account on Orderly Network. It mirrors the Java example by fetching a nonce, constructing the message, and preparing it for signing. ```Python from datetime import datetime import json import math import os import requests from eth_account import Account, messages MESSAGE_TYPES = { "EIP712Domain": [ {"name": "name", "type": "string"}, {"name": "version", "type": "string"}, {"name": "chainId", "type": "uint256"}, {"name": "verifyingContract", "type": "address"}, ], "Registration": [ {"name": "brokerId", "type": "string"}, {"name": "chainId", "type": "uint256"}, {"name": "timestamp", "type": "uint64"}, {"name": "registrationNonce", "type": "uint256"}, ], } OFF_CHAIN_DOMAIN = { "name": "Orderly", "version": "1", "chainId": 421614, "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", } base_url = "https://testnet-api.orderly.org" broker_id = "woofi_dex" chain_id = 421614 account: Account = Account.from_key(os.environ.get("PRIVATE_KEY")) res = requests.get("%s/v1/registration_nonce" % base_url) response = json.loads(res.text) registration_nonce = response["data"]["registration_nonce"] d = datetime.utcnow() epoch = datetime(1970, 1, 1) timestamp = math.trunc((d - epoch).total_seconds() * 1_000) register_message = { "brokerId": broker_id, "chainId": chain_id, "timestamp": timestamp, ``` -------------------------------- ### Place Market Order Example Source: https://context7.com/orderlynetwork/documentation-public/llms.txt This example demonstrates how to place a market BUY order on the Orderly Network testnet using the REST API and ed25519 signature authentication. ```APIDOC ## Place Market Order ### Description This endpoint allows users to place a market order for a specific trading pair. ### Method POST ### Endpoint `/v1/order` ### Parameters #### Request Body - **symbol** (string) - Required - The trading pair, e.g., 'PERP_ETH_USDC'. - **order_type** (string) - Required - The type of order, e.g., 'MARKET'. - **order_quantity** (number) - Required - The quantity of the asset to trade. - **side** (string) - Required - The side of the order, 'BUY' or 'SELL'. ### Request Example ```json { "symbol": "PERP_ETH_USDC", "order_type": "MARKET", "order_quantity": 0.01, "side": "BUY" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - Contains details of the placed order. - **order_id** (number) - The unique identifier for the order. - **client_order_id** (string) - The client-provided order ID (if any). #### Response Example ```json { "success": true, "data": { "order_id": 12345, "client_order_id": "" } } ``` ``` -------------------------------- ### Full Deposit Example (TypeScript) Source: https://github.com/orderlynetwork/documentation-public/blob/main/llms-full.txt A comprehensive TypeScript example demonstrating the entire deposit process, including contract connection, approval, fee calculation, and the final deposit transaction. ```typescript const brokerId = "woofi_pro"; const tokenId = "USDC"; const usdcAddress = "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d"; const vaultAddress = "0x0EaC556c0C2321BA25b9DC01e4e3c95aD5CDCd2f"; config(); async function deposit(): Promise { const provider = new ethers.JsonRpcProvider("https://arbitrum-sepolia.publicnode.com"); const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); const usdcContract = NativeUSDC__factory.connect(usdcAddress, wallet); const depositAmount = 10_000_000n; await usdcContract.approve(vaultAddress, depositAmount); const vaultContract = Vault__factory.connect(vaultAddress, wallet); const orderlyAccountId = getAccountId(wallet.address, brokerId); const encoder = new TextEncoder(); const depositInput = { accountId: orderlyAccountId, brokerHash: keccak256(encoder.encode(brokerId)), tokenHash: keccak256(encoder.encode(tokenId)), tokenAmount: depositAmount } satisfies VaultTypes.VaultDepositFEStruct; // get wei deposit fee for `deposit` call const depositFee = await vaultContract.getDepositFee(wallet.address, depositInput); // deposit USDC into Vault contract await vaultContract.deposit(depositInput, { value: depositFee }); } export function getAccountId(address: string, brokerId: string) { const abicoder = AbiCoder.defaultAbiCoder(); return keccak256( abicoder.encode( ["address", "bytes32"], [address, solidityPackedKeccak256(["string"], [brokerId])] ) ); } deposit(); ``` -------------------------------- ### Sign and Send Request (TypeScript) Source: https://github.com/orderlynetwork/documentation-public/blob/main/build-on-omnichain/api-authentication.mdx Example of signing and sending an API request using TypeScript, including environment variable loading and crypto setup. ```typescript import bs58 from 'bs58'; import { config } from 'dotenv'; import { webcrypto } from 'node:crypto'; import { signAndSendRequest } from "./signer"; // this is only necessary in Node.js to make `@noble/ed25519` dependency work if (!globalThis.crypto) globalThis.crypto = webcrypto as any; config(); async function main() { const baseUrl = 'https://testnet-api.orderly.org'; const orderlyAccountId = ''; const orderlyKey = bs58.decode(process.env.ORDERLY_SECRET!); const res = await signAndSendRequest(orderlyAccountId, orderlyKey, `${baseUrl}/v1/order`, { method: 'POST', body: JSON.stringify({ symbol: 'PERP_ETH_USDC', order_type: 'MARKET', order_quantity: 0.01, side: 'BUY' }) }); const response = await res.json(); console.log(response); } main(); ``` -------------------------------- ### usePrivateInfiniteQuery Usage Example Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/api/use-private-infinite-query.mdx This example demonstrates how to use the `usePrivateInfiniteQuery` hook to fetch a list of orders with support for infinite scrolling. It shows how to construct the API endpoint with query parameters and handle potential errors. ```APIDOC ## usePrivateInfiniteQuery ### Description Hook for paginated private API queries with infinite scroll support. Appends data from subsequent pages rather than replacing it. ### Usage ```tsx const { data: orders } = usePrivateInfiniteQuery( (pageIndex: number, previousPageData) => { // reached the end if (previousPageData && !previousPageData.length) return null; const search = new URLSearchParams([ ["size", size.toString()], ["page", `${pageIndex + 1}`] ]); if (status) { search.set(`status`, status); } if (symbol) { search.set(`symbol`, symbol); } if (side) { search.set(`side`, side); } return `/v1/orders?${search.toString()}`; }, { initialSize: 1, onError: (err) => { console.error("fetch failed::::", err); } } ); ``` ### Parameters * **queryFn**: `(pageIndex: number, previousPageData: any) => string | null` - A function that returns the API endpoint URL for the current page or `null` if there's no more data. * **options**: `object` - Configuration options for the query. * **initialSize** (`number`) - The initial page size. Defaults to 1. * **onError** (`function`) - A callback function to handle errors during the fetch. ### Returns * **data**: `any` - The fetched data, appended from all pages. ### Example To fetch a list of orders: ```tsx const { data: orders } = usePrivateInfiniteQuery( (pageIndex: number, previousPageData) => { if (previousPageData && !previousPageData.length) return null; const search = new URLSearchParams([ ["size", "10"], ["page", `${pageIndex + 1}`] ]); return `/v1/orders?${search.toString()}`; }, { initialSize: 1, onError: (err) => console.error("fetch failed:", err) } ); ``` ``` -------------------------------- ### Install Orderly Hooks and Types SDK Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/setup.mdx Install the Orderly hooks and types SDKs using npm. This is the first step to integrating Orderly functionality into your React project. ```sh npm install @orderly.network/types @orderly.network/hooks ``` -------------------------------- ### Normalize Request Content Example Source: https://github.com/orderlynetwork/documentation-public/blob/main/build-on-omnichain/api-authentication.mdx This example shows how to construct the message string for signing by concatenating the timestamp, HTTP method, request path with query parameters, and the JSON stringified request body. ```string 1649920583000POST/v1/order?symbol=PERP_BTC_USDC{"symbol": "PERP_ETH_USDC", "order_type": "LIMIT", "order_price": 1521.03, "order_quantity": 2.11, "side": "BUY"} ``` -------------------------------- ### Complete Scaffold Component Usage Example Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/react/components/scaffold.mdx A comprehensive example demonstrating the integration of Scaffold with React Router, including sidebar menus, main navigation, bottom navigation, and footer links. ```typescript import React from 'react'; import { Scaffold } from "@orderly.network/ui-scaffold"; import { useNavigate, useLocation } from 'react-router-dom'; const App = () => { const navigate = useNavigate(); const location = useLocation(); const sidebarMenus = [ { name: "Dashboard", href: "/dashboard", icon: }, { name: "Trading", href: "/trading", icon: }, { name: "Portfolio", href: "/portfolio", icon: } ]; const bottomMenus = [ { name: "Home", href: "/home", activeIcon: , inactiveIcon: }, { name: "Trade", href: "/trade", activeIcon: , inactiveIcon: } ]; const routerAdapter = { onRouteChange: (option) => { if (option.target === '_blank') { window.open(option.href, '_blank'); } else { navigate(option.href); } }, currentPath: location.pathname }; return ( { if (item.href) { navigate(item.href); } } }} mainNavProps={{ logo: { src: "/logo.png", alt: "Company Logo" }, mainMenus: [ { name: "Trade", href: "/trade" }, { name: "Portfolio", href: "/portfolio" } ], leading: , trailing: , onItemClick: ({ href }) => navigate(href) }} bottomNavProps={{ mainMenus: bottomMenus, }} footerProps={{ telegramUrl: "https://t.me/yourgroup", twitterUrl: "https://twitter.com/yourhandle", discordUrl: "https://discord.gg/yourserver" }} routerAdapter={routerAdapter} classNames={{ content: "p-4", leftSidebar: "border-r border-gray-200" }} >
{/* Your main application content */}

Welcome to your application

This is the main content area.

); }; export default App; ``` -------------------------------- ### Orderly API cURL Request Example Source: https://github.com/orderlynetwork/documentation-public/blob/main/llms-full.txt A cURL command to demonstrate a POST request to the Orderly API for placing an order. This example includes all necessary headers for authentication and request details. ```shell curl --request POST \ --url https://api.orderly.org/v1/order \ --header 'Content-Type: application/json' \ --header 'orderly-account-id: ' \ --header 'orderly-key: ed25519:8tm7dnKYkSc3FzgPuJaw1wztr79eeZpN35nHW5pL5XhX' \ --header 'orderly-signature: dG4bkKiqG0dUYLzViRZkvbI6Sy239JxAdNMIBxFZ4w030Jofr0ORV06GHtvXZkaZaWUXE+XAU3fnzKN/5fDeBQ==' \ --header 'orderly-timestamp: 1649920583000' \ --data '{ \ "symbol": "", \ "order_type": "", \ "side": "", \ "reduce_only": false \ }' ``` -------------------------------- ### useDaily Hook Example Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/referral/use-daily.mdx This example demonstrates how to use the `useDaily` hook to fetch daily perpetual volume data. The hook returns a `data` object which is an array of objects, each containing `broker_id`, `date`, and `perp_volume`. ```APIDOC ## useDaily Hook ### Description Hook to retrieve daily perpetual volume data for referral tracking over a date range. Returns `perp_volume` based on start and end time. If not passed, defaults to last 30 days. ### Usage ```ts const { data } = useDaily(); ``` ### Response Data Structure The returned data is an array of objects containing the following fields: ```ts { "broker_id": "veeno_dex", "date": "2024-11-11", "perp_volume": 500 } ``` ``` -------------------------------- ### Minimal TypeScript Example for Orderly API Request Source: https://github.com/orderlynetwork/documentation-public/blob/main/build-on-omnichain/api-authentication.mdx This example demonstrates how to sign and send a POST request to the Orderly API using `@noble/ed25519` and `bs58` for key encoding. Ensure your Orderly secret is base58 encoded and your account ID is correct. ```typescript import { signAsync, getPublicKeyAsync } from '@noble/ed25519'; import bs58 from 'bs58'; async function main() { const orderlyAccountId = 'YOUR_ACCOUNT_ID'; const orderlySecret = 'YOUR_ORDERLY_SECRET'; // base58 encoded const baseUrl = 'https://testnet-api.orderly.org'; const url = new URL(`${baseUrl}/v1/order`); const method = 'POST'; const body = JSON.stringify({ symbol: 'PERP_ETH_USDC', order_type: 'MARKET', order_quantity: 0.01, side: 'BUY' }); const timestamp = Date.now(); const privateKey = bs58.decode(orderlySecret); const message = `${timestamp}${method}${url.pathname}${url.search}${body}`; const signature = await signAsync(new TextEncoder().encode(message), privateKey); const response = await fetch(url, { method, body, headers: { 'Content-Type': 'application/json', 'orderly-account-id': orderlyAccountId, 'orderly-key': `ed25519:${bs58.encode(await getPublicKeyAsync(privateKey))}`, 'orderly-timestamp': String(timestamp), 'orderly-signature': Buffer.from(signature).toString('base64url'), }, }); const data = await response.json(); console.log(data); } main(); ``` -------------------------------- ### Full Example (Java) Source: https://github.com/orderlynetwork/documentation-public/blob/main/llms-full.txt Demonstrates how to sign and send a request to the Orderly API using Java. ```APIDOC ## signAndSendRequest Function ### Description A utility function to sign and send requests to the Orderly API. ### Parameters - **orderlyAccountId** (string) - Required - Your Orderly account ID. - **privateKey** (Uint8Array | string) - Required - Your Orderly secret key. - **input** (URL | string) - Required - The URL or string representation of the URL for the API endpoint. - **init** (RequestInit | undefined) - Optional - Request initialization options, including method, body, and headers. ### Returns - Promise - A promise that resolves to the fetch API Response object. ### Usage Example ```typescript // Assuming orderlyKey is decoded from base58 const res = await signAndSendRequest(orderlyAccountId, orderlyKey, `${baseUrl}/v1/order`, { method: 'POST', body: JSON.stringify({ symbol: 'PERP_ETH_USDC', order_type: 'MARKET', order_quantity: 0.01, side: 'BUY' }) }); const response = await res.json(); console.log(response); ``` ``` -------------------------------- ### Instantiate and Login with Account Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/tech-doc/classes/orderly_network_core.Account.mdx Demonstrates how to create an instance of the Account class and log in with a given account ID. Ensure the necessary dependencies like ConfigStore, OrderlyKeyStore, and getWalletAdapter are provided. ```typescript const account = new Account(); account.login("0x1234567890"); ``` -------------------------------- ### useMarketTradeStream Usage Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/market-data/use-market-trade-stream.mdx Example of how to use the useMarketTradeStream hook to get trade data for a symbol. The hook returns an array of trade objects, or indicates loading state. ```APIDOC ## useMarketTradeStream ### Description Streams recent trade executions for a given symbol via WebSocket. ### Method Signature `useMarketTradeStream(symbol: string)` ### Parameters #### Path Parameters - **symbol** (string) - Required - The market symbol for which to stream trades. ### Response Returns an object containing `data` and `isLoading`. - **data** (Array) - An array of trade execution objects. - **isLoading** (boolean) - Indicates if the data is currently being fetched. ### Trade Object Structure ```json { "price": number, "side": "BUY" | "SELL", "size": number, "ts": number } ``` ### Example ```tsx const { data, isLoading } = useMarketTradeStream(symbol); ``` ``` -------------------------------- ### Get Specific Configuration Value Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/util/use-config.mdx Use this snippet to retrieve a single configuration value, such as 'networkId'. The value can then be used in conditional logic, for example, within a useEffect hook. ```typescript const networkId = useConfig("networkId"); useEffect(() => { if (networkId === "testnet") { // do something } }, [networkId]); ``` -------------------------------- ### installExtension Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/tech-doc/modules/orderly_network_react.mdx Installs a browser extension for Orderly Network. It takes options and returns a function to render the extension component. ```APIDOC ## installExtension ### Description Installs a browser extension for Orderly Network. It takes options and returns a function to render the extension component. ### Signature `installExtension(options: ExtensionOptions) => (component: ExtensionRenderComponentType) => void` ### Parameters #### `options` - `options` (ExtensionOptions) - Configuration options for the extension. #### Returns - `fn` - A function that accepts a component to render the extension. - ### Parameters - `component` (ExtensionRenderComponentType) - The component to render. - ### Returns - `void` ``` -------------------------------- ### useReferralRebateSummary Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/referral/use-referral-rebate-summary.mdx Hook to get daily referral rebate statistics over a date range. Provide statistics on referral rebates per date, based on start and end date. ```APIDOC ## useReferralRebateSummary ### Description Provides statistics on referral rebates per date, based on start and end date. ### Usage ```ts const [data, { refresh, isLoading, loadMore }] = useReferralRebateSummary({ startDate, endDate }); ``` ### Parameters - **startDate** (Date) - The start date for the rebate statistics. - **endDate** (Date) - The end date for the rebate statistics. ### Returns - **data**: Referral rebate statistics. - **refresh**: Function to refresh the rebate statistics. - **isLoading**: Boolean indicating if the data is currently being loaded. - **loadMore**: Function to load more data (if applicable). ``` -------------------------------- ### Get Daily User Volume Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/account/use-daily.mdx Use this hook to fetch daily trading volume for your account. Specify a start and end date to define the period for which you want to retrieve data. ```typescript const { data } = useDaily({ startDate: new Date(Date.now() - 86400000 * 40), // 40 days ago endDate: new Date() // today }); ``` -------------------------------- ### Get Account Margin Ratio Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/account/use-margin-ratio.mdx Use this hook to retrieve the current margin ratio, leverage, and maintenance margin ratio for an account. No additional setup is required beyond importing the hook. ```typescript const { marginRatio, currentLeverage, mmr } = useMarginRatio(); ``` -------------------------------- ### React App Setup with Orderly SDK Source: https://context7.com/orderlynetwork/documentation-public/llms.txt Bootstraps a full trading UI using Orderly's React component library. `OrderlyAppProvider` wraps the app with global config; `WalletConnectorProvider` handles EVM + Solana wallet connections. Ready-made page components can be routed in directly. ```tsx import React, { FC, ReactNode } from 'react'; import { OrderlyAppProvider } from '@orderly.network/react-app'; import { WalletConnectorProvider } from '@orderly.network/wallet-connector'; import { WalletAdapterNetwork } from '@solana/wallet-adapter-base'; import '@orderly.network/ui/dist/styles.css'; // npm install @orderly.network/ui @orderly.network/react-app @orderly.network/wallet-connector const App: FC<{ children: ReactNode }> = ({ children }) => ( {children} ); // Page components (each installed separately): // import TradingPage from '@orderly.network/trading'; // import PortfolioPage from '@orderly.network/portfolio'; // import MarketsPage from '@orderly.network/markets'; // import ReferralPage from '@orderly.network/referral'; // // Scaffold layout with built-in top/side nav: // import Scaffold from '@orderly.network/ui-scaffold'; // // // export default App; ``` -------------------------------- ### Get Referee Rebate Summary Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/referral/use-referee-rebate-summary.mdx Use this hook to fetch daily referee rebate statistics. Pass the desired start and end dates to retrieve the relevant data. The hook returns data, a mutate function, and a loading state. ```typescript const { data: distributionData, mutate, isLoading } = useRefereeRebateSummary({ startDate, endDate }); ``` -------------------------------- ### Example Withdrawal Message Payload Source: https://github.com/orderlynetwork/documentation-public/blob/main/llms-full.txt An example payload for an EIP-712 withdrawal message. Note that this is a truncated example. ```json { "brokerId": "woofi_pro", "chainId": 80001, ... (truncated for brevity) } ``` -------------------------------- ### Constructor Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/tech-doc/classes/orderly_network_core.BaseKeyStore.mdx Initializes a new instance of the BaseKeyStore class. It accepts an optional networkId parameter. ```APIDOC ## constructor ### Description Initializes a new instance of the BaseKeyStore class. ### Parameters - **networkId** (string, optional, default: "testnet") - The network identifier for the keystore. ### Defined in packages/core/src/keyStore.ts:16 ``` -------------------------------- ### Account Constructor Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/tech-doc/classes/orderly_network_core.Account.mdx Initializes a new Account instance. It requires configuration stores, key stores, and wallet adapter functions. ```APIDOC ## constructor ### Description Initializes a new Account instance. ### Parameters - **configStore** (`ConfigStore`) - Required - The configuration store for the account. - **keyStore** (`OrderlyKeyStore`) - Required - The keystore for managing user keys. - **getWalletAdapter** (`getWalletAdapterFunc`) - Required - A function to retrieve the wallet adapter. - **options?** (`Partial<{ contracts: IContract }>`) - Optional - Additional options, including contract configurations. ``` -------------------------------- ### Generate and Sign Orderly Key Request (Python) Source: https://github.com/orderlynetwork/documentation-public/blob/main/build-on-omnichain/user-flows/wallet-authentication.mdx This Python example shows how to generate an Orderly key, sign a message using EIP712, and send a request to the Orderly API for key registration. It requires environment variables for private key and uses the `eth_account` library. ```Python from datetime import datetime import json import math import os import requests from base58 import b58encode from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from eth_account import Account, messages def encode_key(key: bytes): return "ed25519:%s" % b58encode(key).decode("utf-8") MESSAGE_TYPES = { "EIP712Domain": [ {"name": "name", "type": "string"}, {"name": "version", "type": "string"}, {"name": "chainId", "type": "uint256"}, {"name": "verifyingContract", "type": "address"}, ], "AddOrderlyKey": [ {"name": "brokerId", "type": "string"}, {"name": "chainId", "type": "uint256"}, {"name": "orderlyKey", "type": "string"}, {"name": "scope", "type": "string"}, {"name": "timestamp", "type": "uint64"}, {"name": "expiration", "type": "uint64"}, ], } OFF_CHAIN_DOMAIN = { "name": "Orderly", "version": "1", "chainId": 421614, ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/react/next.mdx Start the Next.js development server to view your application locally. ```bash npm run dev ``` -------------------------------- ### useDaily Hook Example Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/account/use-daily.mdx Example usage of the `useDaily` hook to fetch daily trading volume. ```APIDOC ## useDaily Hook ### Description This hook retrieves the daily trading volume for the current account within a specified date range. ### Parameters #### Arguments - **startDate** (Date) - Required - The start date for the volume data. - **endDate** (Date) - Required - The end date for the volume data. ### Request Example ```ts const { data } = useDaily({ startDate: new Date(Date.now() - 86400000 * 40), // 40 days ago endDate: new Date() // today }); ``` ### Response #### Success Response The `data` object contains the daily trading volume. The exact structure of the response is detailed in the technical documentation. #### Response Example (Response structure depends on the hook's implementation and is detailed in the tech docs.) ``` -------------------------------- ### constructor Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/tech-doc/classes/orderly_network_core.EtherAdapter.mdx Initializes a new instance of the EtherAdapter class. ```APIDOC ## constructor ### Description Initializes a new instance of the EtherAdapter class. ### Parameters #### Parameters - **options** (WalletAdapterOptions) - Required - Options for initializing the wallet adapter. ### Defined in packages/core/src/wallet/etherAdapter.ts:22 ``` -------------------------------- ### get Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/tech-doc/modules/orderly_network_net.mdx Sends a GET request to the specified URL. It supports generic response types and optional data formatting. ```APIDOC ## get ### Description Sends a GET request to the specified URL. It supports generic response types and optional data formatting. ### Method GET ### Endpoint [URL provided as argument] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript get('/api/users', { cache: 'no-cache' }, (data) => data.users) ``` ### Response #### Success Response (200) - `R`: The response data, typed by the generic parameter `R`. #### Response Example ```json { "users": [ { "id": 1, "name": "John Doe" }, { "id": 2, "name": "Jane Smith" } ] } ``` ``` -------------------------------- ### Withdrawal EIP-712 Message Example Source: https://github.com/orderlynetwork/documentation-public/blob/main/build-on-omnichain/user-flows/withdrawal-deposit.mdx An example of a populated EIP-712 'Withdraw' message. Use this as a template when constructing your withdrawal requests. ```json { "brokerId": "woofi_pro", "chainId": 80001, "receiver": "0x036Cb579025d3535a0ADcD929D05481a3189714b", "token": "USDC", "amount": "1000000", "withdrawNonce": 1, "timestamp": 1685973017064 } ``` -------------------------------- ### Full Example: Create Orderly Key with TypeScript and ethers.js Source: https://github.com/orderlynetwork/documentation-public/blob/main/llms-full.txt This example demonstrates how to generate an ed25519 key pair, construct the EIP-712 message, sign it using a wallet, and then add the Orderly Key via the API. It requires environment variables for private keys and specific network configurations. ```typescript // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore if (!globalThis.crypto) globalThis.crypto = webcrypto; const MESSAGE_TYPES = { EIP712Domain: [ { name: 'name', type: 'string' }, { name: 'version', type: 'string' }, { name: 'chainId', type: 'uint256' }, { name: 'verifyingContract', type: 'address' } ], AddOrderlyKey: [ { name: 'brokerId', type: 'string' }, { name: 'chainId', type: 'uint256' }, { name: 'orderlyKey', type: 'string' }, { name: 'scope', type: 'string' }, { name: 'timestamp', type: 'uint64' }, { name: 'expiration', type: 'uint64' } ] }; const OFF_CHAIN_DOMAIN = { name: 'Orderly', version: '1', chainId: 421614, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC' }; const BASE_URL = 'https://testnet-api.orderly.org'; const BROKER_ID = 'woofi_dex'; const CHAIN_ID = 421614; config(); async function createOrderlyKey(): Promise { const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!); const privateKey = utils.randomPrivateKey(); const orderlyKey = `ed25519:${encodeBase58(await getPublicKeyAsync(privateKey))}`; const timestamp = Date.now(); const addKeyMessage = { brokerId: BROKER_ID, chainId: CHAIN_ID, orderlyKey, scope: 'read,trading', timestamp, expiration: timestamp + 1_000 * 60 * 60 * 24 * 365 // 1 year }; const signature = await wallet.signTypedData( OFF_CHAIN_DOMAIN, { AddOrderlyKey: MESSAGE_TYPES.AddOrderlyKey }, addKeyMessage ); const keyRes = await fetch(`${BASE_URL}/v1/orderly_key`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: addKeyMessage, signature, userAddress: await wallet.getAddress() }) }); const keyJson = await keyRes.json(); console.log('addAccessKey', keyJson); } createOrderlyKey(); ``` -------------------------------- ### Install Orderly React SDK Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/react/next.mdx Add the Orderly React SDK to your Next.js project using npm. ```sh npm install @orderly.network/react ``` -------------------------------- ### Get Funding Rate for a Symbol Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/funding/use-funding-rate.mdx Call the useFundingRate hook with a perpetual futures symbol to get its current funding rate. Ensure the symbol is valid. ```typescript const fundingRate = useFundingRate("PERP_ETH_USDC"); ``` -------------------------------- ### Initialize and Use Poster Hook Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/tech-doc/modules/orderly_network_hooks.mdx Demonstrates how to initialize the `usePoster` hook with various configuration options and access its returned methods for poster manipulation. ```tsx const { ref, toDataURL, toBlob, download, copy } = usePoster({ backgroundColor: "#0b8c70", backgroundImg: "/images/poster_bg.png", color: "rgba(255, 255, 255, 0.98)", profitColor: "rgb(0,181,159)", // ... }); ``` -------------------------------- ### Orderly Network Error Response Example Source: https://context7.com/orderlynetwork/documentation-public/llms.txt This is an example of a structured error response from Orderly Network, indicating a failure with a specific numeric code and a descriptive message. ```json { "success": false, "code": -1101, "message": "Risk exposure is too high." } ``` -------------------------------- ### WS Constructor Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/tech-doc/classes/orderly_network_net.WS.mdx Initializes a new instance of the WS class with the provided options. ```APIDOC ## constructor ### Description Initializes a new instance of the WS class. ### Parameters #### Parameters - **options** (WSOptions) - Required - Configuration options for the WebSocket connection. ``` -------------------------------- ### Get Referral Info with useReferralInfo Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/referral/use-referral-info.mdx Use the useReferralInfo hook to destructure referral data, affiliate/trader status, error, loading state, and a function to get the first referral code. ```typescript const { data, isTrader, isAffiliate, error, isLoading, getFirstRefCode } = useReferralInfo(); ``` -------------------------------- ### useMarkPricesStream Usage Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/hooks/market-data/use-mark-prices-stream.mdx This example demonstrates how to use the `useMarkPricesStream` hook to fetch and display mark prices. ```APIDOC ## useMarkPricesStream ### Description Hook to stream mark prices for all symbols as a symbol-to-price map. ### Method Signature `useMarkPricesStream(): { data: Record }` ### Parameters This hook does not accept any parameters. ### Returns - `data` (Record): An object where keys are symbols (string) and values are their corresponding mark prices (number). ### Example ```ts const { data: markPrices }: { data: Record } = useMarkPricesStream(); ``` ``` -------------------------------- ### Constructor Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/tech-doc/classes/orderly_network_core.MockKeyStore.mdx Initializes a new instance of the MockKeyStore class. It requires a secret key upon instantiation. ```APIDOC ## new MockKeyStore(secretKey: string) ### Description Initializes a new instance of the MockKeyStore class. ### Parameters #### Parameters - **secretKey** (string) - The secret key to initialize the keystore with. ``` -------------------------------- ### Register Account with EIP712 Signature Source: https://github.com/orderlynetwork/documentation-public/blob/main/build-on-omnichain/user-flows/accounts.mdx This example demonstrates how to register an account on Orderly Network using EIP712 for signing. It includes fetching a registration nonce, constructing the message, signing it with a private key, and submitting the registration request. ```Java import java.time.Instant; import org.apache.commons.codec.binary.Hex; import org.json.JSONObject; import org.web3j.crypto.*; import io.github.cdimascio.dotenv.Dotenv; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class RegisterExample { public static JSONObject MESSAGE_TYPES = new JSONObject(""" { "EIP712Domain": [ {"name": "name", "type": "string"}, {"name": "version", "type": "string"}, {"name": "chainId", "type": "uint256"}, {"name": "verifyingContract", "type": "address"}, ], "Registration": [ {"name": "brokerId", "type": "string"}, {"name": "chainId", "type": "uint256"}, {"name": "timestamp", "type": "uint64"}, {"name": "registrationNonce", "type": "uint256"}, ], }""" ); public static JSONObject OFF_CHAIN_DOMAIN = new JSONObject(""" { "name": "Orderly", "version": "1", "chainId": 421614, "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", }""" ); public static void main(String[] args) throws Exception { String baseUrl = "https://testnet-api.orderly.org"; String brokerId = "woofi_dex"; int chainId = 421614; Dotenv dotenv = Dotenv.load(); String pk = dotenv.get("PRIVATE_KEY"); Credentials credentials = Credentials.create(ECKeyPair.create(Hex.decodeHex(pk))); OkHttpClient client = new OkHttpClient(); Request nonceReq = new Request.Builder() .url(baseUrl + "/v1/registration_nonce") .build(); String nonceRes; try (Response response = client.newCall(nonceReq).execute()) { nonceRes = response.body().string(); } JSONObject nonceObj = new JSONObject(nonceRes); String registrationNonce = nonceObj.getJSONObject("data").getString("registration_nonce"); JSONObject registerMessage = new JSONObject(); registerMessage.put("brokerId", brokerId); registerMessage.put("chainId", chainId); registerMessage.put("timestamp", Instant.now().toEpochMilli()); registerMessage.put("registrationNonce", registrationNonce); JSONObject jsonObject = new JSONObject(); jsonObject.put("types", RegisterExample.MESSAGE_TYPES); jsonObject.put("primaryType", "Registration"); jsonObject.put("domain", RegisterExample.OFF_CHAIN_DOMAIN); jsonObject.put("message", registerMessage); Sign.SignatureData signature = Sign.signTypedData(jsonObject.toString(), credentials.getEcKeyPair()); JSONObject jsonBody = new JSONObject(); jsonBody.put("message", registerMessage); jsonBody.put("signature", RegisterExample.signatureToHashString(signature)); jsonBody.put("userAddress", credentials.getAddress()); RequestBody body = RequestBody.create(jsonBody.toString(), MediaType.get("application/json")); Request registerReq = new Request.Builder() .url(baseUrl + "/v1/register_account") .post(body) .build(); String registerRes; try (Response response = client.newCall(registerReq).execute()) { registerRes = response.body().string(); } JSONObject registerObj = new JSONObject(registerRes); String orderlyAccountId = registerObj.getJSONObject("data").getString("account_id"); System.out.println("orderlyAccountId: " + orderlyAccountId); } public static String signatureToHashString(Sign.SignatureData signature) { byte[] retval = new byte[65]; System.arraycopy(signature.getR(), 0, retval, 0, 32); System.arraycopy(signature.getS(), 0, retval, 32, 32); System.arraycopy(signature.getV(), 0, retval, 64, 1); return Numeric.toHexString(retval); } } ``` -------------------------------- ### Create Next.js Project Source: https://github.com/orderlynetwork/documentation-public/blob/main/sdks/react/next.mdx Use Create Next App to initialize a new Next.js project with TypeScript and ESLint. ```bash npx create-next-app@latest my-exchange --app --typescript --eslint cd my-exchange ``` -------------------------------- ### Sign Request (Python) Source: https://github.com/orderlynetwork/documentation-public/blob/main/build-on-omnichain/api-authentication.mdx Demonstrates how to sign and send an API request using Python, including setting up the session and signer. ```python import json import os from base58 import b58decode from requests import Request, Session from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from signer import Signer base_url = "https://testnet-api.orderly.org" orderly_account_id = "" key = b58decode(os.environ.get("ORDERLY_SECRET")) orderly_key = Ed25519PrivateKey.from_private_bytes(key) session = Session() signer = Signer(orderly_account_id, orderly_key) req = signer.sign_request( Request( "POST", "%s/v1/order" % base_url, json={ "symbol": "PERP_ETH_USDC", "order_type": "MARKET", "order_quantity": 0.01, "side": "BUY", }, ) ) res = session.send(req) response = json.loads(res.text) ```