### Local Development Setup (Bun) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md Instructions for setting up and running the API locally using Bun. Includes installation, starting in production or development mode, and running various test suites. ```bash cd packages/api # Install and start bun install bun run start # Production mode bun run dev # Development mode with hot reload # Run tests bun test # All tests bun run test:db # Database tests only bun run test:handlers # API handler tests only bun run test:integration # Integration tests only ``` -------------------------------- ### Install and Build Project Dependencies Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/packages/contracts/README.md Installs project dependencies using Bun and builds the project. This is a standard setup step for projects managed with Bun. ```bash bun install bun run build ``` -------------------------------- ### Project Installation (Bun) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md Steps to clone the repository and install project dependencies using Bun. This is a prerequisite for local development. ```bash # Clone the repository git clone cd aztec-otc-desk # Install dependencies for all packages bun install ``` -------------------------------- ### Start Orderflow Service (Bash) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/packages/api/README.md Installs dependencies and starts the Orderflow Service in production or development mode. The service is accessible at http://localhost:3000. ```bash bun install bun run start # Production mode bun run dev # Development mode with hot reload ``` -------------------------------- ### Run Aztec Sandbox and PXE Tests Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/packages/contracts/README.md Commands to start the Aztec sandbox and PXE clients, followed by running unit tests. This setup is necessary for testing the smart contracts in a local environment. ```bash # Terminal 1: Start Aztec sandbox & two PXE clients bun run sandbox # Terminal 2 # Run PXE tests bun test # Run TXE tests bun run test:nr ``` -------------------------------- ### Build and Test Aztec Noir Contracts Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md Commands to build, test, and run unit tests for the Aztec Noir smart contracts. This includes starting the Aztec Sandbox, installing dependencies, and executing different test suites (TXE, PXE, or both). ```bash # Terminal 1: Start Aztec Sandbox bun run sandbox # Terminal 2: Build and run tests cd packages/contracts bun install bun run build ## Run the TXE tests bun run test:nr ## Run the PXE tests bun test ## Run both tests bun run test ``` -------------------------------- ### Contract Deployment and Demo Setup (Bun) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md Commands to build contracts, deploy token contracts, mint tokens, and perform OTC order operations using the CLI. Requires two terminals. ```bash # Build contracts first! bun install cd packages/contracts bun run build # REQUIRED: Build contracts before starting services cd - # Terminal 1 - Start Aztec Sandbox: bun run sandbox # Terminal 2 - Deploy Contracts & Run Demo: cd packages/cli bun run setup:deploy # Deploy token contracts bun run setup:mint # Mint tokens to trading accounts ⭐ REQUIRED bun run balances # Check balances after minting bun run order:create # Create OTC order (seller) bun run order:fill # Fill OTC order (buyer) bun run balances # Check final balances ``` -------------------------------- ### Run Aztec OTC Desk CLI Demo Workflow Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md Instructions to set up and run the Aztec OTC Desk CLI demo, covering contract deployment, token minting, account setup, order creation, order filling, and balance checks. Prerequisites include running the PXE and Orderflow API. ```bash # Build contracts bun install cd packages/contracts bun run build cd - cd packages/cli # 0. Setup .env cat .env.example > .env # edit to the testnet values if using testnet! # 2. Setup environment (run once per sandbox session) bun run setup:deploy bun run setup:mint # Mint tokens to trading accounts bun run balances # Check balances after minting # 3. Create an OTC order (seller perspective) bun run order:create # 4. Fill the order (buyer perspective) bun run order:fill # 5. Check final balances bun run balances ``` -------------------------------- ### Bun Development Commands Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/packages/api/README.md Common commands for managing the project using Bun. Includes installing dependencies, running in development and production modes, building the project, and running various test suites. ```bash bun install bun run dev bun run start bun run build bun test bun run test:db bun run test:handlers bun run test:integration bun run test:watch ``` -------------------------------- ### Build Contracts (Bun) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md Command to build the Aztec Noir smart contracts using Bun. This step is required before starting services or running contract tests. ```bash cd packages/contracts bun run build ``` -------------------------------- ### Complete Trading Workflow (Bash CLI) Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Demonstrates the complete process of creating and filling an OTC order using the command-line interface. This involves starting the sandbox, configuring the environment, deploying contracts, minting tokens, creating an order, filling the order, and checking final balances. ```bash # Terminal 1: Start Aztec Sandbox with PXEs and Orderflow API bun run sandbox # This starts: # - Aztec Sandbox node # - Two PXE instances (for seller and buyer) # - Orderflow API service on port 3000 # Terminal 2: Setup and execute trade cd packages/cli # Configure environment cp .env.example .env # Edit .env if needed: # L2_NODE_URL=http://localhost:8080 # API_URL=http://localhost:3000 # Build contracts first cd ../contracts bun run build cd ../cli # Deploy token contracts and setup accounts bun run setup:deploy # Output: # Connected to Aztec node at http://localhost:8080 # Deploying Wrapped Ether token contract # Ether token contract deployed, address: 0x1234567890abcdef1234567890abcdef12345678 # Deploying USD Coin token contract # USDC token contract deployed, address: 0xabcdef1234567890abcdef1234567890abcdef12 # Deployments written to /path/to/data/deployments.json # Mint tokens to trading accounts bun run setup:mint # Output: # Minting 10 ETH to seller (0x2b3c4d5e...) # Minting 10000 USDC to buyer (0x3c4d5e6f...) # Minting complete # Check initial balances bun run balances # Output: # Seller (0x2b3c4d5e...): # ETH: 10.0 # USDC: 0.0 # Buyer (0x3c4d5e6f...): # ETH: 0.0 # USDC: 10000.0 # Create OTC order (seller wants to sell 1 ETH for 5000 USDC) bun run order:create # Output: # Escrow contract deployed, address: 0x4d5e6f78..., secret key: 0x9876543210fedcba... # Depositing eth to escrow # 1 ETH deposited to escrow, transaction hash: 0xabcdef1234567890... # Order added to otc order service # Added order #550e8400-e29b-41d4-a716-446655440000 (address: 0x4d5e6f78...) # Fill the order (buyer pays 5000 USDC for 1 ETH) bun run order:fill # Output: # Found a matching order to fill # Attempting to fill order # Filled OTC order with txHash: 0x1234567890abcdef... # Order closed in OTC order service # Check final balances bun run balances # Output: # Seller (0x2b3c4d5e...): # ETH: 9.0 ``` -------------------------------- ### Create OTC Order (TypeScript) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md Example TypeScript code demonstrating how to create an OTC order. This involves deploying an escrow contract, transferring sell tokens, and registering the order with the orderflow service. ```typescript // 1. Deploy escrow contract with trade parameters const escrow = await OTCEscrowContract.deploy( sellTokenAddress, sellTokenAmount, buyTokenAddress, buyTokenAmount ).send().wait(); // 2. Transfer sell tokens to escrow await sellToken.methods.transfer(escrowAddress, sellTokenAmount).send().wait(); // 3. Register order with orderflow service const response = await fetch('http://localhost:3000/order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ escrowAddress: escrow.address, sellTokenAddress, sellTokenAmount: sellTokenAmount.toString(), buyTokenAddress, buyTokenAmount: buyTokenAmount.toString() }) }); ``` -------------------------------- ### Order Creation Response (JSON) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/packages/api/README.md Example of a successful response after creating a new order. Includes a success flag, a confirmation message, and the details of the created order, including the server-generated orderId. ```json { "success": true, "message": "Order created successfully", "data": { "orderId": "generated-uuid-here", "escrowAddress": "0x1234567890abcdef1234567890abcdef12345678", "sellTokenAddress": "0x5678901234abcdef5678901234abcdef56789012", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abcdef123456789abcdef123456789abcdef12", "buyTokenAmount": "2000000000000000000" } } ``` -------------------------------- ### GET /order Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Retrieves all available OTC orders from the orderflow service, allowing traders to browse open trading opportunities. ```APIDOC ## GET /order ### Description Retrieves all available orders from the orderflow service, allowing traders to browse open trading opportunities. ### Method GET ### Endpoint `/order` ### Parameters #### Query Parameters - **id** (string) - Optional - The unique identifier of the order to retrieve. If provided, returns a single order; otherwise, returns all orders. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the orders were retrieved successfully. - **message** (string) - A confirmation message, possibly indicating the number of orders retrieved. - **data** (array or object) - An array of order objects if no ID is specified, or a single order object if an ID is provided. - **orderId** (string) - The unique identifier for the order. - **escrowAddress** (string) - The address of the escrow contract. - **contractInstance** (string) - The contract instance details. - **secretKey** (string) - The secret key for the order. - **sellTokenAddress** (string) - The address of the token being sold. - **sellTokenAmount** (string) - The amount of the token being sold. - **buyTokenAddress** (string) - The address of the token being bought. - **buyTokenAmount** (string) - The amount of the token being bought. #### Response Example (All Orders) ```json { "success": true, "message": "Retrieved 2 order(s)", "data": [ { "orderId": "550e8400-e29b-41d4-a716-446655440000", "escrowAddress": "0x1a2b3c4d5e6f7890abcdef1234567890abcdef12", "contractInstance": "{...}", "secretKey": "0x1234567890abcdef...", "sellTokenAddress": "0x5678901234567890abcdef1234567890abcdef12", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abcdef1234567890abcdef1234567890abcdef12", "buyTokenAmount": "5000000000" }, { "orderId": "660f9511-f3ac-52e5-b827-557766551111", "escrowAddress": "0x2b3c4d5e6f7890abcdef1234567890abcdef1234", "sellTokenAddress": "0x6789012345678901bcdef1234567890abcdef23", "sellTokenAmount": "2000000000000000000", "buyTokenAddress": "0xabcdef1234567890abcdef1234567890abcdef23", "buyTokenAmount": "10000000000" } ] } ``` #### Response Example (Specific Order by ID) ```json { "success": true, "message": "Order retrieved successfully", "data": [ { "orderId": "550e8400-e29b-41d4-a716-446655440000", "escrowAddress": "0x1a2b3c4d5e6f7890abcdef1234567890abcdef12", "contractInstance": "{...}", "secretKey": "0x1234567890abcdef...", "sellTokenAddress": "0x5678901234567890abcdef1234567890abcdef12", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abcdef1234567890abcdef1234567890abcdef12", "buyTokenAmount": "5000000000" } ] } ``` ``` -------------------------------- ### Get Escrow Configuration (TypeScript) Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Retrieves the configuration parameters of an escrow contract to verify trade details. This function requires wallet, user address, escrow contract instance, and a secret key. It outputs the sell and buy token addresses and amounts. ```typescript import { getEscrowConfig, getEscrowContract } from "@aztec-otc-desk/contracts/contract"; import { AztecAddress } from "@aztec/aztec.js/addresses"; import { Fr } from "@aztec/aztec.js/fields"; import { createPXEClient } from "@aztec/aztec.js"; import { ContractInstanceWithAddressSchema } from "@aztec/stdlib/contract"; // Setup const pxe = createPXEClient("http://localhost:8080"); const [account] = await pxe.getRegisteredAccounts(); const wallet = await getWallet(pxe, account.address); const userAddress = account.address; // Get escrow contract const escrowAddress = AztecAddress.fromString("0x2b3c4d5e6f7890abcdef1234567890abcdef1234"); const escrowInstance = ContractInstanceWithAddressSchema.parse({ version: 1, salt: "0x123...", deployer: "0xabc...", contractClassId: "0xdef...", initializationHash: "0x456...", publicKeys: { /* ... */ } }); const escrowSecretKey = Fr.fromString("0x9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba"); const escrowContract = await getEscrowContract( wallet, userAddress, escrowAddress, escrowInstance, escrowSecretKey ); // Get configuration const config = await getEscrowConfig( wallet, userAddress, escrowContract, { from: userAddress } ); console.log(`Sell Token: ${config.sell_token_address.toString()}`); console.log(`Sell Amount: ${config.sell_token_amount}`); console.log(`Buy Token: ${config.buy_token_address.toString()}`); console.log(`Buy Amount: ${config.buy_token_amount}`); ``` -------------------------------- ### GET /order Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/packages/api/README.md Retrieves order(s) from the system. Supports filtering by order ID, escrow address, sell token address, and buy token address. Always returns an array for consistent interface. ```APIDOC ## GET /order ### Description Retrieves order(s) from the system. Supports filtering by order ID, escrow address, sell token address, and buy token address. Always returns an array for consistent interface. ### Method GET ### Endpoint /order ### Parameters #### Query Parameters - **id** (string) - Optional - Get specific order by order ID. - **escrow_address** (string) - Optional - Filter by escrow address. - **sell_token_address** (string) - Optional - Filter by sell token address. - **buy_token_address** (string) - Optional - Filter by buy token address. ### Request Example ```bash curl http://localhost:3000/order?id=uuid-1 ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - A message describing the result of the request. - **data** (array) - An array of order objects. - **orderId** (string) - The unique identifier of the order. - **escrowAddress** (string) - The address of the escrow. - **sellTokenAddress** (string) - The address of the token being sold. - **sellTokenAmount** (string) - The amount of the sell token. - **buyTokenAddress** (string) - The address of the token being bought. - **buyTokenAmount** (string) - The amount of the buy token. #### Response Example ```json { "success": true, "message": "Retrieved 1 order(s) filtered by sell token: 0x5678901234abcdef5678901234abcdef56789012", "data": [ { "orderId": "uuid-1", "escrowAddress": "0x1234567890abcdef1234567890abcdef12345678", "sellTokenAddress": "0x5678901234abcdef5678901234abcdef56789012", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abcdef123456789abcdef123456789abcdef12", "buyTokenAmount": "2000000000000000000" } ] } ``` #### Error Response (404 Not Found) - **success** (boolean) - Indicates if the request was successful. - **error** (string) - A message describing the error. - **data** (array) - An empty array. #### Error Response Example ```json { "success": false, "error": "Order with ID uuid-nonexistent not found", "data": [] } ``` ``` -------------------------------- ### Aztec OTC Desk Orderflow Service API Endpoints Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md Examples of RESTful API calls to the Orderflow Service for managing private OTC orders. This includes creating a new order via POST and retrieving orders via GET, with options for filtering. ```http POST /order Content-Type: application/json { "escrowAddress": "0x1234...", "sellTokenAddress": "0x5678...", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abc...", "buyTokenAmount": "2000000000000000000" } # Get all orders GET /order # Get specific order by ID GET /order?id=uuid-here # Filter by escrow address GET /order?escrow_address=0x1234... # Filter by token addresses GET /order?sell_token_address=0x5678... GET /order?buy_token_address=0x9abc... ``` -------------------------------- ### Order API Response Structures Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/packages/api/README.md Examples of JSON responses for the order API endpoint. Includes structures for retrieving all orders, a single specific order, filtered orders, an order not found error, and a successful filtered retrieval. ```json { "success": true, "message": "Retrieved 2 order(s)", "data": [ { "orderId": "uuid-1", "escrowAddress": "0x1234567890abcdef1234567890abcdef12345678", "sellTokenAddress": "0x5678901234abcdef5678901234abcdef56789012", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abcdef123456789abcdef123456789abcdef12", "buyTokenAmount": "2000000000000000000" }, { "orderId": "uuid-2", "escrowAddress": "0xabcdef1234567890abcdef1234567890abcdef12", "sellTokenAddress": "0xfedcba0987654321fedcba0987654321fedcba09", "sellTokenAmount": "5000000000000000000", "buyTokenAddress": "0x1111222233334444555566667777888899990000", "buyTokenAmount": "3000000000000000000" } ] } { "success": true, "message": "Order retrieved successfully", "data": [ { "orderId": "uuid-1", "escrowAddress": "0x1234567890abcdef1234567890abcdef12345678", "sellTokenAddress": "0x5678901234abcdef5678901234abcdef56789012", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abcdef123456789abcdef123456789abcdef12", "buyTokenAmount": "2000000000000000000" } ] } { "success": true, "message": "Retrieved 1 order(s) filtered by sell token: 0x5678901234abcdef5678901234abcdef56789012", "data": [ { "orderId": "uuid-1", "escrowAddress": "0x1234567890abcdef1234567890abcdef12345678", "sellTokenAddress": "0x5678901234abcdef5678901234abcdef56789012", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abcdef123456789abcdef123456789abcdef12", "buyTokenAmount": "2000000000000000000" } ] } { "success": false, "error": "Order with ID uuid-nonexistent not found", "data": [] } ``` -------------------------------- ### Order Creation Error Response (409 Conflict - JSON) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/packages/api/README.md Example of an error response when attempting to create an order with an escrow address that already exists. Returns a 409 Conflict status with an error message indicating the conflict. ```json { "success": false, "error": "Order with escrow address 0x1234567890abcdef1234567890abcdef12345678 already exists" } ``` -------------------------------- ### Get All OTC Orders using cURL Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Retrieves all currently available OTC orders from the orderflow service. This endpoint allows traders to browse open trading opportunities and is useful for discovering potential matches for trades. ```bash curl -X GET http://localhost:3000/order ``` -------------------------------- ### Run Project Services (Bun) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md Commands to run the bundled service with PXE connections to testnet or to build and run the docker container for the API. ```bash # Bundled service with 2 PXE's connected to testnet bun run testnet # Run docker container directly docker build -t otc-orderflow-api ./packages/api docker run -p 3000:3000 -v $(pwd)/data:/data otc-orderflow-api ``` -------------------------------- ### Deploy OTC Escrow Contract using TypeScript Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Deploys a new escrow contract instance on the Aztec network. This function initializes an escrow with specific trade parameters, including token addresses and amounts, and generates necessary encryption keys for private state management. It requires wallet and PXE client initialization. ```typescript import { deployEscrowContract } from "@aztec-otc-desk/contracts/contract"; import { AztecAddress } from "@aztec/aztec.js/addresses"; import { createPXEClient } from "@aztec/aztec.js"; // Initialize PXE client and wallet const pxe = createPXEClient("http://localhost:8080"); const [sellerAccount] = await pxe.getRegisteredAccounts(); const sellerWallet = await getWallet(pxe, sellerAccount.address); const sellerAddress = sellerAccount.address; // Define trade parameters const ethTokenAddress = AztecAddress.fromString("0x1234567890abcdef1234567890abcdef12345678"); const usdcTokenAddress = AztecAddress.fromString("0xabcdef1234567890abcdef1234567890abcdef12"); const sellAmount = 1000000000000000000n; // 1 ETH (18 decimals) const buyAmount = 5000000000n; // 5000 USDC (6 decimals) // Deploy escrow contract const { contract: escrowContract, secretKey } = await deployEscrowContract( sellerWallet, sellerAddress, ethTokenAddress, sellAmount, usdcTokenAddress, buyAmount, { send: { from: sellerAddress } } ); console.log(`Escrow deployed at: ${escrowContract.address.toString()}`); console.log(`Secret key: ${secretKey.toString()}`); ``` -------------------------------- ### Fill OTC Order using TypeScript Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md This snippet demonstrates how to fill an OTC order. It first queries for available orders, then connects to the relevant escrow contract, and finally executes the trade by sending a transaction to fill the order. Dependencies include a running local server at http://localhost:3000 and the OTCEscrowContract. ```typescript // 1. Query available orders const orders = await fetch('http://localhost:3000/order').then(r => r.json()); // 2. Connect to escrow contract const escrow = await OTCEscrowContract.at(orders.data[0].escrowAddress); // 3. Execute the trade await escrow.methods.fill_order().send().wait(); ``` -------------------------------- ### Run Contract Tests (Bun) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/README.md Commands to run tests for Aztec Noir smart contracts. Includes JS (PXE) tests, Noir (TXE) tests, and all contract tests. Requires a running sandbox. ```bash # Contract tests (requires running sandbox) cd packages/contracts bun test # Run JS (PXE) tests bun run test:nr # Run Noir (TXE) tests bun run test # Run all contract tests # Orderflow service tests cd packages/api bun test # All tests can be run independently ``` -------------------------------- ### Get Specific OTC Order by ID using cURL Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Retrieves a single, specific OTC order identified by its unique order ID. This is useful for inspecting the details of a particular order before deciding to fill it or for retrieving order information after a trade has been initiated. ```bash curl -X GET "http://localhost:3000/order?id=550e8400-e29b-41d4-a716-446655440000" ``` -------------------------------- ### Retrieve Orders with cURL Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/packages/api/README.md Demonstrates how to retrieve all orders or filter them using various query parameters via cURL. Supports filtering by order ID, escrow address, sell token address, and buy token address. Parameters can be combined for more specific results. ```bash curl http://localhost:3000/order curl http://localhost:3000/order?id=uuid-1 curl "http://localhost:3000/order?escrow_address=0x1234567890abcdef1234567890abcdef12345678" curl "http://localhost:3000/order?sell_token_address=0x5678901234abcdef5678901234abcdef56789012" curl "http://localhost:3000/order?buy_token_address=0x9abcdef123456789abcdef123456789abcdef12" curl "http://localhost:3000/order?sell_token_address=0x5678901234abcdef5678901234abcdef56789012&buy_token_address=0x9abcdef123456789abcdef123456789abcdef12" ``` -------------------------------- ### Deposit Tokens to Escrow (TypeScript) Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Deposits seller's tokens into the escrow contract using the provided wallet and contract instances. This function requires the seller's wallet, address, escrow contract, token contract, and the amount to deposit. It returns the transaction hash. ```typescript import { depositToEscrow, getTokenContract } from "@aztec-otc-desk/contracts/contract"; import { AztecAddress } from "@aztec/aztec.js/addresses"; import { createPXEClient } from "@aztec/aztec.js"; // Setup const pxe = createPXEClient("http://localhost:8080"); const [sellerAccount] = await pxe.getRegisteredAccounts(); const sellerWallet = await getWallet(pxe, sellerAccount.address); const sellerAddress = sellerAccount.address; // Get token and escrow contracts const ethTokenAddress = AztecAddress.fromString("0x1234567890abcdef1234567890abcdef12345678"); const ethToken = await getTokenContract(sellerWallet, sellerAddress, pxe, ethTokenAddress); const escrowAddress = AztecAddress.fromString("0x2b3c4d5e6f7890abcdef1234567890abcdef1234"); const escrowContract = await OTCEscrowContract.at(escrowAddress, sellerWallet); // Deposit tokens const depositAmount = 1000000000000000000n; // 1 ETH const txHash = await depositToEscrow( sellerWallet, sellerAddress, escrowContract, ethToken, depositAmount, { send: { from: sellerAddress } } ); console.log(`Deposit transaction hash: ${txHash.toString()}`); ``` -------------------------------- ### Initialize SQLite Database for OTC Orders Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Initializes the SQLite database schema required for storing OTC orders. This includes creating the 'orders' table with essential columns for order details, enabling efficient filtering and querying. It uses the SQLiteDatabase class from the '@aztec-otc-desk/api/db' module. ```typescript import { SQLiteDatabase } from "@aztec-otc-desk/api/db"; // Create and initialize database const database = new SQLiteDatabase("orders.sqlite"); database.initialize(); console.log("Database initialized with orders table"); // Creates table with columns: // - orderId (PRIMARY KEY) // - escrowAddress (UNIQUE) // - contractInstance // - secretKey // - sellTokenAddress // - sellTokenAmount // - buyTokenAddress // - buyTokenAmount // - createdAt ``` -------------------------------- ### Deploy Token Contract (TypeScript) Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Deploys a new fungible token contract on the Aztec network. This requires the deployer's wallet and address, along with metadata for the token (name, symbol, decimals). It returns the deployed token contract instance. ```typescript import { deployTokenContract } from "@aztec-otc-desk/contracts/contract"; import { AztecAddress } from "@aztec/aztec.js/addresses"; import { createPXEClient } from "@aztec/aztec.js"; // Setup const pxe = createPXEClient("http://localhost:8080"); const [deployerAccount] = await pxe.getRegisteredAccounts(); const deployerWallet = await getWallet(pxe, deployerAccount.address); const deployerAddress = deployerAccount.address; // Define token metadata const tokenMetadata = { name: "Wrapped Ether", symbol: "WETH", decimals: 18 }; // Deploy token contract const tokenContract = await deployTokenContract( deployerWallet, deployerAddress, tokenMetadata, { send: { from: deployerAddress } } ); console.log(`Token contract deployed at: ${tokenContract.address.toString()}`); ``` -------------------------------- ### Fill OTC Order (TypeScript) Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Executes an OTC trade by atomically transferring the buyer's tokens to the escrow and receiving the seller's tokens. This requires buyer's wallet, address, escrow contract details, token contract, and the amount to buy. It interacts with a local API to fetch order details and then closes the order after execution. Returns the transaction hash. ```typescript import { fillOTCOrder, getTokenContract, getEscrowContract } from "@aztec-otc-desk/contracts/contract"; import { AztecAddress } from "@aztec/aztec.js/addresses"; import { Fr } from "@aztec/aztec.js/fields"; import { createPXEClient } from "@aztec/aztec.js"; import { ContractInstanceWithAddressSchema } from "@aztec/stdlib/contract"; // Setup buyer wallet const pxe = createPXEClient("http://localhost:8080"); const accounts = await pxe.getRegisteredAccounts(); const buyerAccount = accounts[1]; // Second account is buyer const buyerWallet = await getWallet(pxe, buyerAccount.address); const buyerAddress = buyerAccount.address; // Fetch order from API const orderResponse = await fetch("http://localhost:3000/order"); const { data: orders } = await orderResponse.json(); const order = orders[0]; // Parse order details const escrowAddress = AztecAddress.fromString(order.escrowAddress); const escrowInstance = ContractInstanceWithAddressSchema.parse(JSON.parse(order.contractInstance)); const escrowSecretKey = Fr.fromString(order.secretKey); const usdcAddress = AztecAddress.fromString(order.buyTokenAddress); const buyAmount = BigInt(order.buyTokenAmount); // Get contracts const usdcToken = await getTokenContract(buyerWallet, buyerAddress, pxe, usdcAddress); const escrowContract = await getEscrowContract( buyerWallet, buyerAddress, escrowAddress, escrowInstance, escrowSecretKey ); // Fill the order const txHash = await fillOTCOrder( buyerWallet, buyerAddress, escrowContract, usdcToken, buyAmount, { send: { from: buyerAddress } } ); console.log(`Order filled, transaction hash: ${txHash.toString()}`); // Close the order in the API await fetch(`http://localhost:3000/order?id=${order.orderId}`, { method: "DELETE" }); ``` -------------------------------- ### Deploy OTC Escrow Contract Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Deploys a new escrow contract instance with trade parameters, generating encryption keys for private state management. ```APIDOC ## Deploy OTC Escrow Contract ### Description Deploys a new escrow contract instance with trade parameters, generating encryption keys for private state management. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters #### Request Body (Implicit via function arguments) - **sellerWallet**: Wallet object for the seller. - **sellerAddress**: The address of the seller. - **ethTokenAddress**: The address of the ETH token contract. - **sellAmount**: The amount of ETH to be sold. - **usdcTokenAddress**: The address of the USDC token contract. - **buyAmount**: The amount of USDC to be bought. ### Request Example ```typescript import { deployEscrowContract } from "@aztec-otc-desk/contracts/contract"; import { AztecAddress } from "@aztec.js/addresses"; import { createPXEClient } from "@aztec.js"; // Initialize PXE client and wallet const pxe = createPXEClient("http://localhost:8080"); const [sellerAccount] = await pxe.getRegisteredAccounts(); const sellerWallet = await getWallet(pxe, sellerAccount.address); const sellerAddress = sellerAccount.address; // Define trade parameters const ethTokenAddress = AztecAddress.fromString("0x1234567890abcdef1234567890abcdef12345678"); const usdcTokenAddress = AztecAddress.fromString("0xabcdef1234567890abcdef1234567890abcdef12"); const sellAmount = 1000000000000000000n; // 1 ETH (18 decimals) const buyAmount = 5000000000n; // 5000 USDC (6 decimals) // Deploy escrow contract const { contract: escrowContract, secretKey } = await deployEscrowContract( sellerWallet, sellerAddress, ethTokenAddress, sellAmount, usdcTokenAddress, buyAmount, { send: { from: sellerAddress } } ); console.log(`Escrow deployed at: ${escrowContract.address.toString()}`); console.log(`Secret key: ${secretKey.toString()}`); ``` ### Response #### Success Response - **escrowContract**: The deployed escrow contract object. - **secretKey**: The secret key generated for the escrow contract. #### Response Example ``` Escrow deployed at: 0x2b3c4d5e6f7890abcdef1234567890abcdef1234 Secret key: 0x9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba ``` ``` -------------------------------- ### Query OTC Orders with Flexible Filters in SQLite Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Retrieves OTC orders from the SQLite database using various filtering options. This includes fetching all orders, retrieving a specific order by its ID, filtering by sell or buy token addresses, and applying complex filters combining multiple criteria. It demonstrates the use of `getAllOrders`, `getOrderById`, `getOrdersBySellToken`, `getOrdersByBuyToken`, and `getOrdersWithFilters` methods. ```typescript import { SQLiteDatabase } from "@aztec-otc-desk/api/db"; const database = new SQLiteDatabase("orders.sqlite"); database.initialize(); // Get all orders const allOrders = database.getAllOrders(); console.log(`Found ${allOrders.length} total orders`); // Get order by ID const order = database.getOrderById("550e8400-e29b-41d4-a716-446655440000"); console.log(`Order escrow: ${order?.escrowAddress}`); // Filter by sell token (find all ETH sellers) const ethSellers = database.getOrdersBySellToken("0x1234567890abcdef1234567890abcdef12345678"); console.log(`Found ${ethSellers.length} orders selling ETH`); // Filter by buy token (find all USDC buyers) const usdcBuyers = database.getOrdersByBuyToken("0xabcdef1234567890abcdef1234567890abcdef12"); console.log(`Found ${usdcBuyers.length} orders buying USDC`); // Complex filtering const matchingOrders = database.getOrdersWithFilters({ sellTokenAddress: "0x1234567890abcdef1234567890abcdef12345678", buyTokenAddress: "0xabcdef1234567890abcdef1234567890abcdef12" }); console.log(`Found ${matchingOrders.length} ETH/USDC orders`); // Output: // Found 5 total orders // Order escrow: 0x1a2b3c4d5e6f7890abcdef1234567890abcdef12 // Found 3 orders selling ETH // Found 4 orders buying USDC // Found 2 ETH/USDC orders ``` -------------------------------- ### POST /order Source: https://context7.com/aztec-pioneers/aztec-otc-desk/llms.txt Creates a new OTC order by registering escrow contract details with the orderflow service. This allows other traders to discover and fill the order. ```APIDOC ## POST /order ### Description Creates a new OTC order by registering escrow contract details with the orderflow service, enabling other traders to discover and fill the order. ### Method POST ### Endpoint `/order` ### Parameters #### Request Body - **escrowAddress** (string) - Required - The address of the escrow contract. - **contractInstance** (string) - Required - A JSON string representing the contract instance details. - **secretKey** (string) - Required - The secret key for the order. - **sellTokenAddress** (string) - Required - The address of the token being sold. - **sellTokenAmount** (string) - Required - The amount of the token being sold (as a string to handle large numbers). - **buyTokenAddress** (string) - Required - The address of the token being bought. - **buyTokenAmount** (string) - Required - The amount of the token being bought (as a string to handle large numbers). ### Request Example ```json { "escrowAddress": "0x1a2b3c4d5e6f7890abcdef1234567890abcdef12", "contractInstance": "{\"version\":1,\"salt\":\"0x123...\",\"deployer\":\"0xabc...\",\"contractClassId\":\"0xdef...\",\"initializationHash\":\"0x456...\",\"publicKeys\":{\"masterNullifierPublicKey\":{\"x\":\"0x789...\",\"y\":\"0xabc...\"},\"masterIncomingViewingPublicKey\":{\"x\":\"0xdef...\",\"y\":\"0x012...\"},\"masterOutgoingViewingPublicKey\":{\"x\":\"0x345...\",\"y\":\"0x678...\"},\"masterTaggingPublicKey\":{\"x\":\"0x9ab...\",\"y\":\"0xcde...\"}}"}", "secretKey": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "sellTokenAddress": "0x5678901234567890abcdef1234567890abcdef12", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abcdef1234567890abcdef1234567890abcdef12", "buyTokenAmount": "5000000000" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the order was created successfully. - **message** (string) - A confirmation message. - **data** (object) - Contains the details of the created order. - **orderId** (string) - The unique identifier for the order. - **escrowAddress** (string) - The address of the escrow contract. - **contractInstance** (string) - The contract instance details. - **secretKey** (string) - The secret key for the order. - **sellTokenAddress** (string) - The address of the token being sold. - **sellTokenAmount** (string) - The amount of the token being sold. - **buyTokenAddress** (string) - The address of the token being bought. - **buyTokenAmount** (string) - The amount of the token being bought. #### Response Example ```json { "success": true, "message": "Order created successfully", "data": { "orderId": "550e8400-e29b-41d4-a716-446655440000", "escrowAddress": "0x1a2b3c4d5e6f7890abcdef1234567890abcdef12", "contractInstance": "{...}", "secretKey": "0x1234567890abcdef...", "sellTokenAddress": "0x5678901234567890abcdef1234567890abcdef12", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abcdef1234567890abcdef1234567890abcdef12", "buyTokenAmount": "5000000000" } } ``` #### Error Response (409 Conflict) - **success** (boolean) - Indicates if the order creation failed. - **error** (string) - An error message detailing the reason for failure (e.g., duplicate escrow address). ```json { "success": false, "error": "Order with escrow address 0x1a2b3c4d... already exists" } ``` ``` -------------------------------- ### Create New Order (cURL) Source: https://github.com/aztec-pioneers/aztec-otc-desk/blob/main/packages/api/README.md Creates a new private OTC order using a POST request to the /order endpoint. Requires order details including escrow and token addresses and amounts. Handles potential conflicts if an escrow address is reused. ```bash curl -X POST http://localhost:3000/order \ -H "Content-Type: application/json" \ -d '{ "escrowAddress": "0x1234567890abcdef1234567890abcdef12345678", "sellTokenAddress": "0x5678901234abcdef5678901234abcdef56789012", "sellTokenAmount": "1000000000000000000", "buyTokenAddress": "0x9abcdef123456789abcdef123456789abcdef12", "buyTokenAmount": "2000000000000000000" }' ```