Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CoW Swap Plugin #179

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open

CoW Swap Plugin #179

wants to merge 13 commits into from

Conversation

bh2smith
Copy link
Contributor

@bh2smith bh2smith commented Aug 30, 2024

User description

Implements API for order quoting and creation.

This project is really just a minimal wrapper for https://api.cow.fi/docs/#/default/post_api_v1_quote

Test Plan

yarn && yarn dev
curl -X 'POST' \
  'http://localhost:3000/api/quote' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "network": "mainnet"
  "sellToken": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
  "buyToken": "0x6810e776880c02933d47db1b9fc05908e5386b96",
  "receiver": "0x6810e776880c02933d47db1b9fc05908e5386b96",
  "from": "0x6810e776880c02933d47db1b9fc05908e5386b96",
  "kind": "sell",
  "sellAmountBeforeFee": "1234567890"
}'

Dune Query for CoW Traded Tokens with volume > 10k USD:
https://dune.com/queries/4055949


PR Type

Enhancement, Documentation, Configuration changes


Description

  • Added a health check endpoint that returns a JSON response with a status message.
  • Implemented POST endpoint for order quoting, validating network parameter and forwarding request to CoW Swap API.
  • Added API reference configuration for the CoW Swap AI Plugin.
  • Configured TailwindCSS and PostCSS for the project.
  • Added ESLint configuration extending Next.js core web vitals.
  • Added README with project description, setup, and deployment instructions.
  • Configured Next.js headers for API routes.
  • Added project dependencies and scripts.
  • Added OpenAPI specification for CoW Swap Assistant API.
  • Added TypeScript configuration for the project.

Changes walkthrough 📝

Relevant files
Enhancement
3 files
route.ts
Add health check endpoint                                                               

cowswap-ai-plugin/app/api/health/route.ts

  • Added a health check endpoint that returns a JSON response with a
    status message.
  • +6/-0     
    route.ts
    Implement order quoting endpoint                                                 

    cowswap-ai-plugin/app/api/quote/route.ts

  • Implemented POST endpoint for order quoting.
  • Validates network parameter.
  • Forwards request to CoW Swap API and returns the response.
  • +27/-0   
    route.ts
    Add API reference configuration                                                   

    cowswap-ai-plugin/app/route.ts

    • Added API reference configuration for the CoW Swap AI Plugin.
    +27/-0   
    Configuration changes
    6 files
    tailwind.config.ts
    Configure TailwindCSS                                                                       

    cowswap-ai-plugin/tailwind.config.ts

  • Configured TailwindCSS for the project.
  • Added custom theme extensions.
  • +20/-0   
    .eslintrc.json
    Add ESLint configuration                                                                 

    cowswap-ai-plugin/.eslintrc.json

    • Added ESLint configuration extending Next.js core web vitals.
    +3/-0     
    next.config.mjs
    Configure Next.js headers                                                               

    cowswap-ai-plugin/next.config.mjs

    • Configured Next.js headers for API routes.
    +25/-0   
    package.json
    Add project dependencies and scripts                                         

    cowswap-ai-plugin/package.json

    • Added project dependencies and scripts.
    +41/-0   
    postcss.config.mjs
    Configure PostCSS                                                                               

    cowswap-ai-plugin/postcss.config.mjs

    • Configured PostCSS with TailwindCSS plugin.
    +8/-0     
    tsconfig.json
    Add TypeScript configuration                                                         

    cowswap-ai-plugin/tsconfig.json

    • Added TypeScript configuration for the project.
    +39/-0   
    Documentation
    2 files
    README.md
    Add project README                                                                             

    cowswap-ai-plugin/README.md

  • Added README with project description, setup, and deployment
    instructions.
  • +50/-0   
    ai-plugin.json
    Add OpenAPI specification                                                               

    cowswap-ai-plugin/public/.well-known/ai-plugin.json

    • Added OpenAPI specification for CoW Swap Assistant API.
    +206/-0 

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions


    Copy link

    vercel bot commented Aug 30, 2024

    The latest updates on your projects. Learn more about Vercel for Git ↗︎

    Name Status Preview Comments Updated (UTC)
    templates ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-ai-chat ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-ai-minter ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-blogchain ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-coingecko-ai-plugin ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-contract-deployer ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-marketplace ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-nft-stripe-checkout ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-simple-minter ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-starter ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-starter-react-vite ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm
    templates-token-drop ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 1:55pm

    @mintbase-codium-pr-agent
    Copy link

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Key issues to review

    Error Handling
    The error message for an invalid network in the POST request handler is not consistent with the rest of the API's error structure. Consider using a structured JSON response for all errors.

    Placeholder Data
    The server URL in the OpenAPI specification is set to 'TODO: FIXME', which needs to be updated to a proper URL before deployment.

    @mintbase-codium-pr-agent
    Copy link

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Security
    Add validation for the requestBody to ensure it contains the expected properties

    To improve the security and maintainability of the API, validate the requestBody
    structure before using its properties. This helps prevent runtime errors and
    potential security vulnerabilities due to unexpected input.

    cowswap-ai-plugin/app/api/quote/route.ts [7-10]

     const requestBody = await req.json();
    +if (!requestBody || typeof requestBody !== 'object' || !requestBody.network) {
    +  return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
    +}
     const network: Network = requestBody.network;
     
    Suggestion importance[1-10]: 9

    Why: Validating the requestBody structure enhances security and prevents potential runtime errors due to unexpected input, which is crucial for API robustness.

    9
    Maintainability
    Replace manual network type checks with an enum for better type safety

    Instead of hardcoding the network types and checking them manually, consider using
    an enum for better type safety and maintainability. This approach reduces the risk
    of typos and makes the code cleaner.

    cowswap-ai-plugin/app/api/quote/route.ts [10-14]

    +enum Network {
    +  Mainnet = "mainnet",
    +  Xdai = "xdai",
    +  ArbitrumOne = "arbitrum_one"
    +}
     const network: Network = requestBody.network;
    -if (!["mainnet", "xdai", "arbitrum_one"].includes(network)) {
    -  return NextResponse.json({ error: `Invalid network '${network}'. Must be one of 'mainnet', 'xdai' OR 'arbitrum_one'` }, { status: 400 });
    +if (!(network in Network)) {
    +  return NextResponse.json({ error: `Invalid network '${network}'. Must be one of ${Object.values(Network).join(", ")}` }, { status: 400 });
     }
     
    Suggestion importance[1-10]: 8

    Why: Using an enum for network types improves type safety and maintainability, reducing the risk of typos and making the code cleaner.

    8
    Encapsulate fetch operation in a try-catch block to handle potential errors more gracefully

    Use async/await consistently for fetching and handling the response to improve
    readability and error handling. This change makes the code more consistent and
    easier to maintain.

    cowswap-ai-plugin/app/api/quote/route.ts [16-26]

    -const response = await fetch(`${COW_API}/${network}/api/v1/quote`, {
    -  method: 'POST',
    -  headers: {
    -    'Content-Type': 'application/json'
    -  },
    -  body: JSON.stringify(requestBody)
    -});
    -const data = await response.json();
    +try {
    +  const response = await fetch(`${COW_API}/${network}/api/v1/quote`, {
    +    method: 'POST',
    +    headers: {
    +      'Content-Type': 'application/json'
    +    },
    +    body: JSON.stringify(requestBody)
    +  });
    +  const data = await response.json();
    +  return NextResponse.json(data);
    +} catch (error) {
    +  return NextResponse.json({ error: 'Failed to fetch quote' }, { status: 500 });
    +}
     
    Suggestion importance[1-10]: 8

    Why: Using a try-catch block for the fetch operation improves error handling and makes the code more consistent and easier to maintain.

    8
    Extract API URLs and error messages into a separate configuration file for better maintainability

    To enhance code readability and maintainability, consider extracting the API URL and
    the error message into a separate configuration or constants file. This practice
    helps manage changes more efficiently and keeps the code clean.

    cowswap-ai-plugin/app/api/quote/route.ts [3-14]

    -const COW_API = "https://api.cow.fi"
    -if (!["mainnet", "xdai", "arbitrum_one"].includes(network)) {
    -  return NextResponse.json({ error: `Invalid network '${network}'. Must be one of 'mainnet', 'xdai' OR 'arbitrum_one'` }, { status: 400 });
    +// In a new file, e.g., config.ts
    +export const COW_API = "https://api.cow.fi";
    +export const VALID_NETWORKS = ["mainnet", "xdai", "arbitrum_one"];
    +export const ERROR_MESSAGES = {
    +  invalidNetwork: (network) => `Invalid network '${network}'. Must be one of ${VALID_NETWORKS.join(", ")}`,
    +};
    +// In the existing file
    +import { COW_API, VALID_NETWORKS, ERROR_MESSAGES } from './config';
    +if (!VALID_NETWORKS.includes(network)) {
    +  return NextResponse.json({ error: ERROR_MESSAGES.invalidNetwork(network) }, { status: 400 });
     }
     
    Suggestion importance[1-10]: 7

    Why: Extracting constants into a separate file enhances code readability and maintainability, making it easier to manage changes.

    7

    cowswap-ai-plugin/README.md Outdated Show resolved Hide resolved
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    Configuration changes documentation Improvements or additions to documentation enhancement New feature or request Review effort [1-5]: 3
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    2 participants