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

added near social agent #194

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

Conversation

Immanuel-john
Copy link

@Immanuel-john Immanuel-john commented Sep 28, 2024

User description

Project Title: Near Social AI Agent Plugin

Project Description:
The Near Social AI Agent Plugin provides users with a seamless interface to set up profiles and manage posts on the Near Social platform. This plugin simplifies the process of user engagement by guiding users through collecting necessary profile details and generating content for posts. By integrating AI assistance, it enhances the overall user experience on the Near Social platform.

Technologies Used:

Node.js: The server-side runtime environment for building the API.
NEAR Blockchain: For secure interactions and management of user profiles and posts.
OpenAI: Utilized for generating content based on user prompts.
mintbase.js: Used to facilitate interactions with Mintbase services for NFT functionalities.
How did you use mintbase.js?:
In the Near Social AI Agent Plugin, mintbase.js is employed to interact with the Mintbase API for handling user profiles and managing post uploads. This integration allows users to easily set up their profiles and share content on the blockchain, ensuring a smooth and efficient process. The plugin provides a guided experience, making it accessible for all users.

Working Demo Link:


PR Type

enhancement, documentation


Description

  • Added routes for managing user profiles, posts, and follow actions with NEAR blockchain integration.
  • Implemented utility functions for data handling, NEAR interactions, and image uploads to IPFS.
  • Set up Express server with necessary routes and middleware.
  • Added OpenAPI specification for AI plugin and detailed README with project information and setup instructions.
  • Initialized project with necessary dependencies and configuration for Vercel deployment.

Changes walkthrough 📝

Relevant files
Enhancement
8 files
profile.js
Add profile management routes and NEAR integration             

near-social-ai-agent/routes/profile.js

  • Added GET and POST routes for managing user profiles.
  • Implemented profile data formatting and validation.
  • Integrated NEAR blockchain interactions for profile management.
  • +146/-0 
    nearSocialUtils.js
    Add utility functions for NEAR social interactions             

    near-social-ai-agent/utils/nearSocialUtils.js

  • Added utility functions for fetching social profiles, followers, and
    following.
  • Implemented NEAR blockchain queries for social data.
  • +137/-0 
    utils.js
    Add data utility functions for NEAR interactions                 

    near-social-ai-agent/utils/utils.js

  • Added utility functions for data size estimation and NEAR amount
    calculation.
  • Implemented functions for data conversion and duplication removal.
  • +117/-0 
    post.js
    Add post creation route and NEAR integration                         

    near-social-ai-agent/routes/post.js

  • Added POST route for creating user posts.
  • Implemented content and optional image handling.
  • Integrated NEAR blockchain interactions for post management.
  • +120/-0 
    follow.js
    Add follow management route and NEAR integration                 

    near-social-ai-agent/routes/follow.js

  • Added POST route for managing user follow actions.
  • Implemented NEAR blockchain interactions for follow management.
  • +106/-0 
    imageUtils.js
    Add image upload utility for IPFS                                               

    near-social-ai-agent/utils/imageUtils.js

  • Added utility function for uploading images to IPFS.
  • Implemented image handling and conversion functions.
  • +95/-0   
    app.js
    Set up Express server and route configurations                     

    near-social-ai-agent/app.js

  • Set up Express server with routes for profile, post, and follow
    management.
  • Configured environment variables and static file serving.
  • +25/-0   
    constant.js
    Define constants for NEAR social contract                               

    near-social-ai-agent/utils/constant.js

    • Defined constants for NEAR social contract and network ID.
    +4/-0     
    Documentation
    2 files
    ai-plugin.json
    Add OpenAPI specification for AI plugin                                   

    near-social-ai-agent/public/.well-known/ai-plugin.json

  • Added OpenAPI specification for AI plugin.
  • Defined endpoints for profile and post management.
  • +238/-0 
    README.md
    Add README with project details and setup instructions     

    near-social-ai-agent/README.md

  • Added project introduction and key features.
  • Provided user flow and setup instructions.
  • +84/-0   
    Configuration changes
    2 files
    package.json
    Initialize project with dependencies and metadata               

    near-social-ai-agent/package.json

  • Initialized project with dependencies and scripts.
  • Defined project metadata and author information.
  • +23/-0   
    vercel.json
    Add Vercel configuration for deployment                                   

    near-social-ai-agent/vercel.json

    • Added Vercel configuration for deployment.
    +20/-0   
    Additional files (token-limit)
    1 files
    package-lock.json
    ...                                                                                                           

    near-social-ai-agent/package-lock.json

    ...

    +1769/-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 Sep 28, 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 28, 2024 0:35am
    templates-blogchain ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 28, 2024 0:35am
    templates-coingecko-ai-plugin-simple ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 28, 2024 0:35am
    templates-contract-deployer ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 28, 2024 0:35am

    Copy link

    vercel bot commented Sep 28, 2024

    @Johnson-8844 is attempting to deploy a commit to the Mintbase Team on Vercel.

    A member of the Team first needs to authorize it.

    @mintbase-codium-pr-agent
    Copy link

    PR Reviewer Guide 🔍

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

    Error Handling
    The error handling in the POST route does not return a response when missing details are detected (lines 39-41). This could lead to hanging requests if not all required fields are provided.

    Logging Sensitive Data
    The code logs potentially sensitive data, such as the entire request body (line 32). Consider removing or sanitizing logs that might contain sensitive user information.

    Inconsistent Variable Names
    The variables accountId and accountID are used interchangeably (line 35), which could lead to confusion and errors. It's recommended to standardize the variable naming.

    Commented Code
    There is commented-out code that could be confusing and should be removed if it is not needed (lines 31, 84-86).

    Error Propagation
    The function getSocialProfile catches errors but only logs them without rethrowing or handling them further (line 35). This might suppress important errors that should be handled upstream.

    @mintbase-codium-pr-agent
    Copy link

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Enhancement
    Add a "400" response for missing required fields in the POST method of "/api/profile"

    Add a "400" response to the POST method under "/api/profile" to handle cases where
    required fields are missing in the request, improving API robustness and client
    error handling.

    near-social-ai-agent/public/.well-known/ai-plugin.json [100-116]

     "responses": {
         "200": {
             "description": "Profile data uploaded successfully.",
             "content": {
                 "application/json": {
                     "schema": {
                         "type": "object",
                         "properties": {
                             "profileUrl": {
                                 "type": "string",
                                 "description": "URL for the user to sign the transaction."
                             }
                         }
                     }
                 }
             }
    +    },
    +    "400": {
    +        "description": "Bad Request: Missing required fields.",
    +        "content": {
    +            "application/json": {
    +                "schema": {
    +                    "type": "object",
    +                    "properties": {
    +                        "error": {
    +                            "type": "string",
    +                            "description": "Description of the missing fields."
    +                        }
    +                    }
    +                }
    +            }
    +        }
         }
     }
     
    Suggestion importance[1-10]: 9

    Why: Adding a "400" response improves API robustness and client error handling, which is crucial for a reliable and user-friendly API.

    9
    Add a default error response for the POST method of "/api/post"

    Add a "default" response to handle unexpected errors for the POST method under
    "/api/post", enhancing error handling and client feedback.

    near-social-ai-agent/public/.well-known/ai-plugin.json [217-233]

     "responses": {
         "200": {
             "description": "Post created successfully.",
             "content": {
                 "application/json": {
                     "schema": {
                         "type": "object",
                         "properties": {
                             "postUrl": {
                                 "type": "string",
                                 "description": "URL for the user to sign the transaction for creating the post."
                             }
                         }
                     }
                 }
             }
    +    },
    +    "default": {
    +        "description": "Unexpected error",
    +        "content": {
    +            "application/json": {
    +                "schema": {
    +                    "type": "object",
    +                    "properties": {
    +                        "error": {
    +                            "type": "string",
    +                            "description": "Error message describing the unexpected error."
    +                        }
    +                    }
    +                }
    +            }
    +        }
         }
     }
     
    Suggestion importance[1-10]: 8

    Why: Including a default error response enhances error handling and client feedback, making the API more resilient to unexpected issues.

    8
    Improve error message specificity

    Replace the hardcoded error message with a more descriptive and specific message
    that includes the missing field names.

    near-social-ai-agent/routes/profile.js [40]

    -console.log("Missing details");
    +console.log("Missing details: accountId, name, about, tags, profileImage, bannerImage, twitter, github, telegram, website");
     
    Suggestion importance[1-10]: 7

    Why: The suggestion improves the error message by making it more descriptive, which can help in debugging. However, it does not address a critical issue.

    7
    Simplify property extraction with destructuring

    Use destructuring to simplify the extraction of multiple properties from the
    req.body object, enhancing code readability.

    near-social-ai-agent/routes/profile.js [31-35]

    -const body = req.body;
    -const { accountId, accountID, name, about, profileImage, bannerImage, twitter, github, telegram, website, tags } = body;
    +const { accountId, accountID, name, about, profileImage, bannerImage, twitter, github, telegram, website, tags } = req.body;
     
    Suggestion importance[1-10]: 6

    Why: The suggestion enhances code readability by using destructuring, but it is a minor improvement and does not address any functional or critical issues.

    6
    Standardize the capitalization of "ID" in property descriptions

    Correct the inconsistent capitalization of "Id" in various descriptions to "ID" for
    consistency and adherence to common conventions.

    near-social-ai-agent/public/.well-known/ai-plugin.json [42]

    -"description": "User's account Id."
    +"description": "User's account ID."
     
    Suggestion importance[1-10]: 6

    Why: Consistent capitalization of "ID" enhances readability and adheres to common conventions, making the documentation more professional.

    6
    Error handling
    Add error handling for asynchronous storage fetching

    Implement error handling for the asynchronous getAvailableStorage function to catch
    and handle potential rejections or errors.

    near-social-ai-agent/routes/profile.js [79]

    -const storage = await getAvailableStorage(account);
    +let storage;
    +try {
    +  storage = await getAvailableStorage(account);
    +} catch (error) {
    +  console.error("Failed to fetch storage:", error);
    +  return res.status(500).json({ error: 'Failed to fetch storage data' });
    +}
     
    Suggestion importance[1-10]: 9

    Why: This suggestion adds necessary error handling for the asynchronous getAvailableStorage function, which is crucial for robustness and preventing potential crashes.

    9
    Security
    Ensure the existence of the .env file before loading environment variables

    For better security and error handling, it's advisable to check if the .env file
    exists before calling dotenv.config(). This can prevent the application from
    starting with undefined environment variables, which might lead to runtime errors.

    near-social-ai-agent/app.js [4]

    -require('dotenv').config();
    +if (fs.existsSync(path.join(__dirname, '.env'))) {
    +    require('dotenv').config();
    +} else {
    +    console.error('.env file not found');
    +    process.exit(1);
    +}
     
    Suggestion importance[1-10]: 9

    Why: Checking for the existence of the .env file before loading it enhances security and prevents potential runtime errors due to missing environment variables. This is a significant improvement.

    9
    Maintainability
    Refactor missing fields check to use a loop for better maintainability

    Refactor the conditional checks for missing fields to use a loop that iterates over
    an array of required fields, improving code maintainability and scalability.

    near-social-ai-agent/routes/profile.js [39-41]

    -if (!account || !name || !about || !tags || !profileImage || !bannerImage || !twitter || !github || !telegram || !website) {
    -  console.log("Missing details");
    +const requiredFields = ['account', 'name', 'about', 'tags', 'profileImage', 'bannerImage', 'twitter', 'github', 'telegram', 'website'];
    +const missingFields = requiredFields.filter(field => !body[field]);
    +if (missingFields.length > 0) {
    +  console.log("Missing details:", missingFields.join(', '));
     }
     
    Suggestion importance[1-10]: 8

    Why: The refactoring improves code maintainability and scalability by using a loop to check for missing fields, making the code cleaner and easier to update.

    8
    Use environment variables for the port number to enhance configurability

    To enhance the maintainability and scalability of the application, consider using a
    configuration file or environment variables for the port number instead of
    hardcoding it. This allows for easier adjustments in different environments without
    modifying the code.

    near-social-ai-agent/app.js [23-25]

    -app.listen(8080, () => {
    -    console.log("AI Agent Running on port : 8080")
    +const PORT = process.env.PORT || 8080;
    +app.listen(PORT, () => {
    +    console.log(`AI Agent Running on port : ${PORT}`)
     })
     
    Suggestion importance[1-10]: 8

    Why: Using environment variables for the port number improves the application's maintainability and scalability by allowing easier adjustments for different environments without modifying the code.

    8
    Possible bug
    Correct the path in the static middleware to properly serve static files

    The static middleware path should be corrected to ensure that the 'public' directory
    is properly served. The current implementation might not correctly resolve the path,
    which could lead to static files not being served correctly.

    near-social-ai-agent/app.js [8]

    -app.use('public', express.static(path.join(__dirname, 'public')));
    +app.use('/public', express.static(path.join(__dirname, 'public')));
     
    Suggestion importance[1-10]: 8

    Why: Correcting the path in the static middleware ensures that static files are served correctly, which is crucial for the application's functionality. This addresses a potential bug.

    8
    Best practice
    Use explicit HTTP status codes for clarity and better client handling

    It is recommended to use a more specific HTTP status code than the default 200 for
    successful responses, especially for API endpoints. This can help clients handle
    responses more accurately. For the route handling the AI plugin JSON file, consider
    returning a 200 status explicitly if the file is successfully served, or a different
    status code if there are any issues (e.g., file not found).

    near-social-ai-agent/app.js [20]

    -res.sendFile(path.join(__dirname, 'public/.well-known/ai-plugin.json'));
    +res.status(200).sendFile(path.join(__dirname, 'public/.well-known/ai-plugin.json'));
     
    Suggestion importance[1-10]: 7

    Why: Explicitly setting the HTTP status code improves clarity and helps clients handle responses more accurately. However, it is a minor improvement as the default status code is already 200.

    7
    Possible issue
    Correct the spelling of "guide" in the assistant description

    Replace the incorrect spelling of "guIde" with "guide" in the assistant description
    to maintain professionalism and clarity in the documentation.

    near-social-ai-agent/public/.well-known/ai-plugin.json [17]

    -"description": "Assistant for helping users to setup their profile on Near Social platform and upload a post on Near Social platform. You will guIde the user through collecting profile details and get a signing URL from the API response. Finally display the profileUrl to the user."
    +"description": "Assistant for helping users to setup their profile on Near Social platform and upload a post on Near Social platform. You will guide the user through collecting profile details and get a signing URL from the API response. Finally display the profileUrl to the user."
     
    Suggestion importance[1-10]: 7

    Why: Correcting the spelling of "guide" improves professionalism and clarity in the documentation, which is important for user understanding and trust.

    7

    @microchipgnu
    Copy link
    Member

    I've tested here: https://wallet.bitte.ai/smart-actions/G5pYXPf6-Vk4VR5zJoxuS?mode=debug&agentId=nearsocialaiagent-eudccfeugga5fbe0.eastus-01.azurewebsites.net

    I would love you to be able to return the transaction payload so users sign the upload post transaction directly from the wallet. Something like this: https://wallet.bitte.ai/smart-actions/HDVk_lVf36hG7jBIraMfj

    @Immanuel-john
    Copy link
    Author

    I've tested here: https://wallet.bitte.ai/smart-actions/G5pYXPf6-Vk4VR5zJoxuS?mode=debug&agentId=nearsocialaiagent-eudccfeugga5fbe0.eastus-01.azurewebsites.net

    I would love you to be able to return the transaction payload so users sign the upload post transaction directly from the wallet. Something like this: https://wallet.bitte.ai/smart-actions/HDVk_lVf36hG7jBIraMfj

    hi @microchipgnu the feedback is incorporated and here is the reference chat link - https://wallet.bitte.ai/smart-actions/share/TGlYkjrvHAmGWl48nC1y-

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    documentation Improvements or additions to documentation enhancement New feature or request Review effort [1-5]: 4
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    3 participants