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

feat: Add features to the Solana Agent Kit #2458

Merged
merged 14 commits into from
Jan 17, 2025

Conversation

thearyanag
Copy link
Contributor

Relates to:

#1619

Risks

Low

Background

What does this PR do?

Replace the solana plugin with solana agent kit

  • wrapper around the runtime for the kit
  • replace the trade function with trade action from the kit
  • replace the transfer function with transfer action from the kit
  • replace the swap dao function with trade action from the kit

What kind of change is this?

This PR improves the existing plugin by replacing with the Solana Agent Kit
In following days, will add more actions from the agent kit.

Testing

Where should a reviewer start?

packages/plugin-solana

Reference docs https://sendaifun.github.io/solana-agent-kit/

Detailed testing steps

None, automated tests are fine.

Discord username

0xaryan

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

📝 Walkthrough

Walkthrough

The pull request introduces comprehensive enhancements to the Solana plugin ecosystem, expanding its capabilities with new actions for token management, swapping, lending, staking, and transfer operations. A significant architectural change involves replacing direct SolanaAgentKit instantiation with a new getSAK utility function, which provides a more dynamic and secure method of obtaining the Solana Agent Kit instance. The modifications span multiple files, introducing robust error handling, type validation, and improved interaction templates.

Changes

File/Path Change Summary
packages/plugin-solana-agentkit/src/actions/ Added new action modules: getTokenInfo.ts, gibwork.ts, lend.ts, stake.ts, swap.ts, transfer.ts with comprehensive content validation and handler logic
packages/plugin-solana-agentkit/src/client.ts Introduced getSAK function for dynamic Solana Agent Kit retrieval
packages/plugin-solana-agentkit/src/index.ts Updated actions array to include new Solana ecosystem interactions
packages/plugin-solana-agentkit/src/keypairUtils.ts Added getWalletKey utility with TEE mode support
packages/plugin-solana/src/actions/pumpfun.ts Migrated to new SDK, updated transaction handling and metadata processing
packages/plugin-solana/package.json Updated dependencies, added solana-agent-kit

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (14)
packages/plugin-solana-agentkit/src/actions/stake.ts (2)

29-30: Ensure content.amount is defined before type checking.

Add a check to ensure content.amount is not undefined before verifying its type.

Apply this diff to improve the type check:

function isStakeContent(
    runtime: IAgentRuntime,
    content: any
): content is StakeContent {
    elizaLogger.log("Content for stake", content);
    return (
-        typeof content.amount === "number"
+        content.amount !== undefined && typeof content.amount === "number"
    );
}

38-39: Use a numeric value for amount in the example response.

The amount should be a number, not a string, to match the expected type in StakeContent.

Apply this diff to correct the example:

{
-    "amount": "100",
+    "amount": 100
}
packages/plugin-solana-agentkit/src/actions/lend.ts (2)

29-30: Ensure content.amount is defined before type checking.

Add a check to ensure content.amount is not undefined before verifying its type.

Apply this diff to improve the type check:

function isLendAssetContent(
    runtime: IAgentRuntime,
    content: any
): content is LendAssetContent {
    elizaLogger.log("Content for lend", content);
    return (
-        typeof content.amount === "number"
+        content.amount !== undefined && typeof content.amount === "number"
    );
}

38-39: Use a numeric value for amount in the example response.

The amount should be a number, not a string, to match the expected type in LendAssetContent.

Apply this diff to correct the example:

{
-    "amount": "100",
+    "amount": 100
}
packages/plugin-solana-agentkit/src/actions/getTokenInfo.ts (2)

28-28: Correct the log message in isGetTokenInfoContent

The log message incorrectly refers to "Content for transfer" instead of "Content for getTokenInfo".

-        elizaLogger.log("Content for transfer", content);
+        elizaLogger.log("Content for getTokenInfo", content);

105-105: Use elizaLogger for consistent logging

Replace console.log with elizaLogger.log to maintain consistent logging practices.

-            console.log("Token data:", tokenData);
+            elizaLogger.log("Token data:", tokenData);
packages/plugin-solana-agentkit/src/actions/swap.ts (2)

62-66: Implement validation logic in validate function

The validate function always returns true. Consider adding proper validation to ensure the message contains the necessary parameters.

-            return true;
+            // TODO: Implement actual validation logic
+            return isValid; // Replace with appropriate validation result

152-156: Remove duplicate error handling for transaction confirmation

The code checks confirmation.value.err twice, which is redundant. Remove the duplicate check to clean up the code.

                if (confirmation.value.err) {
                    throw new Error(
                        `Transaction failed: ${confirmation.value.err}`
                    );
                }

-                if (confirmation.value.err) {
-                    throw new Error(
-                        `Transaction failed: ${confirmation.value.err}`
-                    );
-                }
packages/plugin-solana/src/actions/pumpfun.ts (5)

109-112: Simplify transaction handling by removing unnecessary serialization

Serializing and then immediately deserializing transactions is redundant. You can send the versionedTx directly without these steps.

Apply this diff to streamline the code:

For createAndBuyToken:

         versionedTx.sign([mint]);

-        const serializedTransaction = versionedTx.serialize();
-        const serializedTransactionBase64 = Buffer.from(
-            serializedTransaction
-        ).toString("base64");

-        const deserializedTx = VersionedTransaction.deserialize(
-            Buffer.from(serializedTransactionBase64, "base64")
-        );

-        const txid = await connection.sendTransaction(deserializedTx, {
+        const txid = await connection.sendTransaction(versionedTx, {

Repeat similar changes for buyToken and sellToken.

Also applies to: 114-116, 218-223, 224-227, 318-323, 324-327


Line range hint 455-478: Remove commented-out code for cleanliness

The large block of commented-out code can be removed to improve readability.

-    /*
-        // Generate image if tokenMetadata.file is empty or invalid
-        if (!tokenMetadata.file || tokenMetadata.file.length < 100) {  // Basic validation
-            try {
-                const imageResult = await generateImage({
-                    prompt: `logo for ${tokenMetadata.name} (${tokenMetadata.symbol}) token - ${tokenMetadata.description}`,
-                    width: 512,
-                    height: 512,
-                    count: 1
-                }, runtime);
-
-                if (imageResult.success && imageResult.data && imageResult.data.length > 0) {
-                    // Remove the "data:image/png;base64," prefix if present
-                    tokenMetadata.file = imageResult.data[0].replace(/^data:image\/[a-z]+;base64,/, '');
-                } else {
-                    elizaLogger.error("Failed to generate image:", imageResult.error);
-                    return false;
-                }
-            } catch (error) {
-                elizaLogger.error("Error generating image:", error);
-                return false;
-            }
-        } */

275-343: Refactor duplicate code in buyToken and sellToken functions

The buyToken and sellToken functions share similar structures. Extract common logic into a helper function to enhance maintainability.


539-542: Make network environment configurable

The network is hardcoded as "devnet". Allow configuring the network through settings to enable flexibility.

Apply this diff:

-        const sdk = new Fomo(connection, "devnet", deployerKeypair);
+        const network = runtime.getSetting("SOLANA_NETWORK") || "devnet";
+        const sdk = new Fomo(connection, network, deployerKeypair);

618-624: Update example to match action implementation

The example mentions generating a description and buying SOL worth .buy 0.00069 SOL worth. Ensure the example aligns with the current action's capabilities.

packages/plugin-solana/package.json (1)

33-33: Lock the solana-agent-kit version.

Using ^1.4.0 could lead to unexpected breaking changes. Consider using a fixed version like other dependencies.

-        "solana-agent-kit": "^1.4.0",
+        "solana-agent-kit": "1.4.0",
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 24729ee and c71be97.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (16)
  • packages/plugin-solana-agentkit/src/actions/createToken.ts (2 hunks)
  • packages/plugin-solana-agentkit/src/actions/getTokenInfo.ts (1 hunks)
  • packages/plugin-solana-agentkit/src/actions/gibwork.ts (1 hunks)
  • packages/plugin-solana-agentkit/src/actions/lend.ts (1 hunks)
  • packages/plugin-solana-agentkit/src/actions/stake.ts (1 hunks)
  • packages/plugin-solana-agentkit/src/actions/swap.ts (1 hunks)
  • packages/plugin-solana-agentkit/src/actions/transfer.ts (1 hunks)
  • packages/plugin-solana-agentkit/src/client.ts (1 hunks)
  • packages/plugin-solana-agentkit/src/index.ts (1 hunks)
  • packages/plugin-solana-agentkit/src/keypairUtils.ts (1 hunks)
  • packages/plugin-solana/package.json (1 hunks)
  • packages/plugin-solana/src/actions/pumpfun.ts (18 hunks)
  • packages/plugin-solana/src/actions/swap.ts (1 hunks)
  • packages/plugin-solana/src/actions/swapDao.ts (1 hunks)
  • packages/plugin-solana/src/actions/transfer.ts (1 hunks)
  • packages/plugin-solana/src/index.ts (1 hunks)
✅ Files skipped from review due to trivial changes (4)
  • packages/plugin-solana/src/actions/transfer.ts
  • packages/plugin-solana/src/actions/swapDao.ts
  • packages/plugin-solana/src/actions/swap.ts
  • packages/plugin-solana/src/index.ts
🧰 Additional context used
🪛 Gitleaks (8.21.2)
packages/plugin-solana-agentkit/src/actions/transfer.ts

50-50: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

packages/plugin-solana-agentkit/src/actions/swap.ts

28-28: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

packages/plugin-solana-agentkit/src/actions/gibwork.ts

52-52: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (10)
packages/plugin-solana-agentkit/src/keypairUtils.ts (1)

17-82: Well-structured getWalletKey function with comprehensive error handling.

The function effectively manages key retrieval based on TEE mode and includes robust error handling for various key formats.

packages/plugin-solana/src/actions/pumpfun.ts (2)

520-524: Ensure secure handling of private keys

Private keys are retrieved directly from settings. Confirm that sensitive information is stored and accessed securely.


495-496: ⚠️ Potential issue

Verify the correctness of the metadata upload endpoint

There's a FIXME comment questioning the API endpoint used for metadata upload. Ensure that https://pump.fun/api/ipfs is valid or update it to the correct endpoint provided by fomo.fund.

packages/plugin-solana-agentkit/src/index.ts (1)

3-8: Expand plugin actions to include new functionalities

New actions swap, lend, stake, transfer, getTokenInfo, and gibwork have been added. Verify that these actions are correctly implemented and integrated.

Also applies to: 13-13

packages/plugin-solana-agentkit/src/client.ts (1)

1-23: Ensure correct initialization of SolanaAgentKit in getSAK

The new getSAK function retrieves the keypair and initializes SolanaAgentKit. Confirm that the keypair retrieval is secure and that the keys match as expected.

packages/plugin-solana-agentkit/src/actions/createToken.ts (2)

104-104: LGTM! Improved modularity with getSAK.

The refactor to use getSAK utility function enhances code maintainability.


Line range hint 106-111: Address the commented initialSupply parameter.

The initialSupply parameter is commented out due to an SDK issue. This needs to be tracked and resolved.

Would you like me to create a GitHub issue to track the SDK issue with initialSupply parameter?

packages/plugin-solana-agentkit/src/actions/transfer.ts (3)

134-138: LGTM! Proper PublicKey validation.

Good use of PublicKey for validating addresses before transfer.


68-88: ⚠️ Potential issue

Implement the commented admin validation logic.

The commented-out admin validation logic should be implemented to ensure proper access control for token transfers.

Would you like me to help implement the admin validation logic?


50-50: ⚠️ Potential issue

Remove API key from example response template.

The example response template contains what appears to be an API key. Replace it with a placeholder value.

-    "tokenAddress": "BieefG47jAHCGZBxi2q87RDuHyGZyYC3vAzxpyu8pump",
+    "tokenAddress": "<token-address>",

Likely invalid or redundant comment.

🧰 Tools
🪛 Gitleaks (8.21.2)

50-50: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

packages/plugin-solana-agentkit/src/actions/gibwork.ts Outdated Show resolved Hide resolved
packages/plugin-solana/src/actions/pumpfun.ts Show resolved Hide resolved
@thearyanag thearyanag changed the title 1619 add solana agent kit Feat: Add features to the Solana Agent Kit Jan 17, 2025
@wtfsayo
Copy link
Member

wtfsayo commented Jan 17, 2025

@coderabbitai security analysis

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

Tip

For best results, initiate chat on the files or code changes.

@wtfsayo Here's the security analysis of the changes:

Key Management:

  • ⚠️ Private keys are stored in runtime settings. Consider using a secure key management service.
  • ✅ TEE (Trusted Execution Environment) mode is available for enhanced security.
  • ⚠️ OpenAI API key is exposed in client initialization. Consider moving it to a secure environment.

Input Validation:

  • ✅ Strong type validation for all actions using TypeScript interfaces.
  • ✅ Solana address validation using PublicKey class.
  • 🔧 Recommendation: Add range checks for token amounts to prevent overflow attacks.

Error Handling:

  • ✅ Comprehensive error catching and logging.
  • ✅ User-facing error messages are sanitized.
  • 🔧 Recommendation: Add rate limiting for failed attempts.

Dependencies:

  • ✅ Using recent versions: solana-agent-kit v1.4.0, @solana/web3.js v1.95.8
  • 🔧 Recommendation: Set up automated dependency scanning.

Configuration:

  • ⚠️ Sensitive configuration in runtime settings.
  • 🔧 Recommendation: Use environment-specific configuration management.

Overall Risk Assessment: Medium

  • The codebase follows security best practices but has room for improvement in key management and configuration handling.

Would you like me to create GitHub issues for tracking these security improvements?

🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potentially sensitive information exposure
echo "=== Searching for potential sensitive info exposure ==="
rg -i "key|secret|password|token" packages/plugin-solana-agentkit/

# Check for input validation
echo -e "\n=== Analyzing input validation ==="
ast-grep --pattern 'function is$_Content($_) { $$$_ }' packages/plugin-solana-agentkit/

# Look for error handling patterns
echo -e "\n=== Analyzing error handling ==="
rg "throw|catch|error" packages/plugin-solana-agentkit/

# Check package dependencies
echo -e "\n=== Checking dependencies ==="
cat packages/plugin-solana/package.json
cat packages/plugin-solana-agentkit/package.json

# Review key management code
echo -e "\n=== Reviewing key management ==="
cat packages/plugin-solana-agentkit/src/keypairUtils.ts
cat packages/plugin-solana-agentkit/src/client.ts

Length of output: 2637


Script:

#!/bin/bash
# Find relevant files
echo "=== Finding relevant files ==="
fd -t f "package.json|keypairUtils.ts|client.ts" --no-ignore-vcs

# Find all TypeScript files in solana related directories
echo -e "\n=== Finding Solana related files ==="
fd -t f -e ts . --no-ignore-vcs | rg -i "solana"

# Search for potentially sensitive patterns in all TypeScript files
echo -e "\n=== Searching for sensitive patterns ==="
rg -t ts -i "key|secret|password|token"

# Look for input validation in TypeScript files
echo -e "\n=== Analyzing input validation ==="
rg -t ts "function is\w+Content"

# Look for error handling patterns
echo -e "\n=== Analyzing error handling ==="
rg -t ts "throw new|catch|error:"

Length of output: 82008


✏️ Learnings added
Learnt from: wtfsayo
URL: https://github.com/elizaOS/eliza/pull/2458

Timestamp: 2025-01-17T20:18:02.101Z
Learning: The Solana Agent Kit integration requires secure key management practices, including TEE mode support and proper handling of private keys in runtime settings.

Learnt from: wtfsayo
URL: https://github.com/elizaOS/eliza/pull/2458

Timestamp: 2025-01-17T20:18:02.101Z
Learning: Input validation for Solana operations should include range checks for token amounts to prevent overflow attacks, in addition to type validation and address verification.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@wtfsayo
Copy link
Member

wtfsayo commented Jan 17, 2025

its okay @coderabbitai for this plugin

@wtfsayo wtfsayo self-requested a review January 17, 2025 20:27
Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

Tip

For best results, initiate chat on the files or code changes.

@wtfsayo Understood! I'll proceed with the review considering the current security implementation as acceptable for this plugin.

(`・ω・´)ゞ

@wtfsayo wtfsayo changed the title Feat: Add features to the Solana Agent Kit feat: Add features to the Solana Agent Kit Jan 17, 2025
@wtfsayo wtfsayo merged commit 0f643c0 into elizaOS:develop Jan 17, 2025
7 of 10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants