Merge branch 'gib-bounty-sol033188' of github.com:adpthegreat/solana-agent-kit into gib-bounty-sol033188

This commit is contained in:
aryan
2024-12-23 14:00:14 +05:30
12 changed files with 305 additions and 126 deletions

View File

@@ -9,11 +9,15 @@ import { SolanaAgentKit } from "../index";
*/
export async function get_balance(
agent: SolanaAgentKit,
token_address?: PublicKey
) {
token_address?: PublicKey,
): Promise<number> {
if (!token_address)
return await agent.connection.getBalance(agent.wallet_address) / LAMPORTS_PER_SOL
return (
(await agent.connection.getBalance(agent.wallet_address)) /
LAMPORTS_PER_SOL
);
const token_account = await agent.connection.getTokenAccountBalance(token_address);
return token_account.value.uiAmount;
const token_account =
await agent.connection.getTokenAccountBalance(token_address);
return token_account.value.uiAmount || 0;
}

View File

@@ -15,7 +15,6 @@ export * from "./get_token_data";
export * from "./stake_with_jup";
export * from "./fetch_price";
export * from "./send_compressed_airdrop";
export * from "./create_orca_single_sided_whirlpool";
export * from "./get_all_domains_tlds";
export * from "./get_all_registered_all_domains";
@@ -24,7 +23,16 @@ export * from "./get_main_all_domains_domain";
export * from "./get_owned_all_domains";
export * from "./resolve_domain";
export * from "./get_all_domains_tlds";
export * from "./get_all_registered_all_domains";
export * from "./get_owned_domains_for_tld";
export * from "./get_main_all_domains_domain";
export * from "./get_owned_all_domains";
export * from "./resolve_domain";
export * from "./raydium_create_ammV4";
export * from "./raydium_create_clmm";
export * from "./raydium_create_cpmm";
export * from "./openbook_create_market";
export * from "./pyth_fetch_price";

View File

@@ -1,23 +1,27 @@
// src/tools/launch_pumpfun_token.ts
import { VersionedTransaction, Keypair } from "@solana/web3.js";
import { PumpFunTokenOptions, SolanaAgentKit } from "../index";
import {
PumpfunLaunchResponse,
PumpFunTokenOptions,
SolanaAgentKit,
} from "../index";
async function uploadMetadata(
tokenName: string,
tokenName: string,
tokenTicker: string,
description: string,
imageUrl: string,
options?: PumpFunTokenOptions
options?: PumpFunTokenOptions,
): Promise<any> {
// Create metadata object
const formData = new URLSearchParams();
formData.append('name', tokenName);
formData.append("name", tokenName);
formData.append("symbol", tokenTicker);
formData.append("description", description);
formData.append("showName", "true");
if (options?.twitter) formData.append('twitter', options.twitter);
if (options?.twitter) formData.append("twitter", options.twitter);
if (options?.telegram) formData.append("telegram", options.telegram);
if (options?.website) formData.append("website", options.website);
@@ -35,13 +39,12 @@ async function uploadMetadata(
}
// Add file if exists
if (files?.file) {
finalFormData.append('file', files.file);
finalFormData.append("file", files.file);
}
const metadataResponse = await fetch("https://pump.fun/api/ipfs", {
method: "POST",
body: finalFormData
body: finalFormData,
});
if (!metadataResponse.ok) {
@@ -55,7 +58,7 @@ async function createTokenTransaction(
agent: SolanaAgentKit,
mintKeypair: Keypair,
metadataResponse: any,
options?: PumpFunTokenOptions
options?: PumpFunTokenOptions,
) {
const payload = {
publicKey: agent.wallet_address.toBase58(),
@@ -78,12 +81,14 @@ async function createTokenTransaction(
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload)
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Transaction creation failed: ${response.status} - ${errorText}`);
throw new Error(
`Transaction creation failed: ${response.status} - ${errorText}`,
);
}
return response;
@@ -92,12 +97,13 @@ async function createTokenTransaction(
async function signAndSendTransaction(
kit: SolanaAgentKit,
tx: VersionedTransaction,
mintKeypair: Keypair
mintKeypair: Keypair,
) {
try {
// Get the latest blockhash
const { blockhash, lastValidBlockHeight } = await kit.connection.getLatestBlockhash();
const { blockhash, lastValidBlockHeight } =
await kit.connection.getLatestBlockhash();
// Update transaction with latest blockhash
tx.message.recentBlockhash = blockhash;
@@ -107,15 +113,15 @@ async function signAndSendTransaction(
// Send and confirm transaction with options
const signature = await kit.connection.sendTransaction(tx, {
skipPreflight: false,
preflightCommitment: 'confirmed',
maxRetries: 5
preflightCommitment: "confirmed",
maxRetries: 5,
});
// Wait for confirmation
const confirmation = await kit.connection.confirmTransaction({
signature,
blockhash,
lastValidBlockHeight
lastValidBlockHeight,
});
if (confirmation.value.err) {
@@ -124,9 +130,9 @@ async function signAndSendTransaction(
return signature;
} catch (error) {
console.error('Transaction send error:', error);
if (error instanceof Error && 'logs' in error) {
console.error('Transaction logs:', error.logs);
console.error("Transaction send error:", error);
if (error instanceof Error && "logs" in error) {
console.error("Transaction logs:", error.logs);
}
throw error;
}
@@ -140,6 +146,7 @@ async function signAndSendTransaction(
* @param description - Description of the token
* @param imageUrl - URL of the token image
* @param options - Optional token options (twitter, telegram, website, initialLiquiditySOL, slippageBps, priorityFee)
* @returns - Signature of the transaction, mint address and metadata URI, if successful, else error
*/
export async function launchPumpFunToken(
agent: SolanaAgentKit,
@@ -147,15 +154,27 @@ export async function launchPumpFunToken(
tokenTicker: string,
description: string,
imageUrl: string,
options?: PumpFunTokenOptions
) {
options?: PumpFunTokenOptions,
): Promise<PumpfunLaunchResponse> {
try {
const mintKeypair = Keypair.generate();
const metadataResponse = await uploadMetadata(tokenName, tokenTicker, description, imageUrl, options);
const response = await createTokenTransaction(agent, mintKeypair, metadataResponse, options);
const metadataResponse = await uploadMetadata(
tokenName,
tokenTicker,
description,
imageUrl,
options,
);
const response = await createTokenTransaction(
agent,
mintKeypair,
metadataResponse,
options,
);
const transactionData = await response.arrayBuffer();
const tx = VersionedTransaction.deserialize(new Uint8Array(transactionData));
const tx = VersionedTransaction.deserialize(
new Uint8Array(transactionData),
);
const signature = await signAndSendTransaction(agent, tx, mintKeypair);
return {
@@ -163,12 +182,11 @@ export async function launchPumpFunToken(
mint: mintKeypair.publicKey.toBase58(),
metadataUri: metadataResponse.metadataUri,
};
} catch (error) {
console.error("Error in launchpumpfuntoken:", error);
if (error instanceof Error && 'logs' in error) {
console.error('Transaction logs:', (error as any).logs);
if (error instanceof Error && "logs" in error) {
console.error("Transaction logs:", (error as any).logs);
}
throw error;
}
}
}

View File

@@ -0,0 +1,48 @@
import { PublicKey } from "@solana/web3.js";
import { SolanaAgentKit } from "../index";
import { Tool } from "langchain/tools";
import { PriceServiceConnection } from "@pythnetwork/price-service-client";
import BN from "bn.js";
/**
* Fetch the price of a given price feed from Pyth
* @param agent SolanaAgentKit instance
* @param priceFeedID Price feed ID
* @returns Latest price value from feed
*
* You can find priceFeedIDs here: https://www.pyth.network/developers/price-feed-ids#stable
*/
export async function pythFetchPrice(
agent: SolanaAgentKit,
priceFeedID: string
) {
// get Hermes service URL from https://docs.pyth.network/price-feeds/api-instances-and-providers/hermes
const stableHermesServiceUrl: string = "https://hermes.pyth.network";
const connection = new PriceServiceConnection(stableHermesServiceUrl);
const feeds = [priceFeedID];
try {
const currentPrice = await connection.getLatestPriceFeeds(feeds);
if (currentPrice === undefined) {
throw new Error("Price data not available for the given token.");
}
if (currentPrice.length === 0) {
throw new Error("Price data not available for the given token.");
}
// get price and exponent from price feed
let price = new BN(currentPrice[0].getPriceUnchecked().price);
let exponent = new BN(currentPrice[0].getPriceUnchecked().expo);
// convert to scaled price
let scaledPrice = price.div(new BN(10).pow(exponent));
return scaledPrice.toString();
} catch (error: any) {
throw new Error(`Fetching price from Pyth failed: ${error.message}`);
}
}