### Basic Setup Example Source: https://cowswap.mintlify.app/cow-sdk/api/trading-sdk A basic example demonstrating how to set up and initialize the Trading SDK with ViemAdapter. ```APIDOC ## Basic Setup ```typescript import { TradingSdk, SupportedChainId } from '@cowprotocol/sdk-trading' import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter' import { createPublicClient, http, privateKeyToAccount } from 'viem' import { sepolia } from 'viem/chains' const adapter = new ViemAdapter({ provider: createPublicClient({ chain: sepolia, transport: http('YOUR_RPC_URL') }), signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`) }) const sdk = new TradingSdk( { chainId: SupportedChainId.SEPOLIA, appCode: 'YOUR_APP_CODE', }, { enableLogging: true, }, adapter ) ``` ``` -------------------------------- ### Complete Order Signing Example Source: https://cowswap.mintlify.app/cow-py/api/contracts This example demonstrates setting up order details, signing an order, computing its UID, and printing the results. Ensure you have the necessary libraries installed and replace 'your_private_key' with your actual private key. ```python import time from eth_account import Account from web3 import Web3 from cowdao_cowpy.contracts.order import Order, compute_order_uid from cowdao_cowpy.contracts.sign import sign_order, SigningScheme from cowdao_cowpy.contracts.domain import domain from cowdao_cowpy.common.chains import Chain from cowdao_cowpy.common.constants import CowContractAddress from cowdao_cowpy.app_data.utils import DEFAULT_APP_DATA_HASH account = Account.from_key("your_private_key") USDC = Web3.to_checksum_address("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") WETH = Web3.to_checksum_address("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2") order_domain = domain( chain=Chain.MAINNET, verifying_contract=CowContractAddress.SETTLEMENT_CONTRACT.value ) order = Order( sell_token=USDC, buy_token=WETH, receiver=account.address, sell_amount="1000000000", buy_amount="500000000000000000", valid_to=int(time.time()) + 3600, app_data=DEFAULT_APP_DATA_HASH, fee_amount="0", kind="sell", partially_fillable=False, ) signature = sign_order( domain=order_domain, order=order, owner=account, scheme=SigningScheme.EIP712 ) order_uid = compute_order_uid(order_domain, order, account.address) print(f"Order UID: {order_uid}") print(f"Signature: {signature.to_string()}") ``` -------------------------------- ### CoW SDK v6 Basic Setup Source: https://cowswap.mintlify.app/cow-sdk/migration/v6-to-v7 Example of basic setup for CoW SDK v6 without adapters. ```typescript import { SupportedChainId, TradingSdk } from '@cowprotocol/cow-sdk' const options = {} const sdk = new TradingSdk({ chainId: SupportedChainId.SEPOLIA, appCode: 'YOUR_APP_CODE', }, options) ``` -------------------------------- ### Complete Example: Setting Up a Stop-Loss Order Source: https://cowswap.mintlify.app/cow-sdk/advanced/programmatic-orders A comprehensive example demonstrating the setup of a stop-loss order. This includes initializing the adapter and factory, creating the stop-loss order, adding it to a multiplexer, setting the root on the ComposableCoW contract, and generating proofs for a watchtower. ```typescript import { ConditionalOrderFactory, Multiplexer, ProofLocation, SupportedChainId } from '@cowprotocol/sdk-composable' import { EthersV6Adapter } from '@cowprotocol/sdk-ethers-v6-adapter' // 1. Initialize adapter and factory const adapter = new EthersV6Adapter({ provider, signer: wallet }) const factory = new ConditionalOrderFactory(registry, adapter) // 2. Create stop-loss order const stopLoss = new StopLossOrder({ sellToken: WETH_ADDRESS, buyToken: USDC_ADDRESS, sellAmount: parseEther('10'), strikePrice: '2000000000', // $2000 }) // 3. Create multiplexer const multiplexer = new Multiplexer(SupportedChainId.MAINNET) multiplexer.addOrder('stop-loss-1', stopLoss) // 4. Set root on ComposableCoW const root = multiplexer.getOrGenerateTree().root await composableCowContract.setRoot(root) // 5. Generate proofs for watchtower const proofs = multiplexer.dumpProofsAndParams() await storeProofsOffChain(proofs) console.log('Stop-loss order created and activated') ``` -------------------------------- ### CoW SDK v7 Basic Setup with ViemAdapter Source: https://cowswap.mintlify.app/cow-sdk/migration/v6-to-v7 Example of basic setup for CoW SDK v7 using ViemAdapter. Requires instantiation of the adapter with a provider and signer. ```typescript import { SupportedChainId, TradingSdk } from '@cowprotocol/cow-sdk' import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter' import { createPublicClient, http, privateKeyToAccount } from 'viem' import { sepolia } from 'viem/chains' // NEW: Instantiate and set 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 options = {} const sdk = new TradingSdk({ chainId: SupportedChainId.SEPOLIA, appCode: 'YOUR_APP_CODE', }, options, adapter) ``` -------------------------------- ### Example Multi-Step Hook Setup Source: https://cowswap.mintlify.app/hooks-trampoline/architecture/settlement-flow Illustrates a multi-step process using hooks, including unwrapping WETH, buying an NFT, and transferring it to a user. ```solidity // Step 1: Unwrap WETH hooks[0] = Hook({target: weth, callData: withdraw(amount), gasLimit: 50000}); // Step 2: Use ETH to buy NFT hooks[1] = Hook({target: nftMarket, callData: buyNFT{value: amount}(tokenId), gasLimit: 100000}); // Step 3: Transfer NFT to user hooks[2] = Hook({target: nft, callData: transferFrom(this, user, tokenId), gasLimit: 50000}); ``` -------------------------------- ### Project Setup with Forge Source: https://cowswap.mintlify.app/composable-cow/tutorials/custom-order-type Initialize a new project, install dependencies, and set up remappings for ComposableCoW and OpenZeppelin contracts. ```bash mkdir custom-order && cd custom-order forge init forge install cowprotocol/composable-cow ``` ```plaintext @cowprotocol/=lib/composable-cow/ @openzeppelin/=lib/composable-cow/lib/openzeppelin-contracts/ safe/=lib/composable-cow/lib/safe-contracts/contracts/ ``` -------------------------------- ### Complete TWAP Order Setup Example Source: https://cowswap.mintlify.app/cow-sdk/advanced/twap-orders A comprehensive example demonstrating the initialization of the adapter, definition of TWAP parameters, order creation, validation, setting the Merkle root, and storing proofs off-chain. This requires Ethers.js v6 and specific contract addresses/ABIs. ```typescript import { Twap, TwapData, Multiplexer, StartTimeValue, DurationType } from '@cowprotocol/sdk-composable' import { EthersV6Adapter } from '@cowprotocol/sdk-ethers-v6-adapter' import { SupportedChainId } from '@cowprotocol/sdk-config' // Initialize adapter const adapter = new EthersV6Adapter({ provider, signer: wallet }) // Define parameters const twapData: TwapData = { sellToken: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH buyToken: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI receiver: await wallet.getAddress(), sellAmount: parseEther('10'), buyAmount: parseUnits('20000', 18), numberOfParts: BigInt(24), timeBetweenParts: BigInt(3600), startTime: { startType: StartTimeValue.AT_MINING_TIME }, durationOfPart: { durationType: DurationType.AUTO }, appData: '0x0000000000000000000000000000000000000000000000000000000000000000', } // Create and validate order const twapOrder = Twap.fromData(twapData) const validation = twapOrder.isValid() if (!validation.isValid) throw new Error(`Invalid: ${validation.reason}`) // Set root and store proofs const multiplexer = new Multiplexer(SupportedChainId.MAINNET) multiplexer.addOrder('twap-1', twapOrder) const tree = multiplexer.getOrGenerateTree() const root = tree.root const composableCowContract = adapter.getContract( COMPOSABLE_COW_CONTRACT_ADDRESS[SupportedChainId.MAINNET], ComposableCowABI ) await composableCowContract.setRoot(root) const proofs = multiplexer.dumpProofsAndParams() await storeProofsOffChain(proofs) ``` -------------------------------- ### Complete Example: Get Quote and Post Sell Order Source: https://cowswap.mintlify.app/cow-sdk/guides/native-token-swaps This example demonstrates the full workflow of getting a trade quote for selling ETH and then posting the order. Ensure you have sufficient ETH for gas in addition to the selling amount. ```typescript import { TradingSdk, SupportedChainId, OrderKind, TradeParameters, } from '@cowprotocol/sdk-trading' import { parseEther } from 'viem' const sdk = new TradingSdk({ chainId: SupportedChainId.MAINNET, appCode: 'YOUR_APP_CODE', }, {}, adapter) const parameters: TradeParameters = { kind: OrderKind.SELL, sellToken: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', sellTokenDecimals: 18, buyToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC buyTokenDecimals: 6, amount: parseEther('1').toString(), // 1 ETH } // Step 1: Get a quote const { quoteResults } = await sdk.getQuote(parameters) const expectedUSDC = quoteResults.amountsAndCosts.afterSlippage.buyAmount const ethAmount = parseEther('1') console.log(`Selling ${ethAmount} ETH`) console.log(`Expected to receive at least: ${expectedUSDC} USDC`) // Step 2: Create the order if (confirm('Proceed with the trade?')) { const { orderId, txHash } = await sdk.postSellNativeCurrencyOrder(parameters) console.log('Order ID:', orderId) console.log('Transaction hash:', txHash) await adapter.provider.waitForTransactionReceipt({ hash: txHash }) console.log('Order created successfully!') } ``` -------------------------------- ### Local Testing Setup (Docker) Source: https://cowswap.mintlify.app/bff/api-reference/endpoints/notifications Commands to set up the local environment for testing notification services using Docker. This includes starting the queue and database, running migrations, and starting the producer and API. ```bash # Start required services docker-compose up -d queue db # Run migrations yarn migration:run # Start notification producer yarn producer # In another terminal, start the API yarn start # Query notifications curl http://localhost:3001/accounts/0x.../notifications ``` -------------------------------- ### Start Infrastructure Services and API Source: https://cowswap.mintlify.app/bff/quickstart Use these commands to start all necessary infrastructure services, run database migrations, and then start the API service. ```bash yarn compose:up ``` ```bash yarn migration:run ``` ```bash yarn start ``` -------------------------------- ### ViemAdapter Setup for CoW SDK Source: https://cowswap.mintlify.app/cow-sdk/migration/v6-to-v7 Example of setting up ViemAdapter for CoW SDK v7. Requires a viem public client and an account signer. ```typescript 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 }) ``` -------------------------------- ### Flash Loan Setup Pre-Hook Example Source: https://cowswap.mintlify.app/cow-sdk/advanced/hooks Demonstrates how to set up a flash loan as a pre-hook. This involves specifying the flash loan provider's contract address, the encoded `flashLoan` function call data with necessary arguments, and an appropriate gas limit. ```typescript const flashLoanHook = { target: '0xFlashLoanProvider', callData: encodeFunctionData({ abi: FLASH_LOAN_ABI, functionName: 'flashLoan', args: [ receiverAddress, tokenAddress, amount, encodedParams, ], }), gasLimit: '300000', dappId: 'flash-loan', } ``` -------------------------------- ### Usage Examples Source: https://cowswap.mintlify.app/cow-sdk/api/adapters/viem Examples demonstrating how to integrate the ViemAdapter with different wallet solutions. ```APIDOC ## With Wagmi ### Description Example of using ViemAdapter with Wagmi for wallet connection. ### Code Example ```typescript import { useWalletClient, usePublicClient } from 'wagmi' import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter' function MyComponent() { const publicClient = usePublicClient() const { data: walletClient } = useWalletClient() const adapter = new ViemAdapter({ provider: publicClient, walletClient: walletClient }) // Use adapter with SDK } ``` ## With Private Key ### Description Example of initializing ViemAdapter using a private key. ### Code Example ```typescript import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter' import { http, createPublicClient, privateKeyToAccount } from 'viem' import { mainnet } from 'viem/chains' const account = privateKeyToAccount('0x...') const provider = createPublicClient({ chain: mainnet, transport: http('https://eth.llamarpc.com') }) const adapter = new ViemAdapter({ provider, signer: account }) ``` ## With CoW SDK ### Description Example of integrating ViemAdapter with the CoW SDK for trading. ### Code Example ```typescript import { CowSdk, SupportedChainId } from '@cowprotocol/cow-sdk' 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 }) const adapter = new ViemAdapter({ provider, signer: account }) const sdk = new CowSdk({ chainId: SupportedChainId.SEPOLIA, adapter, tradingOptions: { traderParams: { appCode: 'YOUR_APP_CODE', }, options: { chainId: SupportedChainId.SEPOLIA, }, }, }) const orderId = await sdk.trading.postSwapOrder(/* ... */) ``` ``` -------------------------------- ### Implementation Examples Source: https://cowswap.mintlify.app/cow-sdk/api/adapters/ethers-v6 Provides practical examples of how to use the Ethers v6 Adapter. ```APIDOC ## Implementation Examples ### Basic Setup with RPC String ```typescript const adapter = new EthersV6Adapter({ provider: 'https://eth.llamarpc.com', signer: '0x...' }) ``` ### Integration with CoW SDK ```typescript import { CowSdk, SupportedChainId } from '@cowprotocol/cow-sdk' 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 }) const sdk = new CowSdk({ chainId: SupportedChainId.SEPOLIA, adapter, tradingOptions: { traderParams: { appCode: 'YOUR_APP_CODE' }, options: { chainId: SupportedChainId.SEPOLIA } } }) const orderId = await sdk.trading.postSwapOrder(parameters) ``` ### MetaMask Browser Integration ```typescript import { EthersV6Adapter } from '@cowprotocol/sdk-ethers-v6-adapter' import { BrowserProvider } from 'ethers' const provider = new BrowserProvider(window.ethereum) const signer = await provider.getSigner() const adapter = new EthersV6Adapter({ provider, signer }) // Use IntChainIdTypedDataV4Signer for improved MetaMask compatibility const v4Signer = new adapter.IntChainIdTypedDataV4Signer(signer) ``` ``` -------------------------------- ### Install Order Signing SDK Source: https://cowswap.mintlify.app/cow-sdk/api/order-signing-utils Install the SDK using npm, pnpm, or yarn. ```bash npm install @cowprotocol/sdk-order-signing # or pnpm add @cowprotocol/sdk-order-signing # or yarn add @cowprotocol/sdk-order-signing ``` -------------------------------- ### Installation Source: https://cowswap.mintlify.app/cow-sdk/api/composable-sdk Install the Composable SDK using npm. ```APIDOC ## Installation ```shellscript npm install @cowprotocol/sdk-composable ``` ``` -------------------------------- ### Installation Source: https://cowswap.mintlify.app/cow-sdk/api/adapters/viem Install the Viem Adapter package using npm. ```APIDOC ## Installation ```shell npm install @cowprotocol/sdk-viem-adapter ``` ``` -------------------------------- ### Start Playground Services Source: https://cowswap.mintlify.app/services/development/playground Start all services defined in the Docker Compose file. ```bash docker compose up ``` -------------------------------- ### Install SDK Source: https://cowswap.mintlify.app/cow-sdk/api/metadata-api Install the SDK package using npm. This is required before using the MetadataApi. ```bash npm install @cowprotocol/sdk-app-data ``` -------------------------------- ### Install @cowprotocol/sdk-common Source: https://cowswap.mintlify.app/cow-sdk/api/common Install the common utilities package for the CoW Protocol SDK. ```bash npm install @cowprotocol/sdk-common ``` -------------------------------- ### Ethers v5 Example for CowSwap Source: https://cowswap.mintlify.app/cow-sdk/examples/basic-swap This snippet shows how to use CowSwap with Ethers v5. It requires similar setup to the v6 example but uses Ethers v5 specific classes. ```typescript import { ethers } from 'ethers' import { setGlobalAdapter, SupportedChainId, TradingSdk, OrderKind, WRAPPED_NATIVE_CURRENCIES, } from '@cowprotocol/cow-sdk' import { EthersV5Adapter } from '@cowprotocol/sdk-ethers-v5-adapter' const RPC_URL = 'https://sepolia.gateway.tenderly.co' const PRIVATE_KEY = '0x...' // Your private key const DEFAULT_SELL_AMOUNT = '0.1' async function main() { const chainId = SupportedChainId.SEPOLIA const provider = new ethers.providers.JsonRpcProvider(RPC_URL, chainId) const wallet = new ethers.Wallet(PRIVATE_KEY, provider) const adapter = new EthersV5Adapter({ provider, signer: wallet }) setGlobalAdapter(adapter) const sdk = new TradingSdk({ chainId, appCode: 'MyApp', signer: wallet, }) const WETH = WRAPPED_NATIVE_CURRENCIES[chainId] const USDC = { address: '0xbe72E441BF55620febc26715db68d3494213D8Cb', decimals: 18, } const owner = (await wallet.getAddress()) as `0x${string}` const amount = Math.round( Number(DEFAULT_SELL_AMOUNT) * 10 ** WETH.decimals ).toString() const slippageBps = 50 console.log('Owner:', owner) console.log('Getting quote...') const quoteAndPost = await sdk.getQuote({ chainId, kind: OrderKind.SELL, owner, amount, sellToken: WETH.address, sellTokenDecimals: WETH.decimals, buyToken: USDC.address, buyTokenDecimals: USDC.decimals, slippageBps, }) console.log('Posting order...') const result = await quoteAndPost.postSwapOrderFromQuote({}) console.log('Posted:', result) } main().catch((e) => { console.error(e) process.exit(1) }) ``` -------------------------------- ### MultiSend Atomic Setup Transactions Source: https://cowswap.mintlify.app/composable-cow/guides/troubleshooting Example of two transactions to be bundled via Safe's MultiSend contract for atomic setup: setting the fallback handler and registering the domain verifier. ```yaml // Transaction 1: Set fallback handler to: data: setFallbackHandler(0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5) // Transaction 2: Register domain verifier (Safe calls itself) to: data: setDomainVerifier(, 0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74) ``` -------------------------------- ### Copy Environment File Source: https://cowswap.mintlify.app/flash-loan-router/operations/deployment-guide Copy the example environment file to `.env` in the project root. This sets up the configuration for deployment. ```bash cp .env.example .env ``` -------------------------------- ### Set Up Environment Variables Source: https://cowswap.mintlify.app/flash-loan-router/getting-started/installation Copies the example environment file and prompts to edit it with specific configuration details for CLI and Forge deployment scripts. ```bash cp .env.example .env ``` ```dotenv # CLI CHAIN_ID=1 ETH_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY PRIVATE_KEY=your_private_key_here # Forge deployment scripts: # For smart contract verification ETHERSCAN_API_KEY=your_etherscan_api_key # FlashLoanRouter contract address used in a single deployment of AAVE Borrower. # FLASHLOAN_ROUTER_ADDRESS= ``` -------------------------------- ### Structured Log Output Examples Source: https://cowswap.mintlify.app/bff/services/notification-producer Examples of structured log output from the notification producer, showing different log levels and prefixes for various events like starting the producer, indexing blocks, and sending notifications. ```text [notification-producer:main] Start notification producer for networks: 1, 100 [TradeNotificationProducer:1] Indexing from block 18500000 to 18500100: 101 blocks [TradeNotificationProducer:1] Sending 5 notifications ``` -------------------------------- ### Complete Example Source: https://cowswap.mintlify.app/cow-py/api/contracts A comprehensive example demonstrating how to create and sign an order using the provided libraries. ```APIDOC ## Complete Example ### Description This example demonstrates the usage of order signing functionalities, including creating an order, computing its UID, and signing it for cancellation. ### Method Not specified (example code provided) ### Endpoint Not specified (example code provided) ### Parameters None explicitly defined for the example itself, but the underlying functions take parameters like `domain`, `order`, `owner`, and `scheme`. ### Request Example ```python import time from eth_account import Account from web3 import Web3 from cowdao_cowpy.contracts.order import Order, compute_order_uid from cowdao_cowpy.contracts.sign import sign_order, SigningScheme from cowdao_cowpy.contracts.domain import domain from cowdao_cowpy.common.chains import Chain from cowdao_cowpy.common.constants import CowContractAddress from cowdao_cowpy.app_data.utils import DEFAULT_APP_DATA_HASH account = Account.from_key("your_private_key") USDC = Web3.to_checksum_address("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") WETH = Web3.to_checksum_address("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2") order_domain = domain( chain=Chain.MAINNET, verifying_contract=CowContractAddress.SETTLEMENT_CONTRACT.value ) order = Order( sell_token=USDC, buy_token=WETH, receiver=account.address, sell_amount="1000000000", buy_amount="500000000000000000", valid_to=int(time.time()) + 3600, app_data=DEFAULT_APP_DATA_HASH, fee_amount="0", kind="sell", partially_fillable=False, ) signature = sign_order( domain=order_domain, order=order, owner=account, scheme=SigningScheme.EIP712 ) order_uid = compute_order_uid(order_domain, order, account.address) print(f"Order UID: {order_uid}") print(f"Signature: {signature.to_string()}") ``` ### Response #### Success Response (200) - **Order UID** (string) - The unique identifier for the created order. - **Signature** (string) - The EcdsaSignature for the order. #### Response Example ``` Order UID: 0x... Signature: 0x... ``` ``` -------------------------------- ### Complete Example with Pre and Post Hooks Source: https://cowswap.mintlify.app/cow-sdk/advanced/hooks A full example demonstrating how to initialize the CowSdk, define pre and post hooks for approval and staking, generate app data, and post a swap order. ```typescript import { CowSdk, OrderKind } from '@cowprotocol/cow-sdk' import { generateAppDataDoc } from '@cowprotocol/sdk-app-data' import { encodeFunctionData, parseEther } from 'viem' // Initialize SDK const sdk = new CowSdk({ chainId: 1, adapter }) // Define hooks const hooks = { version: '1.0.0', pre: [ // Approve WETH for settlement { target: WETH_ADDRESS, callData: encodeFunctionData({ abi: ERC20_ABI, functionName: 'approve', args: [SETTLEMENT_ADDRESS, parseEther('10')], }), gasLimit: '50000', dappId: 'cow-swap', }, ], post: [ // Stake received tokens { target: STAKING_CONTRACT, callData: encodeFunctionData({ abi: STAKING_ABI, functionName: 'stake', args: [parseEther('10000')], }), gasLimit: '100000', dappId: 'staking-protocol', }, ], } // Generate app data with hooks const appDataDoc = await generateAppDataDoc({ appCode: 'my-app', metadata: { hooks }, }) // Create order with hooks const { quote } = await sdk.trading.getQuote({ kind: OrderKind.SELL, sellToken: WETH_ADDRESS, buyToken: REWARD_TOKEN, sellAmount: parseEther('10'), appData: appDataDoc.fullAppData, }) // Post order const orderId = await sdk.trading.postSwapOrder({ quote: quote.quote, appData: appDataDoc.fullAppData, }) console.log('Order with hooks created:', orderId) ``` -------------------------------- ### Get a Quote Source: https://cowswap.mintlify.app/cow-protocol/tutorials/quickstart-curl Send your trading intention to the /quote endpoint to receive a quote. This example sells WETH for COW tokens. ```APIDOC ## POST /quote ### Description Retrieves a trading quote for a specified sell or buy intention. ### Method POST ### Endpoint `https://api.cow.fi/sepolia/api/v1/quote` ### Parameters #### Request Body - **sellToken** (string) - Required - Address of the token you are selling. - **buyToken** (string) - Required - Address of the token you are buying. - **sellAmountBeforeFee** (string) - Required - Amount to sell in the token's smallest unit. - **kind** (string) - Required - Type of order, either `"sell"` or `"buy"`. - **from** (string) - Required - Your wallet address. - **receiver** (string) - Required - Address that receives the bought tokens. - **validFor** (integer) - Required - How long the order stays valid, in seconds. - **signingScheme** (string) - Required - The signing scheme to use (e.g., `"eip712"`). - **appData** (string) - Optional - Additional data for the order. - **appDataHash** (string) - Optional - Hash of the `appData`. ### Request Example ```json { "sellToken": "0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14", "buyToken": "0xbe72E441BF55620febc26715db68d3494213D8Cb", "sellAmountBeforeFee": "1000000000000000000", "kind": "sell", "from": "0xYOUR_ADDRESS", "receiver": "0xYOUR_ADDRESS", "validFor": 1800, "signingScheme": "eip712", "appData": "{}", "appDataHash": "0xb48d38f93eaa084033fc5970bf96e559c33c4cdc07d889ab00b4d63f9590739d" } ``` ### Response #### Success Response (200) - **quote** (object) - Contains quote details. - **sellToken** (string) - Address of the token being sold. - **buyToken** (string) - Address of the token being bought. - **sellAmount** (string) - Sell amount after fees. - **buyAmount** (string) - Estimated buy amount after fees. - **feeAmount** (string) - Network costs in sell token units. - **kind** (string) - Type of order. - **validTo** (integer) - Unix timestamp after which the order expires. - **receiver** (string) - Receiver address. - **appData** (string) - Additional data. - **appDataHash** (string) - Hash of `appData`. - **partiallyFillable** (boolean) - Whether the order can be partially filled. - **from** (string) - The sender's address. - **expiration** (string) - The deadline for submitting the quoted order data. - **id** (integer) - Quote ID. - **verified** (boolean) - Indicates if the quote is verified. #### Response Example ```json { "quote": { "sellToken": "0xfff9976782d46cc05630d1f6ebab18b2324d6b14", "buyToken": "0xbe72e441bf55620febc26715db68d3494213d8cb", "sellAmount": "999375166535692640", "buyAmount": "191179999", "feeAmount": "624833464307360", "kind": "sell", "validTo": 1741700000, "receiver": "0xYOUR_ADDRESS", "appData": "{}", "appDataHash": "0xb48d38f93eaa084033fc5970bf96e559c33c4cdc07d889ab00b4d63f9590739d", "partiallyFillable": false }, "from": "0xYOUR_ADDRESS", "expiration": "2025-03-11T13:33:20Z", "id": 12345, "verified": true } ``` ``` -------------------------------- ### Using SupportedChainId Source: https://cowswap.mintlify.app/cow-sdk/api/config Import and use the SupportedChainId enum to specify a chain ID. This example shows how to get the mainnet chain ID. ```typescript import { SupportedChainId } from '@cowprotocol/sdk-config' const chainId = SupportedChainId.MAINNET // 1 ``` -------------------------------- ### Complex Logging Configuration Source: https://cowswap.mintlify.app/watch-tower/configuration/logging Combine global, module-specific, and regex-based logging configurations for precise control. This example sets global WARN, DEBUG for commands, WARN for loggers starting with checkForAndPlaceOrder, INFO for loggers starting with chainContext, and INFO for _checkForAndPlaceOrder:1: loggers. ```bash LOG_LEVEL="WARN,commands=DEBUG,^checkForAndPlaceOrder=WARN,^chainContext=INFO,_checkForAndPlaceOrder:1:=INFO" yarn cli ``` -------------------------------- ### Quick Setup Verification Source: https://cowswap.mintlify.app/flash-loan-router/getting-started/quickstart Verify the development environment setup by building contracts and running tests, excluding E2E tests. ```bash forge build && forge test --no-match-path 'test/e2e/**/*' ``` -------------------------------- ### Run Database Migrations and Start Producer (Development) Source: https://cowswap.mintlify.app/bff/services/notification-producer After setting up dependencies, run database migrations and then start the notification producer service. ```bash yarn migration:run yarn producer ``` -------------------------------- ### Post Swap Order Source: https://cowswap.mintlify.app/cow-sdk/examples/basic-swap Example of posting a swap order after getting a quote. Ensure you have the necessary chainId, owner, amount, and token details. ```typescript const WETH = WRAPPED_NATIVE_CURRENCIES[chainId] const USDC = { address: '0xbe72E441BF55620febc26715db68d3494213D8Cb', decimals: 18, } const owner = account.address const amount = BigInt(Math.floor(DEFAULT_SELL_AMOUNT * 10 ** WETH.decimals)) const slippageBps = 50 console.log('Owner:', owner) console.log('Getting quote...') const quoteAndPost = await sdk.getQuote({ chainId, kind: OrderKind.SELL, owner, amount: amount.toString(), sellToken: WETH.address, sellTokenDecimals: WETH.decimals, buyToken: USDC.address, buyTokenDecimals: USDC.decimals, slippageBps, }) console.log('Posting order...') const result = await quoteAndPost.postSwapOrderFromQuote({}) console.log('Posted:', result) } main().catch((e) => { console.error(e) process.exit(1) }) ``` ``` -------------------------------- ### Copy Configuration File Source: https://cowswap.mintlify.app/watch-tower/getting-started/installation Copy the example configuration file to create a new configuration file for customization. ```bash cp config.json.example config.json ``` -------------------------------- ### Install Viem Adapter and Viem Source: https://cowswap.mintlify.app/cow-sdk/concepts/adapters Install the necessary packages for the Viem adapter and Viem library. ```bash npm install @cowprotocol/sdk-viem-adapter viem ``` -------------------------------- ### Run Project Tests Source: https://cowswap.mintlify.app/flash-loan-router/getting-started/installation Executes the project's test suite to verify the installation and setup. Includes an option to exclude end-to-end tests. ```bash forge test forge test --no-match-path 'test/e2e/**/*' ``` -------------------------------- ### EthersV5Adapter Setup for CoW SDK Source: https://cowswap.mintlify.app/cow-sdk/migration/v6-to-v7 Example of setting up EthersV5Adapter for CoW SDK v7. Requires an ethers.js v5 provider and a wallet signer. ```typescript 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 }) ``` -------------------------------- ### Complete Limit Order Example with Ethers Source: https://cowswap.mintlify.app/cow-sdk/examples/limit-orders This example demonstrates setting up the Ethers adapter and creating a limit order. It includes provider and wallet initialization. ```typescript import { JsonRpcProvider, Wallet } from 'ethers' import { setGlobalAdapter, SupportedChainId, TradingSdk, OrderKind, } from '@cowprotocol/cow-sdk' import { EthersV6Adapter } from '@cowprotocol/sdk-ethers-v6-adapter' const RPC_URL = 'https://eth.llamarpc.com' const PRIVATE_KEY = '0x...' async function createLimitOrder() { const chainId = SupportedChainId.MAINNET // Setup const provider = new JsonRpcProvider(RPC_URL, chainId) const wallet = new Wallet(PRIVATE_KEY, provider) const adapter = new EthersV6Adapter({ provider, signer: wallet }) setGlobalAdapter(adapter) const sdk = new TradingSdk({ chainId, appCode: 'LimitOrderExample', signer: wallet, }) const WETH = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2' const USDC = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' // Create limit order: Sell 1 WETH for at least 2000 USDC const result = await sdk.postLimitOrder({ chainId, kind: OrderKind.SELL, sellToken: WETH, sellTokenDecimals: 18, buyToken: USDC, buyTokenDecimals: 6, sellAmount: '1000000000000000000', // 1 WETH buyAmount: '2000000000', // 2000 USDC minimum slippageBps: 0, }) console.log('Limit order ID:', result.orderId) console.log('View at: https://explorer.cow.fi/orders/' + result.orderId) } createLimitOrder() ``` -------------------------------- ### EthersV6Adapter Setup for CoW SDK Source: https://cowswap.mintlify.app/cow-sdk/migration/v6-to-v7 Example of setting up EthersV6Adapter for CoW SDK v7. Requires an ethers.js v6 provider and a wallet signer. ```typescript 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 }) ``` -------------------------------- ### Borrower Contract - Implementation Guide Source: https://cowswap.mintlify.app/flash-loan-router/contracts/base/borrower Provides steps and an example for creating a new flash loan provider adapter by extending the Borrower contract. ```APIDOC ## Implementation Guide To create a new adapter, extend the `Borrower` contract and implement the provider's callback interface: ```solidity theme={null} contract NewProviderBorrower is Borrower, IProviderCallback { constructor(IFlashLoanRouter _router) Borrower(_router) {} function triggerFlashLoan( address lender, IERC20 token, uint256 amount, bytes calldata callBackData ) internal override { // Call provider-specific flash loan function IProvider(lender).requestFlashLoan( address(token), amount, callBackData ); } // Implement provider's callback function providerCallback(bytes calldata data) external { flashLoanCallBack(data); } } ``` ### Implementation Steps 1. **Inherit `Borrower`** and the provider's callback interface 2. **Override `triggerFlashLoan`**: Map standard parameters to the provider's flash loan request format 3. **Implement provider callback**: Receive the callback from the provider and call `flashLoanCallBack(callBackData)` 4. **Deploy**: Use the FlashLoanRouter address as the constructor argument ``` -------------------------------- ### Run Safe App Locally Source: https://cowswap.mintlify.app/cow-swap/tutorials/safe-app Install dependencies and start the Safe Dapp locally on a specified port. Ensure you set the PORT environment variable. ```bash # Install dependencies yarn # Run the app PORT=9999 yarn start ``` -------------------------------- ### Smart Contract Wallet Integration with PRESIGN Source: https://cowswap.mintlify.app/cow-sdk/api/trading-sdk Example demonstrating how to use the PRESIGN signing scheme for smart contract wallets, including getting a pre-sign transaction. ```typescript import { SigningScheme } from '@cowprotocol/sdk-trading' const params = { // ... trade parameters } const advancedSettings = { quoteRequest: { signingScheme: SigningScheme.PRESIGN, } } const { orderId } = await sdk.postSwapOrder(params, advancedSettings) const preSignTx = await sdk.getPreSignTransaction({ orderUid: orderId, account: '0xSmartContractWallet...', }) // Execute preSignTx with your smart contract wallet ``` -------------------------------- ### Adapter Initialization Source: https://cowswap.mintlify.app/cow-sdk/api/adapters/ethers-v5 Examples of how to initialize the EthersV5Adapter with different configurations. ```APIDOC ## Adapter Initialization with Provider and Wallet ### Description Initializes the EthersV5Adapter using an Ethers.js v5 provider and wallet. ### Method `new EthersV5Adapter({ provider, signer })` ### Endpoint N/A (Constructor) ### Parameters #### Request Body - **provider** (ethers.providers.Provider) - Required - An Ethers.js v5 provider instance. - **signer** (ethers.Wallet) - Required - An Ethers.js v5 wallet instance. ### Request Example ```typescript 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 }) ``` ## Adapter Initialization with RPC URL String ### Description Initializes the EthersV5Adapter using an RPC URL string for the provider and a private key or signer address. ### Method `new EthersV5Adapter({ provider, signer })` ### Endpoint N/A (Constructor) ### Parameters #### Request Body - **provider** (string) - Required - The RPC URL string. - **signer** (string) - Required - The private key or signer address. ### Request Example ```typescript import { EthersV5Adapter } from '@cowprotocol/sdk-ethers-v5-adapter' const adapter = new EthersV5Adapter({ provider: 'https://eth.llamarpc.com', signer: '0x...' }) ``` ``` -------------------------------- ### Perform Basic Cross-Chain Swap Source: https://cowswap.mintlify.app/cow-sdk/api/bridging-sdk Example of getting a quote for a USDC swap from Mainnet to Base and then posting the order. Ensure you have the necessary imports and a user signer configured. ```typescript import { BridgingSdk, AcrossBridgeProvider } from '@cowprotocol/sdk-bridging' import { OrderKind } from '@cowprotocol/sdk-order-book' import { SupportedChainId, TargetChainId } from '@cowprotocol/sdk-config' const sdk = new BridgingSdk({ providers: [new AcrossBridgeProvider()], }) // Get a quote for swapping USDC from Mainnet to Base const quote = await sdk.getQuote({ kind: OrderKind.SELL, amount: parseUnits('100', 6), sellTokenChainId: SupportedChainId.MAINNET, sellTokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', sellTokenDecimals: 6, buyTokenChainId: TargetChainId.BASE, buyTokenAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', buyTokenDecimals: 6, signer: userSigner, swapSlippageBps: 50, // 0.5% bridgeSlippageBps: 50, // 0.5% }) // Post the order const result = await quote.postSwapOrderFromQuote() console.log('Order posted:', result.orderUid) ``` -------------------------------- ### Set Up Development Configuration Source: https://cowswap.mintlify.app/watch-tower/getting-started/running-locally Create a development configuration file for a specific testnet, such as Sepolia. This involves copying an example configuration and editing it to include only the desired network and RPC endpoint. ```bash cp config.json.example config.sepolia.json ``` -------------------------------- ### Database Configuration Examples Source: https://cowswap.mintlify.app/bff/services/notification-producer Configure database connection details using environment variables such as DATABASE_HOST, DATABASE_PORT, DATABASE_USERNAME, DATABASE_PASSWORD, and DATABASE_NAME. ```bash DATABASE_HOST=localhost DATABASE_PORT=5432 DATABASE_USERNAME=bff-db-user DATABASE_PASSWORD=bff-db-password DATABASE_NAME=bff-db DATABASE_ENABLED=true ``` -------------------------------- ### Get Account Notifications (Python) Source: https://cowswap.mintlify.app/bff/api-reference/endpoints/notifications Retrieve account notifications using Python's requests library. This snippet prints the count of notifications. Ensure the requests library is installed. ```python import requests account_address = '0x1234567890abcdef1234567890abcdef12345678' response = requests.get(f'https://api.cow.fi/accounts/{account_address}/notifications') notifications = response.json() print(f"Found {len(notifications)} notifications") ``` -------------------------------- ### Get Slippage Tolerance with JavaScript Source: https://cowswap.mintlify.app/bff/api-reference/endpoints/markets Fetch the recommended slippage tolerance for a trading pair using JavaScript. This example demonstrates how to make the API call and parse the JSON response. ```javascript const baseToken = '0x6b175474e89094c44da98b954eedeac495271d0f'; // DAI const quoteToken = '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599'; // WBTC const response = await fetch( `https://api.cow.fi/1/markets/${baseToken}-${quoteToken}/slippageTolerance` ); const data = await response.json(); console.log(`Recommended slippage: ${data.slippageBps / 100}%`); ``` -------------------------------- ### TWAP Start Type: AT_EPOCH Source: https://cowswap.mintlify.app/cow-py/advanced/twap-orders Schedule TWAP orders to begin execution at a specific future time. Calculate the `start_time_epoch` as a Unix timestamp, for example, 24 hours from the current time. ```python import time start_time = int(time.time()) + 86400 # Start 24 hours from now twap_data = TwapData( start_type=StartType.AT_EPOCH, start_time_epoch=start_time, # ... other parameters ) ``` -------------------------------- ### Base Configuration Example Source: https://cowswap.mintlify.app/watch-tower/configuration/networks Example configuration for monitoring the Base network. Includes name, RPC endpoint, and deployment block. ```json { "name": "base", "rpc": "https://mainnet.base.org", "deploymentBlock": 31084679 } ```