Skip to content

Commit

Permalink
add pump.fun-js
Browse files Browse the repository at this point in the history
  • Loading branch information
outsmartchad committed Jul 8, 2024
1 parent b12390b commit 7b126ee
Show file tree
Hide file tree
Showing 27 changed files with 4,156 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/pumpfunsdk-js/pumpdotfun-sdk/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.anchor
.DS_Store
target
**/*.rs.bk
node_modules
test-ledger
.yarn

dist/

.keys*/
.keys*/**

.env
refs/
1 change: 1 addition & 0 deletions src/pumpfunsdk-js/pumpdotfun-sdk/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
example/
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
154 changes: 154 additions & 0 deletions src/pumpfunsdk-js/pumpdotfun-sdk/example/basic/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import dotenv from "dotenv";
import fs from "fs";
import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
import { DEFAULT_DECIMALS, PumpFunSDK } from "../../src";
import NodeWallet from "@coral-xyz/anchor/dist/cjs/nodewallet";
import { AnchorProvider } from "@coral-xyz/anchor";
import {
getOrCreateKeypair,
getSPLBalance,
printSOLBalance,
printSPLBalance,
} from "../util";

const KEYS_FOLDER = __dirname + "/.keys";s
const SLIPPAGE_BASIS_POINTS = 100n;

//create token example:
//https://solscan.io/tx/bok9NgPeoJPtYQHoDqJZyRDmY88tHbPcAk1CJJsKV3XEhHpaTZhUCG3mA9EQNXcaUfNSgfPkuVbEsKMp6H7D9NY
//devnet faucet
//https://faucet.solana.com/

const main = async () => {
dotenv.config();

if (!process.env.HELIUS_RPC_URL) {
console.error("Please set HELIUS_RPC_URL in .env file");
console.error(
"Example: HELIUS_RPC_URL=https://mainnet.helius-rpc.com/?api-key=<your api key>"
);
console.error("Get one at: https://www.helius.dev");
return;
}

let connection = new Connection(process.env.HELIUS_RPC_URL || "");

let wallet = new NodeWallet(new Keypair()); //note this is not used
const provider = new AnchorProvider(connection, wallet, {
commitment: "finalized",
});

const testAccount = getOrCreateKeypair(KEYS_FOLDER, "test-account");
const mint = getOrCreateKeypair(KEYS_FOLDER, "mint");

await printSOLBalance(
connection,
testAccount.publicKey,
"Test Account keypair"
);

let sdk = new PumpFunSDK(provider);

let globalAccount = await sdk.getGlobalAccount();
console.log(globalAccount);

let currentSolBalance = await connection.getBalance(testAccount.publicKey);
if (currentSolBalance == 0) {
console.log(
"Please send some SOL to the test-account:",
testAccount.publicKey.toBase58()
);
return;
}

console.log(await sdk.getGlobalAccount());

//Check if mint already exists
let boundingCurveAccount = await sdk.getBondingCurveAccount(mint.publicKey);
if (!boundingCurveAccount) {
let tokenMetadata = {
name: "TST-7",
symbol: "TST-7",
description: "TST-7: This is a test token",
file: await fs.openAsBlob("example/basic/random.png"),
};

let createResults = await sdk.createAndBuy(
testAccount,
mint,
tokenMetadata,
BigInt(0.0001 * LAMPORTS_PER_SOL),
SLIPPAGE_BASIS_POINTS,
{
unitLimit: 250000,
unitPrice: 250000,
},
);

if (createResults.success) {
console.log("Success:", `https://pump.fun/${mint.publicKey.toBase58()}`);
boundingCurveAccount = await sdk.getBondingCurveAccount(mint.publicKey);
console.log("Bonding curve after create and buy", boundingCurveAccount);
printSPLBalance(connection, mint.publicKey, testAccount.publicKey);
}
} else {
console.log("boundingCurveAccount", boundingCurveAccount);
console.log("Success:", `https://pump.fun/${mint.publicKey.toBase58()}`);
printSPLBalance(connection, mint.publicKey, testAccount.publicKey);
}

if (boundingCurveAccount) {
//buy 0.0001 SOL worth of tokens
let buyResults = await sdk.buy(
testAccount,
mint.publicKey,
BigInt(0.0001 * LAMPORTS_PER_SOL),
SLIPPAGE_BASIS_POINTS,
{
unitLimit: 250000,
unitPrice: 250000,
},
);

if (buyResults.success) {
printSPLBalance(connection, mint.publicKey, testAccount.publicKey);
console.log("Bonding curve after buy", await sdk.getBondingCurveAccount(mint.publicKey));
} else {
console.log("Buy failed");
}

//sell all tokens
let currentSPLBalance = await getSPLBalance(
connection,
mint.publicKey,
testAccount.publicKey
);
console.log("currentSPLBalance", currentSPLBalance);
if (currentSPLBalance) {
let sellResults = await sdk.sell(
testAccount,
mint.publicKey,
BigInt(currentSPLBalance * Math.pow(10, DEFAULT_DECIMALS)),
SLIPPAGE_BASIS_POINTS,
{
unitLimit: 250000,
unitPrice: 250000,
},
);
if (sellResults.success) {
await printSOLBalance(
connection,
testAccount.publicKey,
"Test Account keypair"
);

printSPLBalance(connection, mint.publicKey, testAccount.publicKey, "After SPL sell all");
console.log("Bonding curve after sell", await sdk.getBondingCurveAccount(mint.publicKey));
} else {
console.log("Sell failed");
}
}
}
};

main();
44 changes: 44 additions & 0 deletions src/pumpfunsdk-js/pumpdotfun-sdk/example/events/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import dotenv from "dotenv";
import { Connection, Keypair } from "@solana/web3.js";
import { PumpFunSDK } from "../../src";
import NodeWallet from "@coral-xyz/anchor/dist/cjs/nodewallet";
import { AnchorProvider } from "@coral-xyz/anchor";

const main = async () => {
dotenv.config();

if (!process.env.HELIUS_RPC_URL) {
console.error("Please set HELIUS_RPC_URL in .env file");
console.error(
"Example: HELIUS_RPC_URL=https://mainnet.helius-rpc.com/?api-key=<your api key>"
);
console.error("Get one at: https://www.helius.dev");
return;
}

let connection = new Connection(process.env.HELIUS_RPC_URL || "");

let wallet = new NodeWallet(new Keypair()); //note this is not used
const provider = new AnchorProvider(connection, wallet, {
commitment: "finalized",
});

let sdk = new PumpFunSDK(provider);

let createEvent = sdk.addEventListener("createEvent", (event) => {
console.log("createEvent", event);
});
console.log("createEvent", createEvent);

let tradeEvent = sdk.addEventListener("tradeEvent", (event) => {
console.log("tradeEvent", event);
});
console.log("tradeEvent", tradeEvent);

let completeEvent = sdk.addEventListener("completeEvent", (event) => {
console.log("completeEvent", event);
});
console.log("completeEvent", completeEvent);
};

main();
110 changes: 110 additions & 0 deletions src/pumpfunsdk-js/pumpdotfun-sdk/example/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
const { bs58 } =require ("@coral-xyz/anchor/dist/cjs/utils/bytes");
const { getAssociatedTokenAddressSync } =require ("@solana/spl-token");
const {
Keypair,
PublicKey,
Connection,
LAMPORTS_PER_SOL,
} =require ("@solana/web3.js");
const { sha256 } =require ("js-sha256");

const fs =require ("fs");

function getOrCreateKeypair(dir, keyName) {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const authorityKey = dir + "/" + keyName + ".json";
if (fs.existsSync(authorityKey)) {
const data= JSON.parse(fs.readFileSync(authorityKey, "utf-8"));
return Keypair.fromSecretKey(bs58.decode(data.secretKey));
} else {
const keypair = Keypair.generate();
keypair.secretKey;
fs.writeFileSync(
authorityKey,
JSON.stringify({
secretKey: bs58.encode(keypair.secretKey),
publicKey: keypair.publicKey.toBase58(),
})
);
return keypair;
}
}

function getKeypairByJsonPath(jsonPath) {
try {
const keypairJson = fs.readFileSync(jsonPath, "utf-8");
const data = JSON.parse(keypairJson);
const mintKeypair = Keypair.fromSecretKey(Uint8Array.from(data));
return mintKeypair
} catch (e) {
console.log(e);
}
}

async function printSOLBalance (
connection,
pubKey,
info = ""
) {
const balance = await connection.getBalance(pubKey);
console.log(
`${info ? info + " " : ""}${pubKey.toBase58()}:`,
balance / LAMPORTS_PER_SOL,
`SOL`
);
};

async function getSPLBalance (
connection,
mintAddress,
pubKey,
allowOffCurve = false
) {
try {
let ata = getAssociatedTokenAddressSync(mintAddress, pubKey, allowOffCurve);
const balance = await connection.getTokenAccountBalance(ata, "processed");
return balance.value.uiAmount;
} catch (e) {}
return null;
};

async function printSPLBalance (
connection,
mintAddress,
user,
info = ""
) {
const balance = await getSPLBalance(connection, mintAddress, user);
if (balance === null) {
console.log(
`${info ? info + " " : ""}${user.toBase58()}:`,
"No Account Found"
);
} else {
console.log(`${info ? info + " " : ""}${user.toBase58()}:`, balance);
}
};

const baseToValue = (base, decimals) => {
return base * Math.pow(10, decimals);
};

const valueToBase = (value, decimal) => {
return value / Math.pow(10, decimals);
};

//i.e. account:BondingCurve
function getDiscriminator(name) {
return sha256.digest(name).slice(0, 8);
}

module.exports = {
getOrCreateKeypair,
getKeypairByJsonPath,
printSOLBalance,
getSPLBalance,
printSPLBalance,
baseToValue,
valueToBase,
getDiscriminator,
};
Binary file added src/pumpfunsdk-js/pumpdotfun-sdk/images/999.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
49 changes: 49 additions & 0 deletions src/pumpfunsdk-js/pumpdotfun-sdk/pump-events-listener/listeners.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const {connection} = require("../../../helpers/config");

import { Keypair, Connection } from "@solana/web3.js";
import {PumpFunSDK} from "pumpdotfun-sdk";
import NodeWallet from "@coral-xyz/anchor/dist/cjs/nodewallet";
import { AnchorProvider } from "@coral-xyz/anchor";

const getProvider =()=>{
const wallet = new NodeWallet(Keypair.generate());
const provider = new AnchorProvider(connection, wallet, {
commitment: "finalized",
});
return provider;
}

export const subscribeToCompleteBondingCurveEvent = async (sdk) => {
const completeEventId = sdk.addEventListener("completeEvent", (event, slot, signature) => {
console.log("completeEvent", event, slot, signature);
});
console.log("Subscribed to completeEvent with ID:", completeEventId);
}
export const subscribeToCreatePumpTokenEvent = async (sdk) => {
const createEventId = sdk.addEventListener("createEvent", (event, slot, signature) => {
console.log("createEvent", event, slot, signature);
console.log("mint pubkey", event.mint.toBase58())
});
console.log("Subscribed to createEvent with ID:", createEventId);
}
export const subscribeToTradeEvent = async (sdk) => {
const tradeEventId = sdk.addEventListener("tradeEvent", (event, slot, signature) => {
console.log("tradeEvent", event, slot, signature);
});
console.log("Subscribed to tradeEvent with ID:", tradeEventId);
}

const main = async () => {
try {
const provider = getProvider();
const sdk = new PumpFunSDK(provider);

// Set up event listeners
await subscribeToCreatePumpTokenEvent(sdk);
} catch (error) {
console.error("An error occurred:", error);
}
};



4 changes: 4 additions & 0 deletions src/pumpfunsdk-js/pumpdotfun-sdk/src/IDL/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// pump-fun.json should be a valid JSON file
const IDL = require("./pump-fun.json");
const { PumpFun } = require("./pump-fun");
module.exports = { PumpFun, IDL };
Loading

0 comments on commit 7b126ee

Please sign in to comment.