1.3.0 • Published 4 months ago

bet-test-sdk v1.3.0

Weekly downloads
-
License
ISC
Repository
github
Last release
4 months ago

BetSDK README

Important

Never click any links in this repository or its issues that lead you away from GitHub. Do not run any code that others post without reading and understanding it first. This software is provided "as is" without warranty.

Overview

The BetSDK is designed to interact with the bet.com decentralized application. It provides methods for creating, buying, and selling tokens on the Solana blockchain. The SDK manages the necessary transactions and interactions with the bet.com program.

Installation

npm i bet-test-sdk

Notice (for front-end developers)

If you encounter an error regarding the crypto module when building a front-end project with frameworks such as React, Vue, or Next.js, consider installing a polyfill (for example, the node-polyfills plugin) or adding a crypto-browserify alias to your build configuration.

For example:

import { nodePolyfills } from 'vite-plugin-node-polyfills'

plugins: [
    nodePolyfills({
       include: ['crypto'],
    }),
],

OR

resolve: {
    alias: {
      crypto: 'crypto-browserify',
    }
},

BetSDK transaction

Get BetSDK transaction-related methods.

getCreateAndBuyInstructions

type CreateTokenMetadata = {
  name: string;
  symbol: string;
  description: string;
  migrateDex: MigrateDex;
  file: Blob;
  createdOn?: string;
  twitter?: string;
  telegram?: string;
  discord?: string;
  website?: string;
}

async getCreateAndBuyInstructions(
    creator: PublicKey,
    createTokenMetadata: CreateTokenMetadata,
    buyAmountSol: bigint,
    slippageBasisPoints: bigint = 500n,
    commitment: Commitment = DEFAULT_COMMITMENT
): Promise<{
    newTx: Transaction;
    mintKeyPair: Keypair; // `mintKeyPair`: A Keypair to create a mint. This keypair needs to be used as a signer to sign the transaction.
}>
  • CreateTokenMetadata:

    • name: Token name.
    • symbol: Token symbol.
    • description: Token description.
    • migrateDex: After completing the bet curve, the decentralized exchange (DEX) you wish to migrate to currently supports only Raydium and Meteora. The MigrateType can be imported from the SDK.
    • file: Token logo file
    • createdOn: Specifies the platform on which the token was created.
    • twitter: X link
    • telegram: Telegram link
    • discord: Discord link
    • website: website
  • Creates a new token and buys it.

  • Parameters:
    • creator: The public key of the token creator.
    • createTokenMetadata: Metadata for the token. (For the createTokenMetadata object, the migrateType property specifies that after completing the bet curve, the DEX you wish to migrate to currently supports only Raydium and Meteora. The MigrateType can be imported from the SDK.)
    • buyAmountSol: Amount of SOL to buy.
    • slippageBasisPoints: Slippage in basis points (default: 500).
    • commitment: Commitment level (default: DEFAULT_COMMITMENT).
  • Returns: A promise that resolves to { newTx: Transaction; mintKeyPair: Keypair; }.

getBuyInstructionsBySolAmount

async getBuyInstructionsBySolAmount(
    buyer: PublicKey,
    mint: PublicKey,
    buyAmountSol: bigint,
    slippageBasisPoints: bigint = 500n,
    commitment: Commitment = DEFAULT_COMMITMENT
): Promise<Transaction>
  • Buys a specified amount of tokens by sol input.
  • Parameters:
    • buyer: The public key of the buyer.
    • mint: The public key of the mint account.
    • buyAmountSol: Amount of SOL to buy.
    • slippageBasisPoints: Slippage in basis points (default: 500).
    • commitment: Commitment level (default: DEFAULT_COMMITMENT).
  • Returns: A promise that resolves to a Transaction.

getBuyInstructionsByTokenAmount

async getBuyInstructionsByTokenAmount(
    buyer: PublicKey,
    mint: PublicKey,
    buyAmountToken: bigint,
    slippageBasisPoints: bigint = 500n,
    commitment: Commitment = DEFAULT_COMMITMENT
): Promise<Transaction>
  • Buys a specified amount of tokens by token input.
  • Parameters:
    • buyer: The public key of the buyer.
    • mint: The public key of the mint account.
    • buyAmountToken: Amount of token to buy.
    • slippageBasisPoints: Slippage in basis points (default: 500).
    • commitment: Commitment level (default: DEFAULT_COMMITMENT).
  • Returns: A promise that resolves to a Transaction.

getSellInstructionsByTokenAmount

async getSellInstructionsByTokenAmount(
    seller: PublicKey,
    mint: PublicKey,
    sellTokenAmount: bigint,
    slippageBasisPoints: bigint = 500n,
): Promise<Transaction> 
  • Sells a specified amount of tokens.
  • Parameters:
    • seller: The public key of the seller.
    • mint: The public key of the mint account.
    • sellTokenAmount: Amount of tokens to sell.
    • slippageBasisPoints: Slippage in basis points (default: 500)
  • Returns: A promise that resolves to a Transaction.

getSellInstructionsBySolAmount

async getSellInstructionsBySolAmount(
    seller: PublicKey,
    mint: PublicKey,
    solAmountOut: bigint,
    slippageBasisPoints: bigint = 500n,
): Promise<Transaction> 
  • Sells a specified amount of tokens.
  • Parameters:
    • seller: The public key of the seller.
    • mint: The public key of the mint account.
    • solAmountOut: Amount of sol to sell.
    • slippageBasisPoints: Slippage in basis points (default: 500)
  • Returns: A promise that resolves to a Transaction.

Some preview methods for calculations

// Buy: Fixed sol amount in, estimated token amount out
async getTokenAmountOut(
  mint: PublicKey,
  solAmountIn: bigint,
  slippageBasisPoints?: bigint
): Promise<bigint>

// Buy: Fixed token amount out, estimated sol amount in
async getMinSolAmountIn(
  mint: PublicKey,
  tokenAmountOut: bigint,
  slippageBasisPoints?: bigint
): Promise<bigint>

// Sell: Fixed token amount in, estimated sol amount out
async getSolAmountOut(
  mint: PublicKey,
  tokenAmountIn: bigint,
  slippageBasisPoints?: bigint
): Promise<bigint>

// Sell: Fixed sol amount out, estimated token amount in
async getMinTokenAmountIn(
  mint: PublicKey,
  solAmountOut: bigint,
  slippageBasisPoints?: bigint
): Promise<bigint>

// Get mint's curve state progress
async curveStateProgress(mint: PublicKey): Promise<number>

Usage Example

First, create a .env file and set your RPC URL as shown in the .env.example file.

Then, run the command below to generate a new account, and fund this account with at least 0.004 SOL.

npx ts-node example/basic/index.ts

import dotenv from "dotenv";
import fs from "fs";
import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
import { DEFAULT_DECIMALS, BetSDK } from "bet-test-sdk";
import NodeWallet from "@coral-xyz/anchor/dist/cjs/nodewallet";
import { AnchorProvider } from "@coral-xyz/anchor";
import {
  getOrCreateKeypair,
  getSPLBalance,
  printSOLBalance,
  printSPLBalance,
} from "./util";

dotenv.config();

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

const getProvider = () => {
  if (!process.env.SOLANA_RPC_URL) {
    throw new Error("Please set SOLANA_RPC_URL in .env file");
  }

  const connection = new Connection(process.env.SOLANA_RPC_URL || "");
  const wallet = new NodeWallet(new Keypair());
  return new AnchorProvider(connection, wallet, { commitment: "finalized" });
};

const createAndBuyToken = async (sdk, testAccount) => {
  const tokenMetadata = {
    name: "TST-B",
    symbol: "TST-B",
    description: "TST-B: A test token",
    file: await fs.openAsBlob("example/basic/test.jpg"),
    migrateDex: MigrateDex.Meteora,
    twitter: "https://example.x.com",
    createdOn: "https://test.bet.com",
    telegram: "https://example.t.me",
    discord: "https://example.discord.com",
    website: "https://www.example.com",
  };

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

  if (createResults.success) {
    console.log(createResults);
  } else {
    console.log("Create and Buy failed");
  }
};

const buyTokensWithSolAmount = async (sdk, testAccount, mint) => {
  const curveStateAccount = await sdk.getCurveStateAccount(mint)
  if (curveStateAccount) {
    console.log(
      "mint does not exist",
      mint.toBase58()
    );
    return;
  }
  const buyResults = await sdk.buyWithSolAmount(
    testAccount,
    mint,
    BigInt(0.001 * LAMPORTS_PER_SOL),
    SLIPPAGE_BASIS_POINTS,
    {
      unitLimit: 500000,
      unitPrice: 250000,
    },
  );

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

const buyTokensWithTokenAmount = async (sdk, testAccount, mint) => {
  const curveStateAccount = await sdk.getCurveStateAccount(mint)
  if (curveStateAccount) {
    console.log(
      "mint does not exist",
      mint.toBase58()
    );
    return;
  }
  const buyResults = await sdk.buyWithTokenAmount(
    testAccount,
    mint,
    BigInt(10000 * Math.pow(10, DEFAULT_DECIMALS)),
    SLIPPAGE_BASIS_POINTS,
    {
      unitLimit: 500000,
      unitPrice: 250000,
    },
  );

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

const sellTokensWithTokenAmount = async (sdk, testAccount, mint) => {
  const currentSPLBalance = await getSPLBalance(
    sdk.connection,
    mint,
    testAccount.publicKey
  );
  console.log("currentSPLBalance", currentSPLBalance);

  if (currentSPLBalance) {
    const sellResults = await sdk.sellWithTokenAmount(
      testAccount,
      mint,
      BigInt(currentSPLBalance * Math.pow(10, DEFAULT_DECIMALS)),
      SLIPPAGE_BASIS_POINTS,
      {
        unitLimit: 500000,
        unitPrice: 250000,
      }
    );

    if (sellResults.success) {
      await printSOLBalance(sdk.connection, testAccount.publicKey, "Test Account keypair");
      printSPLBalance(sdk.connection, mint, testAccount.publicKey, "After SPL sell all");
      console.log("Bet curve after sell", await sdk.getCurveStateAccount(mint));
    } else {
      console.log("Sell failed");
    }
  }
};

const sellTokensWithSolAmount = async (sdk, testAccount, mint) => {
  const currentSPLBalance = await getSPLBalance(
    sdk.connection,
    mint,
    testAccount.publicKey
  );
  console.log("currentSPLBalance", currentSPLBalance);

  if (currentSPLBalance) {
    const sellResults = await sdk.sellWithSolAmount(
      testAccount,
      mint,
      BigInt(0.001 * LAMPORTS_PER_SOL),
      SLIPPAGE_BASIS_POINTS,
      {
        unitLimit: 500000,
        unitPrice: 250000,
      }
    );

    if (sellResults.success) {
      await printSOLBalance(sdk.connection, testAccount.publicKey, "Test Account keypair");
      printSPLBalance(sdk.connection, mint, testAccount.publicKey, "After SPL sell all");
      console.log("Bet curve after sell", await sdk.getCurveStateAccount(mint));
    } else {
      console.log("Sell failed");
    }
  }
};

const main = async () => {
  try {
    const provider = getProvider();
    const sdk = new BetSDK(provider);
    const connection = provider.connection;

    const testAccount = getOrCreateKeypair(KEYS_FOLDER, "test-account");
    const mint = "SOLANA MINT IN BET";

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

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

    let curveStateAccount = await sdk.getCurveStateAccount(mint);

    if (!curveStateAccount) {
      await createAndBuyToken(sdk, testAccount, mint);
      curveStateAccount = await sdk.getCurveStateAccount(mint);
    }

    if (curveStateAccount) {
      await buyTokensWithSolAmount(sdk, testAccount, mint);
      await sellTokensWithTokenAmount(sdk, testAccount, mint);
    }
  } catch (error) {
    console.error("An error occurred:", error);
  }
};

main();

BetSDK Class

The BetSDK class provides methods for interacting with the Bet protocol. Below are the method signatures and descriptions.

createAndBuy

async createAndBuy(
  creator: Keypair,
  createTokenMetadata: CreateTokenMetadata,
  buyAmountSol: bigint,
  slippageBasisPoints: bigint = 500n,
  priorityFees?: PriorityFee,
  commitment: Commitment = DEFAULT_COMMITMENT,
  finality: Finality = DEFAULT_FINALITY
): Promise<TransactionResult>
  • Creates a new token and buys it.
  • Parameters:
    • creator: The keypair of the token creator.
    • createTokenMetadata: Metadata for the token.
    • buyAmountSol: Amount of SOL to buy.
    • slippageBasisPoints: Slippage in basis points (default: 500).
    • priorityFees: Priority fees (optional).
    • commitment: Commitment level (default: DEFAULT_COMMITMENT).
    • finality: Finality level (default: DEFAULT_FINALITY).
  • Returns: A promise that resolves to a TransactionResult.

buyWithSolAmount

async buyWithSolAmount(
  buyer: Keypair,
  mint: PublicKey,
  buyAmountSol: bigint,
  slippageBasisPoints: bigint = 500n,
  priorityFees?: PriorityFee,
  commitment: Commitment = DEFAULT_COMMITMENT,
  finality: Finality = DEFAULT_FINALITY
): Promise<TransactionResult>
  • Buys a specified amount of tokens.
  • Parameters:
    • buyer: The keypair of the buyer.
    • mint: The public key of the mint account.
    • buyAmountSol: Amount of SOL to buy.
    • slippageBasisPoints: Slippage in basis points (default: 500).
    • priorityFees: Priority fees (optional).
    • commitment: Commitment level (default: DEFAULT_COMMITMENT).
    • finality: Finality level (default: DEFAULT_FINALITY).
  • Returns: A promise that resolves to a TransactionResult.

buyWithTokenAmount

async buyWithTokenAmount(
  buyer: Keypair,
  mint: PublicKey,
  buyAmountToken: bigint,
  slippageBasisPoints: bigint = 500n,
  priorityFees?: PriorityFee,
  commitment: Commitment = DEFAULT_COMMITMENT,
  finality: Finality = DEFAULT_FINALITY
): Promise<TransactionResult>
  • Buys a specified amount of sols.
  • Parameters:
    • buyer: The keypair of the buyer.
    • mint: The public key of the mint account.
    • buyAmountToken: Amount of token to buy.
    • slippageBasisPoints: Slippage in basis points (default: 500).
    • priorityFees: Priority fees (optional).
    • commitment: Commitment level (default: DEFAULT_COMMITMENT).
    • finality: Finality level (default: DEFAULT_FINALITY).
  • Returns: A promise that resolves to a TransactionResult.

sellWithTokenAmount

async sellWithTokenAmount(
  seller: Keypair,
  mint: PublicKey,
  sellTokenAmount: bigint,
  slippageBasisPoints: bigint = 500n,
  priorityFees?: PriorityFee,
  commitment: Commitment = DEFAULT_COMMITMENT,
  finality: Finality = DEFAULT_FINALITY
): Promise<TransactionResult>
  • Sells a specified amount of tokens.
  • Parameters:
    • seller: The keypair of the seller.
    • mint: The public key of the mint account.
    • sellTokenAmount: Amount of tokens to sell.
    • slippageBasisPoints: Slippage in basis points (default: 500).
    • priorityFees: Priority fees (optional).
    • commitment: Commitment level (default: DEFAULT_COMMITMENT).
    • finality: Finality level (default: DEFAULT_FINALITY).
  • Returns: A promise that resolves to a TransactionResult.

sellWithSolAmount

async sellWithSolAmount(
  seller: Keypair,
  mint: PublicKey,
  sellSolAmount: bigint,
  slippageBasisPoints: bigint = 500n,
  priorityFees?: PriorityFee,
  commitment: Commitment = DEFAULT_COMMITMENT,
  finality: Finality = DEFAULT_FINALITY
): Promise<TransactionResult>
  • Sells a specified amount of tokens.
  • Parameters:
    • seller: The keypair of the seller.
    • mint: The public key of the mint account.
    • sellSolAmount: Amount of sols to sell.
    • slippageBasisPoints: Slippage in basis points (default: 500).
    • priorityFees: Priority fees (optional).
    • commitment: Commitment level (default: DEFAULT_COMMITMENT).
    • finality: Finality level (default: DEFAULT_FINALITY).
  • Returns: A promise that resolves to a TransactionResult.

addEventListener

addEventListener<T extends BetEventType>(
  eventType: T,
  callback: (event: BetEventHandlers[T], slot: number, signature: string) => void
): number
  • Adds an event listener for the specified event type.
  • Parameters:
    • eventType: The type of event to listen for.
    • callback: The callback function to execute when the event occurs.
  • Returns: An identifier for the event listener.

removeEventListener

removeEventListener(eventId: number): void
  • Removes the event listener with the specified identifier.
  • Parameters:
    • eventId: The identifier of the event listener to remove.

Running the Examples

Basic Example

To run the basic example for creating, buying, and selling tokens, use the following command:

npx ts-node example/basic/index.ts

Event Subscription Example

This example demonstrates how to set up event subscriptions using the Bet SDK.

Script: example/events/events.ts

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

dotenv.config();

const getProvider = () => {
  if (!process.env.SOLANA_RPC_URL) {
    throw new Error("Please set SOLANA_RPC_URL in .env file");
  }

  const connection = new Connection(process.env.SOLANA_RPC_URL || "");
  const wallet = new NodeWallet(new Keypair());
  return new AnchorProvider(connection, wallet, { commitment: "finalized" });
};

const setupEventListeners = async (sdk) => {
  const createEventId = sdk.addEventListener("createEvent", (event, slot, signature) => {
    console.log("createEvent", event, slot, signature);
  });
  console.log("Subscribed to createEvent with ID:", createEventId);

  const buyEventId = sdk.addEventListener("buyEvent", (event, slot, signature) => {
    console.log("buyEvent", event, slot, signature);
  });
  console.log("Subscribed to buyEvent with ID:", buyEventId);

  const sellEventId = sdk.addEventListener("sellEvent", (event, slot, signature) => {
    console.log("sellEvent", event, slot, signature);
  });
  console.log("Subscribed to sellEvent with ID:", sellEventId);

  const completeEventId = sdk.addEventListener("completeEvent", (event, slot, signature) => {
    console.log("completeEvent", event, slot, signature);
  });
  console.log("Subscribed to completeEvent with ID:", completeEventId);
};

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

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

main();

Running the Event Subscription Example

To run the event subscription example, use the following command:

npx ts-node example/events/events.ts

Disclaimer

This software is provided "as is" without any warranty, express or implied, including, but not limited to, the warranties of merchantability, fitness for a particular purpose, and noninfringement. In no event shall the authors or copyright holders be liable for any claims, damages, or other liabilities, whether arising from a contract, tort, or any other legal theory in connection with the software or its use.

Use at your own risk. The authors take no responsibility for any harm or damage caused by the use of this software. Users are responsible for ensuring the suitability and safety of this software for their specific use cases.

By using this software, you acknowledge that you have read, understood, and agree to this disclaimer.


Feel free to customize it further to suit the specific context and requirements of your project.


By following this README, you should be able to install the Bet SDK, run the provided examples, and understand how to set up event listeners and perform token operations.

1.2.8

4 months ago

1.2.7

4 months ago

1.2.6

4 months ago

1.2.5

4 months ago

1.2.4

4 months ago

1.2.3

4 months ago

1.2.2

4 months ago

1.3.0

4 months ago

1.2.1

4 months ago

1.2.9

4 months ago

1.2.0

4 months ago

1.1.1

5 months ago

1.1.9

4 months ago

1.1.8

4 months ago

1.1.7

4 months ago

1.1.6

5 months ago

1.1.5

5 months ago

1.1.4

5 months ago

1.1.3

5 months ago

1.1.2

5 months ago

1.1.0

5 months ago

1.0.9

5 months ago

1.0.8

5 months ago

1.0.7

5 months ago

1.0.6

5 months ago

1.0.5

5 months ago

1.0.4

5 months ago

1.0.3

5 months ago

1.0.2

5 months ago

1.0.1

5 months ago

1.0.0

5 months ago