forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpumpfun.ts
522 lines (483 loc) · 16.7 KB
/
pumpfun.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import { AnchorProvider } from "@coral-xyz/anchor";
import { Wallet } from "@coral-xyz/anchor";
import { generateImage } from "@elizaos/core";
import { Connection, Keypair, PublicKey } from "@solana/web3.js";
import { CreateTokenMetadata, PriorityFee, PumpFunSDK } from "pumpdotfun-sdk";
import { getAssociatedTokenAddressSync } from "@solana/spl-token";
import {
settings,
ActionExample,
Content,
HandlerCallback,
IAgentRuntime,
Memory,
ModelClass,
State,
generateObjectDeprecated,
composeContext,
type Action,
elizaLogger,
} from "@elizaos/core";
import { walletProvider } from "../providers/wallet.ts";
export interface CreateAndBuyContent extends Content {
tokenMetadata: {
name: string;
symbol: string;
description: string;
image_description: string;
};
buyAmountSol: string | number;
}
export function isCreateAndBuyContent(
runtime: IAgentRuntime,
content: any
): content is CreateAndBuyContent {
elizaLogger.log("Content for create & buy", content);
return (
typeof content.tokenMetadata === "object" &&
content.tokenMetadata !== null &&
typeof content.tokenMetadata.name === "string" &&
typeof content.tokenMetadata.symbol === "string" &&
typeof content.tokenMetadata.description === "string" &&
typeof content.tokenMetadata.image_description === "string" &&
(typeof content.buyAmountSol === "string" ||
typeof content.buyAmountSol === "number")
);
}
export const createAndBuyToken = async ({
deployer,
mint,
tokenMetadata,
buyAmountSol,
priorityFee,
allowOffCurve,
commitment = "confirmed",
sdk,
connection,
slippage,
}: {
deployer: Keypair;
mint: Keypair;
tokenMetadata: CreateTokenMetadata;
buyAmountSol: bigint;
priorityFee: PriorityFee;
allowOffCurve: boolean;
commitment?:
| "processed"
| "confirmed"
| "finalized"
| "recent"
| "single"
| "singleGossip"
| "root"
| "max";
sdk: PumpFunSDK;
connection: Connection;
slippage: string;
}) => {
const createResults = await sdk.createAndBuy(
deployer,
mint,
tokenMetadata,
buyAmountSol,
BigInt(slippage),
priorityFee,
commitment
);
elizaLogger.log("Create Results: ", createResults);
if (createResults.success) {
elizaLogger.log(
"Success:",
`https://pump.fun/${mint.publicKey.toBase58()}`
);
const ata = getAssociatedTokenAddressSync(
mint.publicKey,
deployer.publicKey,
allowOffCurve
);
const balance = await connection.getTokenAccountBalance(
ata,
"processed"
);
const amount = balance.value.uiAmount;
if (amount === null) {
elizaLogger.log(
`${deployer.publicKey.toBase58()}:`,
"No Account Found"
);
} else {
elizaLogger.log(`${deployer.publicKey.toBase58()}:`, amount);
}
return {
success: true,
ca: mint.publicKey.toBase58(),
creator: deployer.publicKey.toBase58(),
};
} else {
elizaLogger.log("Create and Buy failed");
return {
success: false,
ca: mint.publicKey.toBase58(),
error: createResults.error || "Transaction failed",
};
}
};
export const buyToken = async ({
sdk,
buyer,
mint,
amount,
priorityFee,
allowOffCurve,
slippage,
connection,
}: {
sdk: PumpFunSDK;
buyer: Keypair;
mint: PublicKey;
amount: bigint;
priorityFee: PriorityFee;
allowOffCurve: boolean;
slippage: string;
connection: Connection;
}) => {
const buyResults = await sdk.buy(
buyer,
mint,
amount,
BigInt(slippage),
priorityFee
);
if (buyResults.success) {
elizaLogger.log("Success:", `https://pump.fun/${mint.toBase58()}`);
const ata = getAssociatedTokenAddressSync(
mint,
buyer.publicKey,
allowOffCurve
);
const balance = await connection.getTokenAccountBalance(
ata,
"processed"
);
const amount = balance.value.uiAmount;
if (amount === null) {
elizaLogger.log(
`${buyer.publicKey.toBase58()}:`,
"No Account Found"
);
} else {
elizaLogger.log(`${buyer.publicKey.toBase58()}:`, amount);
}
} else {
elizaLogger.log("Buy failed");
}
};
export const sellToken = async ({
sdk,
seller,
mint,
amount,
priorityFee,
allowOffCurve,
slippage,
connection,
}: {
sdk: PumpFunSDK;
seller: Keypair;
mint: PublicKey;
amount: bigint;
priorityFee: PriorityFee;
allowOffCurve: boolean;
slippage: string;
connection: Connection;
}) => {
const sellResults = await sdk.sell(
seller,
mint,
amount,
BigInt(slippage),
priorityFee
);
if (sellResults.success) {
elizaLogger.log("Success:", `https://pump.fun/${mint.toBase58()}`);
const ata = getAssociatedTokenAddressSync(
mint,
seller.publicKey,
allowOffCurve
);
const balance = await connection.getTokenAccountBalance(
ata,
"processed"
);
const amount = balance.value.uiAmount;
if (amount === null) {
elizaLogger.log(
`${seller.publicKey.toBase58()}:`,
"No Account Found"
);
} else {
elizaLogger.log(`${seller.publicKey.toBase58()}:`, amount);
}
} else {
elizaLogger.log("Sell failed");
}
};
// previous logic:
// if (typeof window !== "undefined" && typeof window.confirm === "function") {
// return window.confirm(
// "Confirm the creation and purchase of the token?"
// );
// }
// return true;
const promptConfirmation = async (): Promise<boolean> => {
return true;
};
// Save the base64 data to a file
import * as fs from "fs";
import * as path from "path";
import { getWalletKey } from "../keypairUtils.ts";
const pumpfunTemplate = `Respond with a JSON markdown block containing only the extracted values. Use null for any values that cannot be determined.
Example response:
\`\`\`json
{
"tokenMetadata": {
"name": "Test Token",
"symbol": "TEST",
"description": "A test token",
"image_description": "create an image of a rabbit"
},
"buyAmountSol": "0.00069"
}
\`\`\`
{{recentMessages}}
Given the recent messages, extract or generate (come up with if not included) the following information about the requested token creation:
- Token name
- Token symbol
- Token description
- Token image description
- Amount of SOL to buy
Respond with a JSON markdown block containing only the extracted values.`;
export default {
name: "CREATE_AND_BUY_TOKEN",
similes: ["CREATE_AND_PURCHASE_TOKEN", "DEPLOY_AND_BUY_TOKEN"],
validate: async (_runtime: IAgentRuntime, _message: Memory) => {
return true; //return isCreateAndBuyContent(runtime, message.content);
},
description:
"Create a new token and buy a specified amount using SOL. Requires deployer private key, token metadata, buy amount in SOL, priority fee, and allowOffCurve flag.",
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: State,
_options: { [key: string]: unknown },
callback?: HandlerCallback
): Promise<boolean> => {
elizaLogger.log("Starting CREATE_AND_BUY_TOKEN handler...");
// Compose state if not provided
if (!state) {
state = (await runtime.composeState(message)) as State;
} else {
state = await runtime.updateRecentMessageState(state);
}
// Get wallet info for context
const walletInfo = await walletProvider.get(runtime, message, state);
state.walletInfo = walletInfo;
// Generate structured content from natural language
const pumpContext = composeContext({
state,
template: pumpfunTemplate,
});
const content = await generateObjectDeprecated({
runtime,
context: pumpContext,
modelClass: ModelClass.LARGE,
});
// Validate the generated content
if (!isCreateAndBuyContent(runtime, content)) {
elizaLogger.error(
"Invalid content for CREATE_AND_BUY_TOKEN action."
);
return false;
}
const { tokenMetadata, buyAmountSol } = content;
/*
// 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;
}
} */
const imageResult = await generateImage(
{
prompt: `logo for ${tokenMetadata.name} (${tokenMetadata.symbol}) token - ${tokenMetadata.description}`,
width: 256,
height: 256,
count: 1,
},
runtime
);
tokenMetadata.image_description = imageResult.data[0].replace(
/^data:image\/[a-z]+;base64,/,
""
);
// Convert base64 string to Blob
const base64Data = tokenMetadata.image_description;
const outputPath = path.join(
process.cwd(),
`generated_image_${Date.now()}.txt`
);
fs.writeFileSync(outputPath, base64Data);
elizaLogger.log(`Base64 data saved to: ${outputPath}`);
const byteCharacters = atob(base64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: "image/png" });
// Add the default decimals and convert file to Blob
const fullTokenMetadata: CreateTokenMetadata = {
name: tokenMetadata.name,
symbol: tokenMetadata.symbol,
description: tokenMetadata.description,
file: blob,
};
// Default priority fee for high network load
const priorityFee = {
unitLimit: 100_000_000,
unitPrice: 100_000,
};
const slippage = "2000";
try {
// Get private key from settings and create deployer keypair
const { keypair: deployerKeypair } = await getWalletKey(
runtime,
true
);
// Generate new mint keypair
const mintKeypair = Keypair.generate();
elizaLogger.log(
`Generated mint address: ${mintKeypair.publicKey.toBase58()}`
);
// Setup connection and SDK
const connection = new Connection(settings.SOLANA_RPC_URL!, {
commitment: "confirmed",
confirmTransactionInitialTimeout: 500000, // 120 seconds
wsEndpoint: settings.SOLANA_RPC_URL!.replace("https", "wss"),
});
const wallet = new Wallet(deployerKeypair);
const provider = new AnchorProvider(connection, wallet, {
commitment: "confirmed",
});
const sdk = new PumpFunSDK(provider);
// const slippage = runtime.getSetting("SLIPPAGE");
const createAndBuyConfirmation = await promptConfirmation();
if (!createAndBuyConfirmation) {
elizaLogger.log("Create and buy token canceled by user");
return false;
}
// Convert SOL to lamports (1 SOL = 1_000_000_000 lamports)
const lamports = Math.floor(Number(buyAmountSol) * 1_000_000_000);
elizaLogger.log("Executing create and buy transaction...");
const result = await createAndBuyToken({
deployer: deployerKeypair,
mint: mintKeypair,
tokenMetadata: fullTokenMetadata,
buyAmountSol: BigInt(lamports),
priorityFee,
allowOffCurve: false,
sdk,
connection,
slippage,
});
if (callback) {
if (result.success) {
callback({
text: `Token ${tokenMetadata.name} (${tokenMetadata.symbol}) created successfully!\nContract Address: ${result.ca}\nCreator: ${result.creator}\nView at: https://pump.fun/${result.ca}`,
content: {
tokenInfo: {
symbol: tokenMetadata.symbol,
address: result.ca,
creator: result.creator,
name: tokenMetadata.name,
description: tokenMetadata.description,
timestamp: Date.now(),
},
},
});
} else {
callback({
text: `Failed to create token: ${result.error}\nAttempted mint address: ${result.ca}`,
content: {
error: result.error,
mintAddress: result.ca,
},
});
}
}
//await trustScoreDb.addToken(tokenInfo);
/*
// Update runtime state
await runtime.updateState({
...state,
lastCreatedToken: tokenInfo
});
*/
// Log success message with token view URL
const successMessage = `Token created and purchased successfully! View at: https://pump.fun/${mintKeypair.publicKey.toBase58()}`;
elizaLogger.log(successMessage);
return result.success;
} catch (error) {
if (callback) {
callback({
text: `Error during token creation: ${error.message}`,
content: { error: error.message },
});
}
return false;
}
},
examples: [
[
{
user: "{{user1}}",
content: {
text: "Create a new token called GLITCHIZA with symbol GLITCHIZA and generate a description about it on pump.fun. Also come up with a description for it to use for image generation .buy 0.00069 SOL worth.",
},
},
{
user: "{{user2}}",
content: {
text: "Token GLITCHIZA (GLITCHIZA) created successfully on pump.fun!\nContract Address: 3kD5DN4bbA3nykb1abjS66VF7cYZkKdirX8bZ6ShJjBB\nCreator: 9jW8FPr6BSSsemWPV22UUCzSqkVdTp6HTyPqeqyuBbCa\nView at: https://pump.fun/EugPwuZ8oUMWsYHeBGERWvELfLGFmA1taDtmY8uMeX6r",
action: "CREATE_AND_BUY_TOKEN",
content: {
tokenInfo: {
symbol: "GLITCHIZA",
address:
"EugPwuZ8oUMWsYHeBGERWvELfLGFmA1taDtmY8uMeX6r",
creator:
"9jW8FPr6BSSsemWPV22UUCzSqkVdTp6HTyPqeqyuBbCa",
name: "GLITCHIZA",
description: "A GLITCHIZA token",
},
},
},
},
],
] as ActionExample[][],
} as Action;