Feat: Added Pumpfun Token Launch

This commit is contained in:
Scriptscrypt
2024-11-28 01:50:31 +05:30
parent 68d250df24
commit b2a9ddcd06
6 changed files with 1897 additions and 151 deletions

View File

@@ -9,11 +9,9 @@ import {
transfer,
trade,
registerDomain,
lendAsset,
getLendingDetails,
getTPS,
launchpumpfuntoken,
} from "../tools";
import { CollectionOptions, LuloDepositAssetMint } from "../types";
import { CollectionOptions } from "../types";
import { DEFAULT_OPTIONS } from "../constants";
/**
@@ -31,23 +29,11 @@ export class SolanaAgentKit {
public wallet_address: PublicKey;
constructor(
privateKey?: string,
rpcURL = "https://api.mainnet-beta.solana.com",
private_key: string,
rpc_url = "https://api.mainnet-beta.solana.com"
) {
this.connection = new Connection(rpcURL);
if (privateKey) {
this.wallet = Keypair.fromSecretKey(bs58.decode(privateKey));
} else {
this.wallet = Keypair.generate();
console.log("Generated new wallet: ", this.wallet.publicKey.toBase58());
console.log(
"Safely store the private key: ",
"\n----------------------------------\n",
this.wallet.secretKey,
"\n----------------------------------\n",
"Please fund this wallet with SOL to use it (on mainnet), or use the faucet method to request funds (only on devnet/testnet).",
);
}
this.connection = new Connection(rpc_url);
this.wallet = Keypair.fromSecretKey(bs58.decode(private_key));
this.wallet_address = this.wallet.publicKey;
}
@@ -57,7 +43,7 @@ export class SolanaAgentKit {
}
async deployToken(
decimals: number = DEFAULT_OPTIONS.TOKEN_DECIMALS,
decimals: number = DEFAULT_OPTIONS.TOKEN_DECIMALS
// initialSupply?: number
) {
return deploy_token(this, decimals);
@@ -74,7 +60,7 @@ export class SolanaAgentKit {
async mintNFT(
collectionMint: PublicKey,
metadata: Parameters<typeof mintCollectionNFT>[2],
recipient?: PublicKey,
recipient?: PublicKey
) {
return mintCollectionNFT(this, collectionMint, metadata, recipient);
}
@@ -91,24 +77,24 @@ export class SolanaAgentKit {
outputMint: PublicKey,
inputAmount: number,
inputMint?: PublicKey,
slippageBps: number = DEFAULT_OPTIONS.SLIPPAGE_BPS,
slippageBps: number = DEFAULT_OPTIONS.SLIPPAGE_BPS
) {
return trade(this, outputMint, inputAmount, inputMint, slippageBps);
}
async lendAssets(
asset: LuloDepositAssetMint,
amount: number,
LULO_API_KEY: string,
async launchpumpfuntoken(
tokenName: string,
tokenTicker: string,
options: {
description: string;
twitter: string;
telegram: string;
website: string;
imageUrl: string;
initialLiquiditySOL: any;
mintAddress: string;
}
) {
return lendAsset(this, asset, amount, LULO_API_KEY);
}
async fetchLendingDetails(LULO_API_KEY: string) {
return getLendingDetails(this, LULO_API_KEY);
}
async getTPS() {
return getTPS(this);
return launchpumpfuntoken(this, tokenName, tokenTicker, options);
}
}

View File

@@ -4,9 +4,8 @@ import { PublicKey } from "@solana/web3.js";
export class SolanaBalanceTool extends Tool {
name = "solana_balance";
description =
"Get the balance of a Solana wallet or token account. Input can be a token address or empty for SOL balance.";
description = "Get the balance of a Solana wallet or token account. Input can be a token address or empty for SOL balance.";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
@@ -24,9 +23,8 @@ export class SolanaBalanceTool extends Tool {
export class SolanaTransferTool extends Tool {
name = "solana_transfer";
description =
"Transfer tokens or SOL to another address. Input should be JSON string with: {to: string, amount: number, mint?: string}";
description = "Transfer tokens or SOL to another address. Input should be JSON string with: {to: string, amount: number, mint?: string}";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
@@ -36,7 +34,7 @@ export class SolanaTransferTool extends Tool {
const { to, amount, mint } = JSON.parse(input);
const recipient = new PublicKey(to);
const mintAddress = mint ? new PublicKey(mint) : undefined;
await this.solanaKit.transfer(recipient, amount, mintAddress);
return `Successfully transferred ${amount} to ${to}`;
} catch (error: any) {
@@ -47,16 +45,15 @@ export class SolanaTransferTool extends Tool {
export class SolanaDeployTokenTool extends Tool {
name = "solana_deploy_token";
description =
"Deploy a new SPL token. Input should be JSON string with: {decimals?: number, initialSupply?: number}";
description = "Deploy a new SPL token. Input should be JSON string with: {decimals?: number, initialSupply?: number}";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
async _call(input: string): Promise<string> {
try {
const validJson = input
const validJson = input
.replace(/([a-zA-Z0-9_]+):/g, '"$1":') // Add quotes around keys
.trim();
const { decimals = 9 } = JSON.parse(validJson);
@@ -70,9 +67,8 @@ export class SolanaDeployTokenTool extends Tool {
export class SolanaDeployCollectionTool extends Tool {
name = "solana_deploy_collection";
description =
"Deploy a new NFT collection. Input should be JSON with: {name: string, uri: string, royaltyBasisPoints?: number, creators?: Array<{address: string, percentage: number}>}";
description = "Deploy a new NFT collection. Input should be JSON with: {name: string, uri: string, royaltyBasisPoints?: number, creators?: Array<{address: string, percentage: number}>}";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
@@ -90,9 +86,8 @@ export class SolanaDeployCollectionTool extends Tool {
export class SolanaMintNFTTool extends Tool {
name = "solana_mint_nft";
description =
"Mint a new NFT in a collection. Input should be JSON with: {collectionMint: string, metadata: {name: string, symbol: string, uri: string}, recipient?: string}";
description = "Mint a new NFT in a collection. Input should be JSON with: {collectionMint: string, metadata: {name: string, symbol: string, uri: string}, recipient?: string}";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
@@ -104,7 +99,7 @@ export class SolanaMintNFTTool extends Tool {
const result = await this.solanaKit.mintNFT(
new PublicKey(collectionMint),
metadata,
recipientPubkey,
recipientPubkey
);
return `NFT minted successfully. Mint address: ${result.mint.toString()}`;
} catch (error: any) {
@@ -115,22 +110,20 @@ export class SolanaMintNFTTool extends Tool {
export class SolanaTradeTool extends Tool {
name = "solana_trade";
description =
"Swap tokens using Jupiter Exchange. Input should be JSON with: {outputMint: string, inputAmount: number, inputMint?: string, slippageBps?: number}";
description = "Swap tokens using Jupiter Exchange. Input should be JSON with: {outputMint: string, inputAmount: number, inputMint?: string, slippageBps?: number}";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
async _call(input: string): Promise<string> {
try {
const { outputMint, inputAmount, inputMint, slippageBps } =
JSON.parse(input);
const { outputMint, inputAmount, inputMint, slippageBps } = JSON.parse(input);
const tx = await this.solanaKit.trade(
new PublicKey(outputMint),
inputAmount,
inputMint ? new PublicKey(inputMint) : undefined,
slippageBps,
slippageBps
);
return `Trade executed successfully. Transaction: ${tx}`;
} catch (error: any) {
@@ -142,7 +135,7 @@ export class SolanaTradeTool extends Tool {
export class SolanaRequestFundsTool extends Tool {
name = "solana_request_funds";
description = "Request SOL from Solana faucet (devnet/testnet only)";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
@@ -159,9 +152,8 @@ export class SolanaRequestFundsTool extends Tool {
export class SolanaRegisterDomainTool extends Tool {
name = "solana_register_domain";
description =
"Register a .sol domain name. Input should be JSON with: {name: string, spaceKB?: number}";
description = "Register a .sol domain name. Input should be JSON with: {name: string, spaceKB?: number}";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
@@ -180,7 +172,7 @@ export class SolanaRegisterDomainTool extends Tool {
export class SolanaGetWalletAddressTool extends Tool {
name = "solana_get_wallet_address";
description = "Get the wallet address of the agent";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
@@ -190,69 +182,57 @@ export class SolanaGetWalletAddressTool extends Tool {
}
}
export class SolanaLendAssetTool extends Tool {
name = "solana_lend_asset";
description =
"Lend idle assets for yield using Lulo. Input should be JSON with: {asset: string, amount: number, luloApiKey: string}";
export class SolanaPumpfunTokenLaunch extends Tool {
name = "solana_launch_pumpfun_token";
description = "Launch a new token on Pump.fun via Solana Agent Kit. Input should be JSON with: {tokenName: string, tokenTicker: string, description?: string, twitter?: string, telegram?: string, website?: string, imageUrl?: string, initialLiquiditySOL?: number, mintAddress?: string}";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
async _call(input: string): Promise<string> {
try {
const { asset, amount, luloApiKey } = JSON.parse(input);
// Parse and validate input
const validJson = input
.replace(/([a-zA-Z0-9_]+):/g, '"$1":')
.trim();
const {
tokenName,
tokenTicker,
description,
twitter,
telegram,
website,
imageUrl,
initialLiquiditySOL,
mintAddress
} = JSON.parse(validJson);
const tx = await this.solanaKit.lendAssets(
new PublicKey(asset),
amount,
luloApiKey,
if (!tokenName || !tokenTicker) {
throw new Error("tokenName and tokenTicker are required");
}
// Launch token with options
const result = await this.solanaKit.launchpumpfuntoken(
tokenName,
tokenTicker,
{
description,
twitter,
telegram,
website,
imageUrl,
initialLiquiditySOL,
mintAddress,
}
);
return `Asset lent successfully. Transaction: ${tx}`;
return `Token launched successfully.
Transaction: ${result.signature}
Mint Address: ${result.mint}
Metadata URI: ${result.metadataUri}`;
} catch (error: any) {
return `Error lending asset: ${error.message}`;
}
}
}
export class SolanaFetchLendingDetailsTool extends Tool {
name = "solana_get_lending_details";
description =
"Get details of assets lent on Lulo. Input should be JSON with: {luloApiKey: string}";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
async _call(input: string): Promise<string> {
try {
const { luloApiKey } = JSON.parse(input);
const lendingDetails =
await this.solanaKit.fetchLendingDetails(luloApiKey);
return `Lending details: ${lendingDetails}`;
} catch (error: any) {
return `Error fetching lending details: ${error.message}`;
}
}
}
export class SolanaTPSCalculatorTool extends Tool {
name = "solana_get_tps";
description = "Get the current TPS of the Solana network";
constructor(private solanaKit: SolanaAgentKit) {
super();
}
async _call(_input: string): Promise<string> {
try {
const tps = await this.solanaKit.getTPS();
return `Solana (mainnet-beta) current transactions per second: ${tps}`;
} catch (error: any) {
return `Error fetching TPS: ${error.message}`;
return `Error launching token: ${error.message}`;
}
}
}
@@ -269,8 +249,6 @@ export function createSolanaTools(solanaKit: SolanaAgentKit) {
new SolanaRequestFundsTool(solanaKit),
new SolanaRegisterDomainTool(solanaKit),
new SolanaGetWalletAddressTool(solanaKit),
new SolanaLendAssetTool(solanaKit),
new SolanaFetchLendingDetailsTool(solanaKit),
new SolanaTPSCalculatorTool(solanaKit),
new SolanaPumpfunTokenLaunch(solanaKit)
];
}

View File

@@ -1,10 +1,9 @@
export * from "./request_faucet_funds";
export * from "./deploy_token";
export * from "./deploy_collection";
export * from "./get_balance";
export * from "./mint_nft";
export * from "./transfer";
export * from "./trade";
export * from "./register_domain";
export * from "./lend";
export * from "./get_tps";
export * from './request_faucet_funds';
export * from './deploy_token';
export * from './deploy_collection';
export * from './get_balance';
export * from './mint_nft';
export * from './transfer';
export * from './trade';
export * from './register_domain';
export * from './launch_pumpfun_token';

View File

@@ -0,0 +1,182 @@
// src/tools/launch_pumpfun_token.ts
import { VersionedTransaction, Keypair } from "@solana/web3.js";
import { PumpFunTokenOptions, SolanaAgentKit } from "../index";
import fetch from "node-fetch";
import FormData from 'form-data';
async function uploadMetadata(
tokenName: string,
tokenTicker: string,
options: PumpFunTokenOptions
): Promise<any> {
// Create form data for IPFS
const formData: FormData = new FormData();
// required fields
formData.append("name", tokenName);
formData.append("symbol", tokenTicker);
formData.append("description", options.description || `${tokenName} token created via PumpPortal.fun`);
formData.append("showName", "true");
// optional fields
if (options.twitter) formData.append("twitter", options.twitter);
if (options.telegram) formData.append("telegram", options.telegram);
if (options.website) formData.append("website", options.website);
// If imageUrl is provided, fetch and append the image
if (options.imageUrl) {
const imageResponse = await fetch(options.imageUrl);
const imageBuffer = await imageResponse.buffer();
formData.append("file", imageBuffer, {
filename: "token_image.png",
contentType: "image/png"
});
}
// TBD : Remove after approval
console.log("Uploading metadata with fields:", {
name: tokenName,
symbol: tokenTicker,
description: options.description,
hasImage: !!options.imageUrl
});
const metadataResponse = await fetch("https://pump.fun/api/ipfs", {
method: "POST",
body: formData as any,
headers: formData.getHeaders()
});
if (!metadataResponse.ok) {
const errorText = await metadataResponse.text();
throw new Error(`Metadata upload failed: ${errorText || metadataResponse.statusText}`);
}
return await metadataResponse.json();
}
async function createTokenTransaction(
kit: SolanaAgentKit,
mintKeypair: Keypair,
metadataResponse: any,
options: PumpFunTokenOptions
) {
const response = await fetch("https://pumpportal.fun/api/trade-local", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
publicKey: kit.wallet_address.toBase58(),
action: "create",
tokenMetadata: {
name: metadataResponse.metadata.name,
symbol: metadataResponse.metadata.symbol,
uri: metadataResponse.metadataUri,
},
mint: mintKeypair.publicKey.toBase58(),
denominatedInSol: "true",
amount: options.initialLiquiditySOL || 0.0001,
slippage: 5,
priorityFee: 0.00005,
pool: "pump",
}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Transaction creation failed: ${response.status} - ${errorText}`);
}
return response;
}
async function signAndSendTransaction(
kit: SolanaAgentKit,
tx: VersionedTransaction,
mintKeypair: Keypair
) {
try {
// Get the latest blockhash
const { blockhash, lastValidBlockHeight } = await kit.connection.getLatestBlockhash();
// Update transaction with latest blockhash
tx.message.recentBlockhash = blockhash;
// Sign the transaction
tx.sign([mintKeypair, kit.wallet]);
// Send and confirm transaction with options
const signature = await kit.connection.sendTransaction(tx, {
skipPreflight: false,
preflightCommitment: 'confirmed',
maxRetries: 5
});
// Wait for confirmation
const confirmation = await kit.connection.confirmTransaction({
signature,
blockhash,
lastValidBlockHeight
});
if (confirmation.value.err) {
throw new Error(`Transaction failed: ${confirmation.value.err}`);
}
return signature;
} catch (error) {
console.error('Transaction send error:', error);
if (error instanceof Error && 'logs' in error) {
console.error('Transaction logs:', error.logs);
}
throw error;
}
}
export async function launchpumpfuntoken(
kit: SolanaAgentKit,
tokenName: string,
tokenTicker: string,
options: PumpFunTokenOptions = {}
) {
try {
// TBD : Remove clgs after approval
console.log("Starting token launch process...");
// Generate mint keypair
const mintKeypair = Keypair.generate();
console.log("Mint public key:", mintKeypair.publicKey.toBase58());
// Upload metadata
console.log("Uploading metadata to IPFS...");
const metadataResponse = await uploadMetadata(tokenName, tokenTicker, options);
console.log("Metadata response:", metadataResponse);
// Create token transaction
console.log("Creating token transaction...");
const response = await createTokenTransaction(kit, mintKeypair, metadataResponse, options);
const transactionData = await response.arrayBuffer();
const tx = VersionedTransaction.deserialize(new Uint8Array(transactionData));
// Send transaction with proper blockhash handling
console.log("Sending transaction...");
const signature = await signAndSendTransaction(kit, tx, mintKeypair);
console.log("Token launch successful!");
return {
signature,
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);
}
throw error;
}
}

View File

@@ -1,5 +1,4 @@
import { PublicKey } from "@solana/web3.js";
import { TOKENS } from "../constants";
export interface Creator {
address: string;
@@ -24,22 +23,21 @@ export interface MintCollectionNFTResponse {
metadata: PublicKey;
}
/**
* Mint addresses of supported tokens for lending on Lulo
*/
export type LuloDepositAssetMint = (typeof TOKENS)[keyof typeof TOKENS];
/**
* Lulo Account Details response format
*/
export interface LuloAccountDetailsResponse {
totalValue: number;
interestEarned: number;
realtimeApy: number;
settings: {
owner: string;
allowedProtocols: string | null;
homebase: string | null;
minimumRate: string;
};
export interface PumpFunTokenOptions {
description?: string;
twitter?: string;
telegram?: string;
website?: string;
imageUrl?: string;
initialLiquiditySOL?: any;
slippageBps?: number;
priorityFee?: number;
mintAddress?: string; // Optional mint address
}
export interface PumpfunLaunchResponse {
signature: string;
mint: string;
metadataUri?: string;
error?: string;
}

1603
yarn.lock Normal file

File diff suppressed because it is too large Load Diff