### Quick Start: Simple CoW Hook dApp Example Source: https://docs.cow.fi/cow-protocol/tutorials/hook-dapp A basic HTML and JavaScript example demonstrating how to create a CoW Hook dApp. It initializes the CoW Hook dApp library, checks the COW token balance of the order creator, and allows adding or editing a hook. ```html
``` -------------------------------- ### Cow Protocol Basic Swap Example (TypeScript) Source: https://docs.cow.fi/cow-protocol/reference/sdks/cow-sdk Demonstrates a basic swap using the Cow Protocol SDK with ViemAdapter. It covers getting a quote, verifying amounts, and posting an order. ```typescript import { SupportedChainId, OrderKind, TradeParameters, TradingSdk } from '@cowprotocol/cow-sdk' import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter' import { createPublicClient, http, privateKeyToAccount } from 'viem' import { sepolia } from 'viem/chains' // EthersV5Adapter and EthersV6Adapter are also available // @cowprotocol/sdk-ethers-v5-adapter, @cowprotocol/sdk-ethers-v6-adapter const adapter = new ViemAdapter({ provider: createPublicClient({ chain: sepolia, transport: http('YOUR_RPC_URL') }), // You can also set `walletClient` instead of `signer` using `useWalletClient` from wagmi signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`) }) const sdk = new TradingSdk({ chainId: SupportedChainId.SEPOLIA, appCode: 'YOUR_APP_CODE', }, {}, adapter) const parameters: TradeParameters = { kind: OrderKind.SELL, sellToken: '0xfff9976782d46cc05630d1f6ebab18b2324d6b14', sellTokenDecimals: 18, buyToken: '0x0625afb445c3b6b7b929342a04a22599fd5dbb59', buyTokenDecimals: 18, amount: '120000000000000', } // Get quote const { quoteResults, postSwapOrderFromQuote } = await sdk.getQuote(parameters) const buyAmount = quoteResults.amountsAndCosts.afterSlippage.buyAmount // Verify amount if (confirm(`You will receive at least: ${buyAmount}. Proceed?`)) { // Sign and post order const orderId = await postSwapOrderFromQuote() console.log('Order created, ID:', orderId) } ``` -------------------------------- ### Install CoW Widget Library (npm) Source: https://docs.cow.fi/cow-protocol/integrate/widget Installs the necessary library for the CoW Widget. This is the first step to integrating the widget into your project. ```bash # Install the widget library npm install @cowprotocol/widget-lib ``` -------------------------------- ### Install CoW Swap Widget Library (npm) Source: https://docs.cow.fi/cow-protocol/tutorials/widget Installs the CoW Swap widget library using npm. This command is an alternative to the Yarn installation for npm users. ```bash npm install @cowprotocol/widget-lib ``` -------------------------------- ### Installing CoW SDK Blockchain Adapters Source: https://docs.cow.fi/cow-protocol/reference/sdks/cow-sdk Provides installation commands for different blockchain adapters compatible with the CoW SDK. It includes instructions for Ethers.js v6, Ethers.js v5, and Viem using pnpm. ```bash # For ethers v6 pnpm add @cowprotocol/sdk-ethers-v6-adapter ethers # For ethers v5 pnpm add @cowprotocol/sdk-ethers-v5-adapter ethers@^5.7.0 # For viem pnpm add @cowprotocol/sdk-viem-adapter viem ``` -------------------------------- ### Install CoW Swap Widget Library (Yarn) Source: https://docs.cow.fi/cow-protocol/tutorials/widget Installs the CoW Swap widget library using Yarn. This is the first step to integrating the widget into your project. ```bash yarn add @cowprotocol/widget-lib ``` -------------------------------- ### Install @cowprotocol/hook-dapp-lib using npm Source: https://docs.cow.fi/cow-protocol/tutorials/hook-dapp Installs the CoW Hook dApp library using the npm package manager. This library is crucial for integrating custom hooks with CoW Swap. ```bash npm install @cowprotocol/hook-dapp-lib ``` -------------------------------- ### Order Signing Example (ethers.js) Source: https://docs.cow.fi/cow-protocol/integrate/api Example code demonstrating how to sign an order using ethers.js for EIP-712 compliance. ```APIDOC ## Order Signing with ethers.js ### Description Orders must be cryptographically signed before submission. This example shows how to sign an order using the ethers.js library. ### Code Example ```javascript import { ethers } from 'ethers'; // Assume 'signer' is an Ethers.js signer instance and 'orderData' is the order object const domain = { name: 'Gnosis Protocol', version: 'v2', chainId: 1, // Replace with the correct chain ID verifyingContract: '0x9008D19f58AAbD9E30D60971565AA8510560ab41' // Replace with the correct verifying contract address }; const types = { Order: [ { name: 'sellToken', type: 'address' }, { name: 'buyToken', type: 'address' }, { name: 'receiver', type: 'address' }, { name: 'sellAmount', type: 'uint256' }, { name: 'buyAmount', type: 'uint256' }, { name: 'feeAmount', type: 'uint256' }, { name: ' தாக்க', type: 'address' }, { name: 'gasPrice', type: 'uint256' }, { name: 'gasAmount', type: 'uint256' }, { name: 'requiredConfirmations', type: 'uint32' }, { name: 'isSellOrder', type: 'bool' }, // Include other order fields as necessary based on the specific protocol version ] }; // orderData should be structured according to the 'types.Order' schema // const orderData = { ... }; // const signature = await signer._signTypedData(domain, types, orderData); // console.log('Order Signature:', signature); ``` ``` -------------------------------- ### Install CoW SDK with pnpm Source: https://docs.cow.fi/cow-protocol/reference/sdks/cow-sdk Installs the CoW SDK package using the pnpm package manager. This is a common way to add dependencies to Node.js projects. ```bash pnpm add @cowprotocol/cow-sdk ``` -------------------------------- ### Install @cowprotocol/hook-dapp-lib using Yarn Source: https://docs.cow.fi/cow-protocol/tutorials/hook-dapp Installs the CoW Hook dApp library using the Yarn package manager. This library provides essential tools for developing custom hooks. ```bash yarn add @cowprotocol/hook-dapp-lib ``` -------------------------------- ### Install CoW SDK and Adapters (npm) Source: https://docs.cow.fi/cow-protocol/integrate/sdk Commands to install the CoW SDK and one of its compatible blockchain adapters using npm. Choose the adapter that matches your project's blockchain interaction library (Viem, Ethers v6, or Ethers v5). ```bash # Install the SDK npm install @cowprotocol/cow-sdk # Install an adapter (choose one) npm install @cowprotocol/sdk-viem-adapter viem npm install @cowprotocol/sdk-ethers-v6-adapter ethers npm install @cowprotocol/sdk-ethers-v5-adapter ethers@^5.7.0 ``` -------------------------------- ### eth_cancelBundle Request Example (JSON) Source: https://docs.cow.fi/mevblocker/searchers/API%20Reference/cancel_bundle This example demonstrates the structure of a request to the eth_cancelBundle method. It requires a JSON-RPC payload including the method name and parameters, specifically the 'replacementUuid' to identify the bundle for cancellation. The 'replacementUuid' is an arbitrary string used to target the bundle. ```json { "jsonrpc": "2.0", "id": 1, "method": "eth_cancelBundle", "params": [ { "replacementUuid": "mevblocker" } ] } ``` -------------------------------- ### Setting Up ViemAdapter for CoW SDK Source: https://docs.cow.fi/cow-protocol/reference/sdks/cow-sdk This code snippet illustrates how to set up the ViemAdapter for the CoW SDK. It requires creating a viem public client and an account from a private key, which are then used to instantiate the adapter. ```javascript import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter' import { http, createPublicClient, privateKeyToAccount } from 'viem' import { sepolia } from 'viem/chains' const account = privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`) const transport = http('YOUR_RPC_URL') const provider = createPublicClient({ chain: sepolia, transport }) // You can also set `walletClient` instead of `signer` using `useWalletClient` from wagmi const adapter = new ViemAdapter({ provider, signer: account }) ``` -------------------------------- ### Setting Up EthersV5Adapter for CoW SDK Source: https://docs.cow.fi/cow-protocol/reference/sdks/cow-sdk This example demonstrates setting up the EthersV5Adapter for the CoW SDK. It involves creating an ethers.js v5 provider and wallet, and then initializing the adapter with these instances. ```javascript import { EthersV5Adapter } from '@cowprotocol/sdk-ethers-v5-adapter' import { ethers } from 'ethers' const provider = new ethers.providers.JsonRpcProvider('YOUR_RPC_URL') const wallet = new ethers.Wallet('YOUR_PRIVATE_KEY', provider) const adapter = new EthersV5Adapter({ provider, signer: wallet }) ``` -------------------------------- ### Setting Up EthersV6Adapter for CoW SDK Source: https://docs.cow.fi/cow-protocol/reference/sdks/cow-sdk This example shows how to set up the EthersV6Adapter for use with the CoW SDK. It requires initializing an ethers.js v6 provider and wallet, then passing them to the adapter. ```javascript import { EthersV6Adapter } from '@cowprotocol/sdk-ethers-v6-adapter' import { JsonRpcProvider, Wallet } from 'ethers' const provider = new JsonRpcProvider('YOUR_RPC_URL') const wallet = new Wallet('YOUR_PRIVATE_KEY', provider) const adapter = new EthersV6Adapter({ provider, signer: wallet }) ``` -------------------------------- ### Install CoW SDK with yarn Source: https://docs.cow.fi/cow-protocol/reference/sdks/cow-sdk Installs the CoW SDK package using the yarn package manager. This is another popular method for managing project dependencies. ```bash yarn add @cowprotocol/cow-sdk ``` -------------------------------- ### Perform a Sell Order Trade with CoW SDK (TypeScript, Viem) Source: https://docs.cow.fi/cow-protocol/integrate/sdk This example demonstrates how to set up the CoW SDK with a Viem adapter to perform a sell order. It includes initializing the SDK, defining trade parameters for selling USDC for WETH, fetching a quote, and executing the trade. Ensure you replace placeholder values like YOUR_RPC_URL, YOUR_PRIVATE_KEY, and YOUR_APP_CODE. ```typescript import { SupportedChainId, OrderKind, TradeParameters, TradingSdk } from '@cowprotocol/cow-sdk' import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter' import { createPublicClient, http, privateKeyToAccount } from 'viem' import { mainnet } from 'viem/chains' // Setup adapter const adapter = new ViemAdapter({ provider: createPublicClient({ chain: mainnet, transport: http('YOUR_RPC_URL') }), signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`) }) // Initialize SDK const sdk = new TradingSdk({ chainId: SupportedChainId.MAINNET, appCode: 'YOUR_APP_CODE', }, {}, adapter) // Define trade parameters const parameters: TradeParameters = { kind: OrderKind.SELL, sellToken: '0xA0b86a33E6411Ec5d0b9dd2E7dC15A9CAA6C1F8e', // USDC sellTokenDecimals: 6, buyToken: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH buyTokenDecimals: 18, amount: '1000000', // 1 USDC } // Get quote and execute trade const { quoteResults, postSwapOrderFromQuote } = await sdk.getQuote(parameters) const orderId = await postSwapOrderFromQuote() console.log('Order created:', orderId) ``` -------------------------------- ### POST /create_order (Example) Source: https://docs.cow.fi/cow-protocol/reference/contracts/core This endpoint allows for the creation of ERC-1271 orders with signed metadata. The metadata, including a signer address, is sent as part of the request body. ```APIDOC ## POST /create_order ### Description Allows the creation of ERC-1271 orders with signed metadata. The `signer` property within the `metadata` is used to verify the signature against the order's origin. ### Method POST ### Endpoint /create_order ### Parameters #### Request Body - **metadata** (object) - Required - Contains signed order metadata. - **signer** (string) - Required - The address of the smart-contract wallet signing the order. ### Request Example ```json { "metadata": { "signer": "0x291cf356e5639fb4c19ba5bfb4e2f8f82b371573" } } ``` ### Response #### Success Response (200) - **order_hash** (string) - The hash of the created order. - **app_data_hash** (string) - The hash of the application data. #### Response Example ```json { "order_hash": "0xabc123...", "app_data_hash": "0xdef456..." } ``` ``` -------------------------------- ### GET /api/v1/version Source: https://docs.cow.fi/cow-protocol/reference/apis/orderbook Retrieves the current API version. ```APIDOC ## GET /api/v1/version ### Description Retrieves the current API version. ### Method GET ### Endpoint /api/v1/version ### Response #### Success Response (200) - **version** (string) - The current API version. #### Response Example ```json { "version": "1.0.0" } ``` ``` -------------------------------- ### Flashloan Order Execution Guide Source: https://docs.cow.fi/cow-protocol/tutorials/solvers/flashloans_support This section details how to retrieve and interpret flashloan information from order appdata and outlines the necessary adjustments for solvers and drivers to execute flashloan orders. ```APIDOC ## Flashloan Order Information Retrieval ### Description Information about an order's flashloan is embedded within the order's appdata by the user. Solvers and drivers are responsible for retrieving this full appdata, as only the appdata hash is initially shared. ### Key Flashloan Fields in Appdata - `amount` (string): The amount of tokens to be flashloaned, in wei. - `token` (string): The contract address of the token to be flashloaned. - `receiver` (string): The address designated to receive the flashloaned tokens. - `liquidityProvider` (string): The contract address of the lending protocol's pool (e.g., AavePool). - `protocolAdapter` (string): The address of the adapter contract needed to integrate the liquidity provider with CoW Protocol's flashloan machinery. ### Example Flashloan Data Structure ```json { "flashloan": { "amount": "20000000000000000000", "liquidityProvider": "0xb50201558B00496A145fE76f7424749556E326D8", "protocolAdapter": "0x19167A179bcDDBecc2d655d059f20501E5323560", "receiver": "0x19167A179bcDDBecc2d655d059f20501E5323560", "token": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d" } } ``` ## Adjustments for Flashloan Order Execution ### Encoding the Call to the Flashloan Router #### Description Flashloan settlements must be executed through the flashloan router contract to ensure the loan is available for the entire settlement duration. Instead of calling `settle()` directly on the settlement contract, drivers must call `flashloanAndSettle()` on the router. #### Method `flashloanAndSettle()` #### Endpoint `0x9da8b48441583a2b93e2ef8213aad0ec0b392c69` (Flashloan Router Contract Address) #### Parameters 1. `Loan.Data[]` (array): An array of loan data structures, which can be directly initialized using the `flashloan` field from the order's appdata. 2. `settlement` (bytes): The calldata for the regular `settle()` call that the router will initiate after securing the flashloans. #### Note For Aave integrations, no additional permissioned interactions are required from the driver if the call to the flashloan router is constructed correctly and includes pre- and post-hooks. ### Estimating Gas Costs #### Description Solvers are responsible for estimating and accounting for the total gas costs of a settlement, including the overhead introduced by the flashloan flow via the wrapper contract. Proper gas estimation is crucial to avoid losses. #### Considerations - The flashloan flow involves a call to a wrapper contract, adding gas overhead compared to a direct settlement contract call. - Solvers connected to the reference driver still need to account for this overhead, as the reference driver does not perform post-processing of network fees. - If using `eth_call` for simulation, adjust it to call the flashloan router instead of the settlement contract, or heuristically add an overhead. ### Adjusting Order Filtering Logic #### Description Solvers often implement order filtering logic. For flashloan orders, this logic may need adjustment to account for the temporary balance increase provided by the flashloan during pre-hook execution. #### Handling Strategies 1. **Assume Order is Good**: If an order utilizes a flashloan, assume it is valid. 2. **Simulate Flashloan**: Adjust verification logic to simulate the entire flashloan execution flow by calling the router. 3. **"Fake" Flashloan with State Overrides**: Modify verification logic to use state overrides, making it appear as if the flashloan receiver has acquired the necessary tokens prior to verification. ``` -------------------------------- ### GET /api/v1/auction Source: https://docs.cow.fi/cow-protocol/reference/apis/orderbook Retrieves the current batch auction. ```APIDOC ## GET /api/v1/auction ### Description Retrieves the current batch auction. ### Method GET ### Endpoint /api/v1/auction ### Response #### Success Response (200) - **Auction** (object) - Information about the current auction. #### Response Example ```json { "id": 123, "startTime": "2023-03-15T10:00:00Z", "endTime": "2023-03-15T10:15:00Z" } ``` ``` -------------------------------- ### GET /api/v2/trades Source: https://docs.cow.fi/cow-protocol/reference/apis/orderbook Retrieves existing trades (paginated). ```APIDOC ## GET /api/v2/trades ### Description Retrieves existing trades (paginated). ### Method GET ### Endpoint /api/v2/trades ### Parameters #### Query Parameters - **offset** (integer) - Optional - The offset for pagination. - **limit** (integer) - Optional - The limit for pagination. ### Response #### Success Response (200) - **trades** (array) - An array of trades. #### Response Example ```json { "trades": [ { "orderUid": "0x...", "sellToken": "0x...", "buyToken": "0x...", "sellAmount": "1000000000000000000", "buyAmount": "2000000000000000000", "feeAmount": "10000000000000000", "txHash": "0x...", "settlementDate": "2023-03-15T10:00:00Z" } ], "offset": 0, "limit": 10, "total": 100 } ``` ``` -------------------------------- ### GET /api/v1/trades Source: https://docs.cow.fi/cow-protocol/reference/apis/orderbook Retrieves existing trades (unpaginated). ```APIDOC ## GET /api/v1/trades ### Description Retrieves existing trades (unpaginated). ### Method GET ### Endpoint /api/v1/trades ### Response #### Success Response (200) - **trades** (array) - An array of trades. #### Response Example ```json [ { "orderUid": "0x...", "sellToken": "0x...", "buyToken": "0x...", "sellAmount": "1000000000000000000", "buyAmount": "2000000000000000000", "feeAmount": "10000000000000000", "txHash": "0x...", "settlementDate": "2023-03-15T10:00:00Z" } ] ``` ``` -------------------------------- ### Clone Boilerplate Project with Git Source: https://docs.cow.fi/cow-protocol/tutorials/swap-in-safe-app Clone the 'safe-app-example' repository to your local machine to start with a basic boilerplate for your Safe Dapp integration. ```bash git clone