mirror of
https://github.com/d0zingcat/solana-agent-kit.git
synced 2026-05-22 15:10:43 +00:00
Merge branch 'main' into feat/squads_multisig
This commit is contained in:
@@ -31,7 +31,7 @@
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["test/**/*", "src/utils/keypair.ts"],
|
||||
"files": ["test/**/*", "src/utils/keypair.ts", "examples/**/*"],
|
||||
"rules": {
|
||||
"no-console": "off"
|
||||
}
|
||||
|
||||
17
README.md
17
README.md
@@ -2,8 +2,6 @@
|
||||
|
||||
# Solana Agent Kit
|
||||
|
||||
|
||||
|
||||

|
||||
|
||||
|
||||
@@ -25,6 +23,10 @@ An open-source toolkit for connecting AI agents to Solana protocols. Now, any ag
|
||||
|
||||
Anyone - whether an SF-based AI researcher or a crypto-native builder - can bring their AI agents trained with any model and seamlessly integrate with Solana.
|
||||
|
||||
|
||||
[](https://replit.com/@sendaifun/Solana-Agent-Kit)
|
||||
> Replit template created by [Arpit Singh](https://github.com/The-x-35)
|
||||
|
||||
## 🔧 Core Blockchain Features
|
||||
|
||||
- **Token Operations**
|
||||
@@ -237,6 +239,17 @@ The toolkit relies on several key Solana and Metaplex libraries:
|
||||
Contributions are welcome! Please feel free to submit a Pull Request.
|
||||
Refer to [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines on how to contribute to this project.
|
||||
|
||||
## Contributors
|
||||
|
||||
<a href="https://github.com/sendaifun/solana-agent-kit/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=sendaifun/solana-agent-kit" />
|
||||
</a>
|
||||
|
||||
|
||||
## Star History
|
||||
|
||||
[](https://star-history.com/#sendaifun/solana-agent-kit&Date)
|
||||
|
||||
## License
|
||||
|
||||
Apache-2 License
|
||||
|
||||
63
SECURITY.md
Normal file
63
SECURITY.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
We take the security of our software seriously. If you believe you have found a security vulnerability, please report it to us following these guidelines:
|
||||
|
||||
### Reporting Process
|
||||
|
||||
1. **DO NOT** create a public GitHub issue for the vulnerability
|
||||
2. Email your findings to:
|
||||
- Primary: aryan@sendai.fun
|
||||
- Secondary: dev@sendai.fun
|
||||
|
||||
### What to Include
|
||||
|
||||
Please include the following information in your report:
|
||||
|
||||
- A clear description of the vulnerability
|
||||
- Steps to reproduce the issue
|
||||
- Affected versions
|
||||
- Any potential impacts
|
||||
- Optional: Suggested fixes or mitigations
|
||||
|
||||
### Response Timeline
|
||||
|
||||
- We will acknowledge receipt of your vulnerability report within 48 hours
|
||||
- We aim to send a more detailed response within 5 business days
|
||||
- We will keep you informed of our progress throughout the process
|
||||
|
||||
### Security Updates
|
||||
|
||||
Security updates will be released as soon as possible after we have confirmed and fixed the vulnerability. Updates will be published through:
|
||||
|
||||
- GitHub releases
|
||||
- Security advisories
|
||||
- Email notifications to affected parties (if applicable)
|
||||
|
||||
## Supported Versions
|
||||
|
||||
As an open-source project under the Apache 2.0 license, we focus our security updates on the latest stable release. While you're free to use any version as per the Apache 2.0 license terms, we strongly recommend using the most recent version for the best security posture.
|
||||
|
||||
| Version | Security Updates |
|
||||
| ------- | --------------- |
|
||||
| Latest Release | ✅ Active |
|
||||
| Previous Releases | ⚠️ Use at your own risk |
|
||||
|
||||
Note: The Apache 2.0 license comes with NO WARRANTIES or CONDITIONS of any kind, either express or implied. Users are responsible for their own security assessment when using any version of this software.
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
When using this software, please follow these security best practices:
|
||||
- Keep your private keys secure and never share them
|
||||
- Regularly update to the latest version
|
||||
- Review transaction details before signing
|
||||
- Use appropriate access controls in production environments
|
||||
|
||||
## Bug Bounty Program
|
||||
|
||||
Currently, we do not offer a bug bounty program. However, we greatly appreciate responsible disclosure of security vulnerabilities.
|
||||
|
||||
## License
|
||||
|
||||
This security policy is part of our project licensed under [Apache 2.0](LICENSE).
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -15,6 +15,10 @@
|
||||
<li>And more...</li>
|
||||
</ul>
|
||||
<p>Anyone - whether an SF-based AI researcher or a crypto-native builder - can bring their AI agents trained with any model and seamlessly integrate with Solana.</p>
|
||||
<p><a href="https://replit.com/@sendaifun/Solana-Agent-Kit" target="_blank" class="external"><img src="https://replit.com/badge/github/sendaifun/solana-agent-kit" alt="Run on Repl.it"></a></p>
|
||||
<blockquote>
|
||||
<p>Replit template created by <a href="https://github.com/The-x-35" target="_blank" class="external">Arpit Singh</a></p>
|
||||
</blockquote>
|
||||
<a id="md:🔧-core-blockchain-features" class="tsd-anchor"></a><h2 class="tsd-anchor-link">🔧 Core Blockchain Features<a href="#md:🔧-core-blockchain-features" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><ul>
|
||||
<li>
|
||||
<p><strong>Token Operations</strong></p>
|
||||
@@ -149,6 +153,10 @@
|
||||
</ul>
|
||||
<a id="md:contributing" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Contributing<a href="#md:contributing" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>Contributions are welcome! Please feel free to submit a Pull Request.
|
||||
Refer to <a href="media/CONTRIBUTING.md">CONTRIBUTING.md</a> for detailed guidelines on how to contribute to this project.</p>
|
||||
<a id="md:contributors" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Contributors<a href="#md:contributors" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><a href="https://github.com/sendaifun/solana-agent-kit/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=sendaifun/solana-agent-kit" />
|
||||
</a>
|
||||
<a id="md:star-history" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Star History<a href="#md:star-history" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p><a href="https://star-history.com/#sendaifun/solana-agent-kit&Date" target="_blank" class="external"><img src="https://api.star-history.com/svg?repos=sendaifun/solana-agent-kit&type=Date" alt="Star History Chart"></a></p>
|
||||
<a id="md:license" class="tsd-anchor"></a><h2 class="tsd-anchor-link">License<a href="#md:license" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>Apache-2 License</p>
|
||||
<a id="md:security" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Security<a href="#md:security" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>This toolkit handles private keys and transactions. Always ensure you're using it in a secure environment and never share your private keys.</p>
|
||||
</div></div><div class="col-sidebar"><div class="page-menu"><div class="tsd-navigation settings"><details class="tsd-accordion"><summary class="tsd-accordion-summary"><h3><svg width="20" height="20" viewBox="0 0 24 24" fill="none"><use href="assets/icons.svg#icon-chevronDown"></use></svg>Settings</h3></summary><div class="tsd-accordion-details"><div class="tsd-filter-visibility"><span class="settings-label">Member Visibility</span><ul id="tsd-filter-options"><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-protected" name="protected"/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>Protected</span></label></li><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-inherited" name="inherited" checked/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>Inherited</span></label></li><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-external" name="external"/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>External</span></label></li></ul></div><div class="tsd-theme-toggle"><label class="settings-label" for="tsd-theme">Theme</label><select id="tsd-theme"><option value="os">OS</option><option value="light">Light</option><option value="dark">Dark</option></select></div></div></details></div><details open class="tsd-accordion tsd-page-navigation"><summary class="tsd-accordion-summary"><h3><svg width="20" height="20" viewBox="0 0 24 24" fill="none"><use href="assets/icons.svg#icon-chevronDown"></use></svg>On This Page</h3></summary><div class="tsd-accordion-details"><a href="#md:solana-agent-kit"><span>Solana <wbr/>Agent <wbr/>Kit</span></a><ul><li><a href="#md:🔧-core-blockchain-features"><span>🔧 <wbr/>Core <wbr/>Blockchain <wbr/>Features</span></a></li><li><a href="#md:🤖-ai-integration-features"><span>🤖 AI <wbr/>Integration <wbr/>Features</span></a></li><li><a href="#md:📦-installation"><span>📦 <wbr/>Installation</span></a></li><li><a href="#md:quick-start"><span>Quick <wbr/>Start</span></a></li><li><a href="#md:usage-examples"><span>Usage <wbr/>Examples</span></a></li><li><ul><li><a href="#md:deploy-a-new-token"><span>Deploy a <wbr/>New <wbr/>Token</span></a></li><li><a href="#md:create-nft-collection"><span>Create NFT <wbr/>Collection</span></a></li><li><a href="#md:swap-tokens"><span>Swap <wbr/>Tokens</span></a></li><li><a href="#md:lend-tokens"><span>Lend <wbr/>Tokens</span></a></li><li><a href="#md:stake-sol"><span>Stake SOL</span></a></li><li><a href="#md:send-an-spl-token-airdrop-via-zk-compression"><span>Send an SPL <wbr/>Token <wbr/>Airdrop via ZK <wbr/>Compression</span></a></li><li><a href="#md:fetch-price-data-from-pyth"><span>Fetch <wbr/>Price <wbr/>Data from <wbr/>Pyth</span></a></li></ul></li><li><a href="#md:examples"><span>Examples</span></a></li><li><ul><li><a href="#md:langgraph-multi-agent-system"><span>Lang<wbr/>Graph <wbr/>Multi-<wbr/>Agent <wbr/>System</span></a></li></ul></li><li><a href="#md:dependencies"><span>Dependencies</span></a></li><li><a href="#md:contributing"><span>Contributing</span></a></li><li><a href="#md:license"><span>License</span></a></li><li><a href="#md:security"><span>Security</span></a></li></ul></div></details></div><div class="site-menu"><nav class="tsd-navigation"><a href="modules.html" class="current"><svg class="tsd-kind-icon" viewBox="0 0 24 24"><use href="assets/icons.svg#icon-1"></use></svg><span>solana-agent-kit</span></a><ul class="tsd-small-nested-navigation" id="tsd-nav-container" data-base="."><li>Loading...</li></ul></nav></div></div></div><footer><p class="tsd-generator">Generated using <a href="https://typedoc.org/" target="_blank">TypeDoc</a></p></footer><div class="overlay"></div></body></html>
|
||||
</div></div><div class="col-sidebar"><div class="page-menu"><div class="tsd-navigation settings"><details class="tsd-accordion"><summary class="tsd-accordion-summary"><h3><svg width="20" height="20" viewBox="0 0 24 24" fill="none"><use href="assets/icons.svg#icon-chevronDown"></use></svg>Settings</h3></summary><div class="tsd-accordion-details"><div class="tsd-filter-visibility"><span class="settings-label">Member Visibility</span><ul id="tsd-filter-options"><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-protected" name="protected"/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>Protected</span></label></li><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-inherited" name="inherited" checked/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>Inherited</span></label></li><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-external" name="external"/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>External</span></label></li></ul></div><div class="tsd-theme-toggle"><label class="settings-label" for="tsd-theme">Theme</label><select id="tsd-theme"><option value="os">OS</option><option value="light">Light</option><option value="dark">Dark</option></select></div></div></details></div><details open class="tsd-accordion tsd-page-navigation"><summary class="tsd-accordion-summary"><h3><svg width="20" height="20" viewBox="0 0 24 24" fill="none"><use href="assets/icons.svg#icon-chevronDown"></use></svg>On This Page</h3></summary><div class="tsd-accordion-details"><a href="#md:solana-agent-kit"><span>Solana <wbr/>Agent <wbr/>Kit</span></a><ul><li><a href="#md:🔧-core-blockchain-features"><span>🔧 <wbr/>Core <wbr/>Blockchain <wbr/>Features</span></a></li><li><a href="#md:🤖-ai-integration-features"><span>🤖 AI <wbr/>Integration <wbr/>Features</span></a></li><li><a href="#md:📦-installation"><span>📦 <wbr/>Installation</span></a></li><li><a href="#md:quick-start"><span>Quick <wbr/>Start</span></a></li><li><a href="#md:usage-examples"><span>Usage <wbr/>Examples</span></a></li><li><ul><li><a href="#md:deploy-a-new-token"><span>Deploy a <wbr/>New <wbr/>Token</span></a></li><li><a href="#md:create-nft-collection"><span>Create NFT <wbr/>Collection</span></a></li><li><a href="#md:swap-tokens"><span>Swap <wbr/>Tokens</span></a></li><li><a href="#md:lend-tokens"><span>Lend <wbr/>Tokens</span></a></li><li><a href="#md:stake-sol"><span>Stake SOL</span></a></li><li><a href="#md:send-an-spl-token-airdrop-via-zk-compression"><span>Send an SPL <wbr/>Token <wbr/>Airdrop via ZK <wbr/>Compression</span></a></li><li><a href="#md:fetch-price-data-from-pyth"><span>Fetch <wbr/>Price <wbr/>Data from <wbr/>Pyth</span></a></li></ul></li><li><a href="#md:examples"><span>Examples</span></a></li><li><ul><li><a href="#md:langgraph-multi-agent-system"><span>Lang<wbr/>Graph <wbr/>Multi-<wbr/>Agent <wbr/>System</span></a></li></ul></li><li><a href="#md:dependencies"><span>Dependencies</span></a></li><li><a href="#md:contributing"><span>Contributing</span></a></li><li><a href="#md:contributors"><span>Contributors</span></a></li><li><a href="#md:star-history"><span>Star <wbr/>History</span></a></li><li><a href="#md:license"><span>License</span></a></li><li><a href="#md:security"><span>Security</span></a></li></ul></div></details></div><div class="site-menu"><nav class="tsd-navigation"><a href="modules.html" class="current"><svg class="tsd-kind-icon" viewBox="0 0 24 24"><use href="assets/icons.svg#icon-1"></use></svg><span>solana-agent-kit</span></a><ul class="tsd-small-nested-navigation" id="tsd-nav-container" data-base="."><li>Loading...</li></ul></nav></div></div></div><footer><p class="tsd-generator">Generated using <a href="https://typedoc.org/" target="_blank">TypeDoc</a></p></footer><div class="overlay"></div></body></html>
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,7 +1,6 @@
|
||||
import { createReactAgent } from "@langchain/langgraph/prebuilt";
|
||||
import { gpt4o } from "../utils/model";
|
||||
import { solanaAgentState } from "../utils/state";
|
||||
import { HumanMessage } from "@langchain/core/messages";
|
||||
import { agentKit } from "../utils/solanaAgent";
|
||||
import {
|
||||
SolanaBalanceTool,
|
||||
|
||||
@@ -8,27 +8,30 @@ import * as readline from "readline";
|
||||
import { PostgresSaver } from "@langchain/langgraph-checkpoint-postgres";
|
||||
dotenv.config();
|
||||
|
||||
const checkpointer = PostgresSaver.fromConnString(
|
||||
process.env.POSTGRES_DB_URL!
|
||||
);
|
||||
const checkpointer = PostgresSaver.fromConnString(process.env.POSTGRES_DB_URL!);
|
||||
|
||||
function validateEnvironment(): void {
|
||||
const missingVars: string[] = [];
|
||||
const requiredVars = ["OPENAI_API_KEY", "RPC_URL", "SOLANA_PRIVATE_KEY", "POSTGRES_DB_URL"];
|
||||
const missingVars: string[] = [];
|
||||
const requiredVars = [
|
||||
"OPENAI_API_KEY",
|
||||
"RPC_URL",
|
||||
"SOLANA_PRIVATE_KEY",
|
||||
"POSTGRES_DB_URL",
|
||||
];
|
||||
|
||||
requiredVars.forEach((varName) => {
|
||||
if (!process.env[varName]) {
|
||||
missingVars.push(varName);
|
||||
}
|
||||
});
|
||||
|
||||
if (missingVars.length > 0) {
|
||||
console.error("Error: Required environment variables are not set");
|
||||
missingVars.forEach((varName) => {
|
||||
console.error(`${varName}=your_${varName.toLowerCase()}_here`);
|
||||
});
|
||||
process.exit(1);
|
||||
requiredVars.forEach((varName) => {
|
||||
if (!process.env[varName]) {
|
||||
missingVars.push(varName);
|
||||
}
|
||||
});
|
||||
|
||||
if (missingVars.length > 0) {
|
||||
console.error("Error: Required environment variables are not set");
|
||||
missingVars.forEach((varName) => {
|
||||
console.error(`${varName}=your_${varName.toLowerCase()}_here`);
|
||||
});
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
validateEnvironment();
|
||||
@@ -36,37 +39,37 @@ validateEnvironment();
|
||||
const WALLET_DATA_FILE = "wallet_data.txt";
|
||||
|
||||
async function initializeAgent() {
|
||||
try {
|
||||
const llm = new ChatOpenAI({
|
||||
modelName: "gpt-4o-mini",
|
||||
temperature: 0.7,
|
||||
});
|
||||
try {
|
||||
const llm = new ChatOpenAI({
|
||||
modelName: "gpt-4o-mini",
|
||||
temperature: 0.7,
|
||||
});
|
||||
|
||||
let walletDataStr: string | null = null;
|
||||
let walletDataStr: string | null = null;
|
||||
|
||||
if (fs.existsSync(WALLET_DATA_FILE)) {
|
||||
try {
|
||||
walletDataStr = fs.readFileSync(WALLET_DATA_FILE, "utf8");
|
||||
} catch (error) {
|
||||
console.error("Error reading wallet data:", error);
|
||||
}
|
||||
}
|
||||
if (fs.existsSync(WALLET_DATA_FILE)) {
|
||||
try {
|
||||
walletDataStr = fs.readFileSync(WALLET_DATA_FILE, "utf8");
|
||||
} catch (error) {
|
||||
console.error("Error reading wallet data:", error);
|
||||
}
|
||||
}
|
||||
|
||||
const solanaAgent = new SolanaAgentKit(
|
||||
process.env.SOLANA_PRIVATE_KEY!,
|
||||
process.env.RPC_URL,
|
||||
process.env.OPENAI_API_KEY!,
|
||||
);
|
||||
const solanaAgent = new SolanaAgentKit(
|
||||
process.env.SOLANA_PRIVATE_KEY!,
|
||||
process.env.RPC_URL,
|
||||
process.env.OPENAI_API_KEY!,
|
||||
);
|
||||
|
||||
const tools = createSolanaTools(solanaAgent);
|
||||
await checkpointer.setup();
|
||||
const config = { configurable: { thread_id: "Solana Agent Kit!" } };
|
||||
const tools = createSolanaTools(solanaAgent);
|
||||
await checkpointer.setup();
|
||||
const config = { configurable: { thread_id: "Solana Agent Kit!" } };
|
||||
|
||||
const agent = createReactAgent({
|
||||
llm,
|
||||
tools,
|
||||
checkpointSaver: checkpointer,
|
||||
messageModifier: `
|
||||
const agent = createReactAgent({
|
||||
llm,
|
||||
tools,
|
||||
checkpointSaver: checkpointer,
|
||||
messageModifier: `
|
||||
You are a helpful agent that can interact onchain using the Solana Agent Kit. You are
|
||||
empowered to interact onchain using your tools. If you ever need funds, you can request them from the
|
||||
faucet. If not, you can provide your wallet details and request funds from the user. If there is a 5XX
|
||||
@@ -75,146 +78,146 @@ async function initializeAgent() {
|
||||
themselves using the Solana Agent Kit, recommend they go to https://www.solanaagentkit.xyz for more information. Be
|
||||
concise and helpful with your responses. Refrain from restating your tools' descriptions unless it is explicitly requested.
|
||||
`,
|
||||
});
|
||||
});
|
||||
|
||||
if (walletDataStr) {
|
||||
fs.writeFileSync(WALLET_DATA_FILE, walletDataStr);
|
||||
}
|
||||
|
||||
return { agent, config };
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize agent:", error);
|
||||
throw error;
|
||||
if (walletDataStr) {
|
||||
fs.writeFileSync(WALLET_DATA_FILE, walletDataStr);
|
||||
}
|
||||
|
||||
return { agent, config };
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize agent:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function runAutonomousMode(agent: any, config: any, interval = 10) {
|
||||
console.log("Starting autonomous mode...");
|
||||
console.log("Starting autonomous mode...");
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
const thought =
|
||||
"Be creative and do something interesting on the blockchain. " +
|
||||
"Choose an action or set of actions and execute it that highlights your abilities.";
|
||||
while (true) {
|
||||
try {
|
||||
const thought =
|
||||
"Be creative and do something interesting on the blockchain. " +
|
||||
"Choose an action or set of actions and execute it that highlights your abilities.";
|
||||
|
||||
const stream = await agent.stream(
|
||||
{ messages: [new HumanMessage(thought)] },
|
||||
config,
|
||||
);
|
||||
const stream = await agent.stream(
|
||||
{ messages: [new HumanMessage(thought)] },
|
||||
config,
|
||||
);
|
||||
|
||||
for await (const chunk of stream) {
|
||||
if ("agent" in chunk) {
|
||||
console.log(chunk.agent.messages[0].content);
|
||||
} else if ("tools" in chunk) {
|
||||
console.log(chunk.tools.messages[0].content);
|
||||
}
|
||||
console.log("-------------------");
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, interval * 1000));
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
console.error("Error:", error.message);
|
||||
}
|
||||
process.exit(1);
|
||||
for await (const chunk of stream) {
|
||||
if ("agent" in chunk) {
|
||||
console.log(chunk.agent.messages[0].content);
|
||||
} else if ("tools" in chunk) {
|
||||
console.log(chunk.tools.messages[0].content);
|
||||
}
|
||||
console.log("-------------------");
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, interval * 1000));
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
console.error("Error:", error.message);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runChatMode(agent: any, config: any) {
|
||||
console.log("Starting chat mode... Type 'exit' to end.");
|
||||
console.log("Starting chat mode... Type 'exit' to end.");
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
});
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
});
|
||||
|
||||
const question = (prompt: string): Promise<string> =>
|
||||
new Promise((resolve) => rl.question(prompt, resolve));
|
||||
const question = (prompt: string): Promise<string> =>
|
||||
new Promise((resolve) => rl.question(prompt, resolve));
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const userInput = await question("\nPrompt: ");
|
||||
try {
|
||||
while (true) {
|
||||
const userInput = await question("\nPrompt: ");
|
||||
|
||||
if (userInput.toLowerCase() === "exit") {
|
||||
break;
|
||||
}
|
||||
if (userInput.toLowerCase() === "exit") {
|
||||
break;
|
||||
}
|
||||
|
||||
const stream = await agent.stream(
|
||||
{ messages: [new HumanMessage(userInput)] },
|
||||
config,
|
||||
);
|
||||
const stream = await agent.stream(
|
||||
{ messages: [new HumanMessage(userInput)] },
|
||||
config,
|
||||
);
|
||||
|
||||
for await (const chunk of stream) {
|
||||
if ("agent" in chunk) {
|
||||
console.log(chunk.agent.messages[0].content);
|
||||
} else if ("tools" in chunk) {
|
||||
console.log(chunk.tools.messages[0].content);
|
||||
}
|
||||
console.log("-------------------");
|
||||
}
|
||||
for await (const chunk of stream) {
|
||||
if ("agent" in chunk) {
|
||||
console.log(chunk.agent.messages[0].content);
|
||||
} else if ("tools" in chunk) {
|
||||
console.log(chunk.tools.messages[0].content);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
console.error("Error:", error.message);
|
||||
}
|
||||
process.exit(1);
|
||||
} finally {
|
||||
rl.close();
|
||||
console.log("-------------------");
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
console.error("Error:", error.message);
|
||||
}
|
||||
process.exit(1);
|
||||
} finally {
|
||||
rl.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function chooseMode(): Promise<"chat" | "auto"> {
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
});
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
});
|
||||
|
||||
const question = (prompt: string): Promise<string> =>
|
||||
new Promise((resolve) => rl.question(prompt, resolve));
|
||||
const question = (prompt: string): Promise<string> =>
|
||||
new Promise((resolve) => rl.question(prompt, resolve));
|
||||
|
||||
while (true) {
|
||||
console.log("\nAvailable modes:");
|
||||
console.log("1. chat - Interactive chat mode");
|
||||
console.log("2. auto - Autonomous action mode");
|
||||
while (true) {
|
||||
console.log("\nAvailable modes:");
|
||||
console.log("1. chat - Interactive chat mode");
|
||||
console.log("2. auto - Autonomous action mode");
|
||||
|
||||
const choice = (await question("\nChoose a mode (enter number or name): "))
|
||||
.toLowerCase()
|
||||
.trim();
|
||||
const choice = (await question("\nChoose a mode (enter number or name): "))
|
||||
.toLowerCase()
|
||||
.trim();
|
||||
|
||||
rl.close();
|
||||
rl.close();
|
||||
|
||||
if (choice === "1" || choice === "chat") {
|
||||
return "chat";
|
||||
} else if (choice === "2" || choice === "auto") {
|
||||
return "auto";
|
||||
}
|
||||
console.log("Invalid choice. Please try again.");
|
||||
if (choice === "1" || choice === "chat") {
|
||||
return "chat";
|
||||
} else if (choice === "2" || choice === "auto") {
|
||||
return "auto";
|
||||
}
|
||||
console.log("Invalid choice. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
console.log("Starting Agent...");
|
||||
const { agent, config } = await initializeAgent();
|
||||
const mode = await chooseMode();
|
||||
try {
|
||||
console.log("Starting Agent...");
|
||||
const { agent, config } = await initializeAgent();
|
||||
const mode = await chooseMode();
|
||||
|
||||
if (mode === "chat") {
|
||||
await runChatMode(agent, config);
|
||||
} else {
|
||||
await runAutonomousMode(agent, config);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
console.error("Error:", error.message);
|
||||
}
|
||||
process.exit(1);
|
||||
if (mode === "chat") {
|
||||
await runChatMode(agent, config);
|
||||
} else {
|
||||
await runAutonomousMode(agent, config);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
console.error("Error:", error.message);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((error) => {
|
||||
console.error("Fatal error:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
main().catch((error) => {
|
||||
console.error("Fatal error:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
4
examples/tg-bot-starter/.env.example
Normal file
4
examples/tg-bot-starter/.env.example
Normal file
@@ -0,0 +1,4 @@
|
||||
OPENAI_API_KEY=
|
||||
RPC_URL=
|
||||
SOLANA_PRIVATE_KEY=
|
||||
TELEGRAM_BOT_TOKEN=
|
||||
41
examples/tg-bot-starter/.gitignore
vendored
Normal file
41
examples/tg-bot-starter/.gitignore
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
22
examples/tg-bot-starter/README.md
Normal file
22
examples/tg-bot-starter/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
|
||||
# Telegram Bot Starter with Solana Agent Kit
|
||||
|
||||
This example showcases how we can make a telegram bot with the Solana Agent Kit by Send AI.
|
||||
|
||||
## How to get the telegram bot token
|
||||
|
||||
You can check [here](https://help.zoho.com/portal/en/kb/desk/support-channels/instant-messaging/telegram/articles/telegram-integration-with-zoho-desk#How_to_find_a_token_for_an_existing_Telegram_Bot) how you can obtain a bot token for your telegram bot.
|
||||
|
||||
## How to setup the project
|
||||
|
||||
- Set env variables
|
||||
- Run ``` pnpm install ```
|
||||
- Run ``` pnpm run dev ```
|
||||
- Run ``` ngrok http 3000 ```
|
||||
- With the URL you got from ngrok, where your bot is hosted at https://yourUrl.app/api/bot
|
||||
- Set the webhook by using this command ``` curl https://api.telegram.org/bot<telegram_bot_token>/setWebhook?url=https://<your-deployment-url>.app/api/bot ``` or simply clicking on that link.
|
||||
- You can host it on Vercel too as we have used NextJs in this.
|
||||
- Once the URL is set successfully, you will see this ``` {"ok":true,"result":true,"description":"Webhook was set"} ```
|
||||
|
||||
Done!!! Congrtulations you just hosted Solana Agent Kit on a Telegram bot.
|
||||
|
||||
7
examples/tg-bot-starter/next.config.ts
Normal file
7
examples/tg-bot-starter/next.config.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
31
examples/tg-bot-starter/package.json
Normal file
31
examples/tg-bot-starter/package.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "tg-bot-starter",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@langchain/core": "^0.3.26",
|
||||
"@langchain/langgraph": "^0.2.36",
|
||||
"@langchain/openai": "^0.3.16",
|
||||
"grammy": "^1.33.0",
|
||||
"messages": "link:@langchain/core/messages",
|
||||
"next": "15.1.3",
|
||||
"prebuilt": "link:@langchain/langgraph/prebuilt",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"solana-agent-kit": "^1.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"postcss": "^8",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
4296
examples/tg-bot-starter/pnpm-lock.yaml
generated
Normal file
4296
examples/tg-bot-starter/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
8
examples/tg-bot-starter/postcss.config.mjs
Normal file
8
examples/tg-bot-starter/postcss.config.mjs
Normal file
@@ -0,0 +1,8 @@
|
||||
/** @type {import('postcss-load-config').Config} */
|
||||
const config = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
1
examples/tg-bot-starter/public/file.svg
Normal file
1
examples/tg-bot-starter/public/file.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
1
examples/tg-bot-starter/public/globe.svg
Normal file
1
examples/tg-bot-starter/public/globe.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
1
examples/tg-bot-starter/public/next.svg
Normal file
1
examples/tg-bot-starter/public/next.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
1
examples/tg-bot-starter/public/vercel.svg
Normal file
1
examples/tg-bot-starter/public/vercel.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
1
examples/tg-bot-starter/public/window.svg
Normal file
1
examples/tg-bot-starter/public/window.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
86
examples/tg-bot-starter/src/app/api/bot/route.ts
Normal file
86
examples/tg-bot-starter/src/app/api/bot/route.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const fetchCache = 'force-no-store';
|
||||
export const maxDuration = 300;
|
||||
|
||||
import { Bot, webhookCallback } from 'grammy';
|
||||
import { SolanaAgentKit, createSolanaTools } from "solana-agent-kit";
|
||||
import { ChatOpenAI } from "@langchain/openai";
|
||||
import { MemorySaver } from "@langchain/langgraph";
|
||||
import { createReactAgent } from "@langchain/langgraph/prebuilt";
|
||||
import { HumanMessage } from "@langchain/core/messages";
|
||||
|
||||
const token = process.env.TELEGRAM_BOT_TOKEN;
|
||||
if (!token) throw new Error('TELEGRAM_BOT_TOKEN environment variable not found.');
|
||||
const bot = new Bot(token);
|
||||
|
||||
|
||||
async function initializeAgent(userId: string) {
|
||||
try {
|
||||
const llm = new ChatOpenAI({
|
||||
modelName: "gpt-4o-mini",
|
||||
temperature: 0.7,
|
||||
});
|
||||
|
||||
const solanaKit = new SolanaAgentKit(
|
||||
process.env.SOLANA_PRIVATE_KEY!,
|
||||
process.env.RPC_URL,
|
||||
process.env.OPENAI_API_KEY!
|
||||
);
|
||||
|
||||
const tools = createSolanaTools(solanaKit);
|
||||
const memory = new MemorySaver();
|
||||
const config = { configurable: { thread_id: userId } };
|
||||
const agent = createReactAgent({
|
||||
llm,
|
||||
tools,
|
||||
checkpointSaver: memory,
|
||||
messageModifier: `
|
||||
You are a helpful agent that can interact onchain using the Solana Agent Kit. You are
|
||||
empowered to interact onchain using your tools. If you ever need funds, you can request them from the
|
||||
faucet. If not, you can provide your wallet details and request funds from the user. If there is a 5XX
|
||||
(internal) HTTP error code, ask the user to try again later. If someone asks you to do something you
|
||||
can't do with your currently available tools, you must say so, and encourage them to implement it
|
||||
themselves using the Solana Agent Kit, recommend they go to https://www.solanaagentkit.xyz for more information. Be
|
||||
concise and helpful with your responses. Refrain from restating your tools' descriptions unless it is explicitly requested.
|
||||
`,
|
||||
});
|
||||
return { agent, config };
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize agent:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
// Telegram bot handler
|
||||
bot.on('message:text', async (ctx:any) => {
|
||||
const userId = ctx.from?.id.toString();
|
||||
if (!userId) return;
|
||||
const {agent, config} = await initializeAgent(userId);
|
||||
const stream = await agent.stream({ messages: [new HumanMessage(ctx.message.text)] }, config);
|
||||
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 20000));
|
||||
try {
|
||||
for await (const chunk of await Promise.race([stream, timeoutPromise]) as AsyncIterable<{ agent?: any; tools?: any }>) {
|
||||
if ("agent" in chunk) {
|
||||
if (chunk.agent.messages[0].content) await ctx.reply(String(chunk.agent.messages[0].content));
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error.message === 'Timeout') {
|
||||
await ctx.reply("I'm sorry, the operation took too long and timed out. Please try again.");
|
||||
} else {
|
||||
console.error("Error processing stream:", error);
|
||||
await ctx.reply("I'm sorry, an error occurred while processing your request.");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Export webhook handler
|
||||
export const POST = async (req: Request) => {
|
||||
// Mark the function as a background function for Vercel
|
||||
const headers = new Headers();
|
||||
headers.set('x-vercel-background', 'true');
|
||||
|
||||
const handler = webhookCallback(bot, 'std/http'); // Use the correct callback
|
||||
|
||||
// Handle the incoming webhook request
|
||||
return handler(req);
|
||||
};
|
||||
BIN
examples/tg-bot-starter/src/app/favicon.ico
Normal file
BIN
examples/tg-bot-starter/src/app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
21
examples/tg-bot-starter/src/app/globals.css
Normal file
21
examples/tg-bot-starter/src/app/globals.css
Normal file
@@ -0,0 +1,21 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
34
examples/tg-bot-starter/src/app/layout.tsx
Normal file
34
examples/tg-bot-starter/src/app/layout.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
101
examples/tg-bot-starter/src/app/page.tsx
Normal file
101
examples/tg-bot-starter/src/app/page.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import Image from "next/image";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
|
||||
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/next.svg"
|
||||
alt="Next.js logo"
|
||||
width={180}
|
||||
height={38}
|
||||
priority
|
||||
/>
|
||||
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
|
||||
<li className="mb-2">
|
||||
Get started by editing{" "}
|
||||
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
|
||||
src/app/page.tsx
|
||||
</code>
|
||||
.
|
||||
</li>
|
||||
<li>Save and see your changes instantly.</li>
|
||||
</ol>
|
||||
|
||||
<div className="flex gap-4 items-center flex-col sm:flex-row">
|
||||
<a
|
||||
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/vercel.svg"
|
||||
alt="Vercel logomark"
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
Deploy now
|
||||
</a>
|
||||
<a
|
||||
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Read our docs
|
||||
</a>
|
||||
</div>
|
||||
</main>
|
||||
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center">
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src="/file.svg"
|
||||
alt="File icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Learn
|
||||
</a>
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src="/window.svg"
|
||||
alt="Window icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Examples
|
||||
</a>
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src="/globe.svg"
|
||||
alt="Globe icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Go to nextjs.org →
|
||||
</a>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
18
examples/tg-bot-starter/tailwind.config.ts
Normal file
18
examples/tg-bot-starter/tailwind.config.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { Config } from "tailwindcss";
|
||||
|
||||
export default {
|
||||
content: [
|
||||
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
background: "var(--background)",
|
||||
foreground: "var(--foreground)",
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
} satisfies Config;
|
||||
27
examples/tg-bot-starter/tsconfig.json
Normal file
27
examples/tg-bot-starter/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "solana-agent-kit",
|
||||
"version": "1.3.0",
|
||||
"version": "1.3.1",
|
||||
"description": "connect any ai agents to solana protocols",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
@@ -14,7 +14,7 @@
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\""
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=23.1.0",
|
||||
"node": ">=22.0.0",
|
||||
"pnpm": ">=8.0.0"
|
||||
},
|
||||
"keywords": [],
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
deploy_collection,
|
||||
deploy_token,
|
||||
get_balance,
|
||||
get_balance_other,
|
||||
getTPS,
|
||||
resolveSolDomain,
|
||||
getPrimaryDomain,
|
||||
@@ -66,12 +67,12 @@ export class SolanaAgentKit {
|
||||
public connection: Connection;
|
||||
public wallet: Keypair;
|
||||
public wallet_address: PublicKey;
|
||||
public openai_api_key: string;
|
||||
public openai_api_key: string | null;
|
||||
|
||||
constructor(
|
||||
private_key: string,
|
||||
rpc_url = "https://api.mainnet-beta.solana.com",
|
||||
openai_api_key: string,
|
||||
openai_api_key: string | null = null,
|
||||
) {
|
||||
this.connection = new Connection(rpc_url);
|
||||
this.wallet = Keypair.fromSecretKey(bs58.decode(private_key));
|
||||
@@ -104,6 +105,13 @@ export class SolanaAgentKit {
|
||||
return get_balance(this, token_address);
|
||||
}
|
||||
|
||||
async getBalanceOther(
|
||||
walletAddress: PublicKey,
|
||||
tokenAddress?: PublicKey,
|
||||
): Promise<number> {
|
||||
return get_balance_other(this, walletAddress, tokenAddress);
|
||||
}
|
||||
|
||||
async mintNFT(
|
||||
collectionMint: PublicKey,
|
||||
metadata: Parameters<typeof mintCollectionNFT>[2],
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
import { create_image } from "../tools/create_image";
|
||||
import { BN } from "@coral-xyz/anchor";
|
||||
import { FEE_TIERS } from "../tools";
|
||||
import { toJSON } from "../utils/toJSON";
|
||||
|
||||
export class SolanaBalanceTool extends Tool {
|
||||
name = "solana_balance";
|
||||
@@ -18,7 +17,7 @@ export class SolanaBalanceTool extends Tool {
|
||||
If you want to get the balance of your wallet, you don't need to provide the tokenAddress.
|
||||
If no tokenAddress is provided, the balance will be in SOL.
|
||||
|
||||
Inputs:
|
||||
Inputs ( input is a JSON string ):
|
||||
tokenAddress: string, eg "So11111111111111111111111111111111111111112" (optional)`;
|
||||
|
||||
constructor(private solanaKit: SolanaAgentKit) {
|
||||
@@ -32,7 +31,7 @@ export class SolanaBalanceTool extends Tool {
|
||||
|
||||
return JSON.stringify({
|
||||
status: "success",
|
||||
balance: balance,
|
||||
balance,
|
||||
token: input || "SOL",
|
||||
});
|
||||
} catch (error: any) {
|
||||
@@ -45,6 +44,49 @@ export class SolanaBalanceTool extends Tool {
|
||||
}
|
||||
}
|
||||
|
||||
export class SolanaBalanceOtherTool extends Tool {
|
||||
name = "solana_balance_other";
|
||||
description = `Get the balance of a Solana wallet or token account different from the agent's wallet.
|
||||
|
||||
If no tokenAddress is provided, the SOL balance of the wallet will be returned.
|
||||
|
||||
Inputs ( input is a JSON string ):
|
||||
walletAddress: string, eg "GDEkQF7UMr7RLv1KQKMtm8E2w3iafxJLtyXu3HVQZnME" (required)
|
||||
tokenAddress: string, eg "SENDdRQtYMWaQrBroBrJ2Q53fgVuq95CV9UPGEvpCxa" (optional)`;
|
||||
|
||||
constructor(private solanaKit: SolanaAgentKit) {
|
||||
super();
|
||||
}
|
||||
|
||||
protected async _call(input: string): Promise<string> {
|
||||
try {
|
||||
const { walletAddress, tokenAddress } = JSON.parse(input);
|
||||
|
||||
const tokenPubKey = tokenAddress
|
||||
? new PublicKey(tokenAddress)
|
||||
: undefined;
|
||||
|
||||
const balance = await this.solanaKit.getBalanceOther(
|
||||
new PublicKey(walletAddress),
|
||||
tokenPubKey,
|
||||
);
|
||||
|
||||
return JSON.stringify({
|
||||
status: "success",
|
||||
balance,
|
||||
wallet: walletAddress,
|
||||
token: tokenAddress || "SOL",
|
||||
});
|
||||
} catch (error: any) {
|
||||
return JSON.stringify({
|
||||
status: "error",
|
||||
message: error.message,
|
||||
code: error.code || "UNKNOWN_ERROR",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class SolanaTransferTool extends Tool {
|
||||
name = "solana_transfer";
|
||||
description = `Transfer tokens or SOL to another address ( also called as wallet address ).
|
||||
@@ -318,7 +360,7 @@ export class SolanaRegisterDomainTool extends Tool {
|
||||
|
||||
protected async _call(input: string): Promise<string> {
|
||||
try {
|
||||
const parsedInput = toJSON(input);
|
||||
const parsedInput = JSON.parse(input);
|
||||
this.validateInput(parsedInput);
|
||||
|
||||
const tx = await this.solanaKit.registerDomain(
|
||||
@@ -555,7 +597,7 @@ export class SolanaLendAssetTool extends Tool {
|
||||
status: "success",
|
||||
message: "Asset lent successfully",
|
||||
transaction: tx,
|
||||
amount: amount,
|
||||
amount,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return JSON.stringify({
|
||||
@@ -669,7 +711,7 @@ export class SolanaTokenDataTool extends Tool {
|
||||
|
||||
return JSON.stringify({
|
||||
status: "success",
|
||||
tokenData: tokenData,
|
||||
tokenData,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return JSON.stringify({
|
||||
@@ -698,7 +740,7 @@ export class SolanaTokenDataByTickerTool extends Tool {
|
||||
const tokenData = await this.solanaKit.getTokenDataByTicker(ticker);
|
||||
return JSON.stringify({
|
||||
status: "success",
|
||||
tokenData: tokenData,
|
||||
tokenData,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return JSON.stringify({
|
||||
@@ -1005,7 +1047,7 @@ export class SolanaPythFetchPrice extends Tool {
|
||||
const response: PythFetchPriceResponse = {
|
||||
status: "success",
|
||||
priceFeedID: input,
|
||||
price: price,
|
||||
price,
|
||||
};
|
||||
return JSON.stringify(response);
|
||||
} catch (error: any) {
|
||||
@@ -1079,7 +1121,7 @@ export class SolanaGetOwnedDomains extends Tool {
|
||||
return JSON.stringify({
|
||||
status: "success",
|
||||
message: "Owned domains fetched successfully",
|
||||
domains: domains,
|
||||
domains,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return JSON.stringify({
|
||||
@@ -1109,7 +1151,7 @@ export class SolanaGetOwnedTldDomains extends Tool {
|
||||
return JSON.stringify({
|
||||
status: "success",
|
||||
message: "TLD domains fetched successfully",
|
||||
domains: domains,
|
||||
domains,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return JSON.stringify({
|
||||
@@ -1136,7 +1178,7 @@ export class SolanaGetAllTlds extends Tool {
|
||||
return JSON.stringify({
|
||||
status: "success",
|
||||
message: "TLDs fetched successfully",
|
||||
tlds: tlds,
|
||||
tlds,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return JSON.stringify({
|
||||
@@ -1255,14 +1297,14 @@ export class SolanaRockPaperScissorsTool extends Tool {
|
||||
|
||||
protected async _call(input: string): Promise<string> {
|
||||
try {
|
||||
const parsedInput = toJSON(input);
|
||||
const parsedInput = JSON.parse(input);
|
||||
this.validateInput(parsedInput);
|
||||
const result = await this.solanaKit.rockPaperScissors(
|
||||
Number(parsedInput['"amount"']),
|
||||
parsedInput['"choice"'].replace(/^"|"$/g, "") as
|
||||
| "rock"
|
||||
| "paper"
|
||||
| "scissors",
|
||||
| "rock"
|
||||
| "paper"
|
||||
| "scissors",
|
||||
);
|
||||
|
||||
return JSON.stringify({
|
||||
@@ -1329,6 +1371,7 @@ export class SolanaTipLinkTool extends Tool {
|
||||
export function createSolanaTools(solanaKit: SolanaAgentKit) {
|
||||
return [
|
||||
new SolanaBalanceTool(solanaKit),
|
||||
new SolanaBalanceOtherTool(solanaKit),
|
||||
new SolanaTransferTool(solanaKit),
|
||||
new SolanaDeployTokenTool(solanaKit),
|
||||
new SolanaDeployCollectionTool(solanaKit),
|
||||
|
||||
50
src/tools/get_balance_other.ts
Normal file
50
src/tools/get_balance_other.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import {
|
||||
LAMPORTS_PER_SOL,
|
||||
ParsedAccountData,
|
||||
PublicKey,
|
||||
} from "@solana/web3.js";
|
||||
import { SolanaAgentKit } from "../index";
|
||||
|
||||
/**
|
||||
* Get the balance of SOL or an SPL token for the specified wallet address (other than the agent's wallet)
|
||||
* @param agent - SolanaAgentKit instance
|
||||
* @param wallet_address - Public key of the wallet to check balance for
|
||||
* @param token_address - Optional SPL token mint address. If not provided, returns SOL balance
|
||||
* @returns Promise resolving to the balance as a number (in UI units) or 0 if account doesn't exist
|
||||
*/
|
||||
export async function get_balance_other(
|
||||
agent: SolanaAgentKit,
|
||||
wallet_address: PublicKey,
|
||||
token_address?: PublicKey,
|
||||
): Promise<number> {
|
||||
try {
|
||||
if (!token_address) {
|
||||
return (
|
||||
(await agent.connection.getBalance(wallet_address)) / LAMPORTS_PER_SOL
|
||||
);
|
||||
}
|
||||
|
||||
const tokenAccounts = await agent.connection.getTokenAccountsByOwner(
|
||||
wallet_address,
|
||||
{ mint: token_address },
|
||||
);
|
||||
|
||||
if (tokenAccounts.value.length === 0) {
|
||||
console.warn(
|
||||
`No token accounts found for wallet ${wallet_address.toString()} and token ${token_address.toString()}`,
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const tokenAccount = await agent.connection.getParsedAccountInfo(
|
||||
tokenAccounts.value[0].pubkey,
|
||||
);
|
||||
const tokenData = tokenAccount.value?.data as ParsedAccountData;
|
||||
|
||||
return tokenData.parsed?.info?.tokenAmount?.uiAmount || 0;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Error fetching on-chain balance for ${token_address?.toString()}: ${error}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ export * from "./request_faucet_funds";
|
||||
export * from "./deploy_token";
|
||||
export * from "./deploy_collection";
|
||||
export * from "./get_balance";
|
||||
export * from "./get_balance_other";
|
||||
export * from "./mint_nft";
|
||||
export * from "./transfer";
|
||||
export * from "./trade";
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import {
|
||||
VersionedTransaction,
|
||||
PublicKey,
|
||||
LAMPORTS_PER_SOL,
|
||||
} from "@solana/web3.js";
|
||||
import { VersionedTransaction, PublicKey } from "@solana/web3.js";
|
||||
import { SolanaAgentKit } from "../index";
|
||||
import { TOKENS, DEFAULT_OPTIONS, JUP_API } from "../constants";
|
||||
|
||||
import { getMint } from "@solana/spl-token";
|
||||
/**
|
||||
* Swap tokens using Jupiter Exchange
|
||||
* @param agent SolanaAgentKit instance
|
||||
@@ -23,12 +19,23 @@ export async function trade(
|
||||
slippageBps: number = DEFAULT_OPTIONS.SLIPPAGE_BPS,
|
||||
): Promise<string> {
|
||||
try {
|
||||
// Check if input token is native SOL
|
||||
const isNativeSol = inputMint.equals(TOKENS.SOL);
|
||||
|
||||
// For native SOL, we use LAMPORTS_PER_SOL, otherwise fetch mint info
|
||||
const inputDecimals = isNativeSol
|
||||
? 9 // SOL always has 9 decimals
|
||||
: (await getMint(agent.connection, inputMint)).decimals;
|
||||
|
||||
// Calculate the correct amount based on actual decimals
|
||||
const scaledAmount = inputAmount * Math.pow(10, inputDecimals);
|
||||
|
||||
const quoteResponse = await (
|
||||
await fetch(
|
||||
`${JUP_API}/quote?` +
|
||||
`inputMint=${inputMint.toString()}` +
|
||||
`inputMint=${isNativeSol ? TOKENS.SOL.toString() : inputMint.toString()}` +
|
||||
`&outputMint=${outputMint.toString()}` +
|
||||
`&amount=${inputAmount * LAMPORTS_PER_SOL}` +
|
||||
`&amount=${scaledAmount}` +
|
||||
`&slippageBps=${slippageBps}` +
|
||||
`&onlyDirectRoutes=true` +
|
||||
`&maxAccounts=20`,
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
export const toJSON = (str: string): any => {
|
||||
try {
|
||||
// Remove curly braces and split by comma
|
||||
const pairs = str.trim().slice(1, -1).split(",");
|
||||
|
||||
// Convert to object with explicit type
|
||||
const obj: Record<string, any> = {};
|
||||
|
||||
pairs.forEach((pair) => {
|
||||
const [key, value] = pair
|
||||
.trim()
|
||||
.split(":")
|
||||
.map((s) => s.trim());
|
||||
|
||||
if (!key || value === undefined) {
|
||||
throw new Error("Invalid key-value pair format");
|
||||
}
|
||||
|
||||
obj[key] = isNaN(Number(value)) ? value : Number(value);
|
||||
});
|
||||
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse string to JSON: ${error}`);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user