1

Hi brand new to this and trying to teach myself so I apologize for any dumb questions.

I am trying to build a javascript that automates purchases on the solana network. For my test, I am trying to buy .1 worth of an spl token using sol, wait for confirmation, wait for transaction to finalize without timing out, pull spl token balance after transfer, and put the token balance in the next quoteresponse to sell.

I have done all of this and even converted the spl balance to an integer based on decimals, but i keep getting an error.

I know it is due to the variable, because when I replace the variable with the SPL token balance output, it sells correctly.

Is there a way to do this?

// Get public key key and mint coin address
PublicKey('FwryFeyEYNz7YgKo2ujU4dUewx2NHD3K8UBJTMADqbDZ'); // Your wallet's public key
const mintAddress = new PublicKey('6wFdiXQhczmKwwdwEaizs3P144ErdzE7Ena4VYD3m5CE'); // SPL Token's mint address

// Function to get SPL Token balance
async function getSPLTokenBalance(connection, walletPublicKey, mintAddress) {
    try {
        const tokenAccountAddress = await getAssociatedTokenAddress(mintAddress, walletPublicKey);
        const balanceResult = await connection.getTokenAccountBalance(tokenAccountAddress);
        let balanceInTokens = balanceResult.value.uiAmount;

        // Convert to integer to avoid floating point precision issues
        let balanceAsInt = Math.floor(balanceInTokens);

        // Zero out the last 9 digits
        balanceAsInt = balanceAsInt * 1e9;

        console.log(`Scaled SPL Token balance: ${balanceAsInt}`);
        return balanceAsInt; // Balance in tokens with the last 9 digits as zeros
    } catch (error) {
        console.error('Error in getSPLTokenBalance:', error);
        return 0;
    }
}

// Calling the getSPLTokenBalance function properly
(async () => {
    try {
        await getSPLTokenBalance(connection, walletPublicKey, mintAddress);
    } catch (error) {
        console.error('Error while getting SPL Token balance:', error);
    }
})();

// Replace the hardcoded private key with a secure method of handling private keys
const privateKey = 'Hardcoded cause i'm learning but this part works';
const wallet = new Wallet(Keypair.fromSecretKey(bs58.decode(privateKey)));

// Swapping SOL to SPL with 5.0% slippage
const quoteResponse = await (
    await fetch('https://quote-api.jup.ag/v6/quote?inputMint=6wFdiXQhczmKwwdwEaizs3P144ErdzE7Ena4VYD3m5CE\outputMint=So11111111111111111111111111111111111111112\amount=`&{balanceAsInt}`\slippageBps=500'
    )
).json();

The '${balanceAsInt} is in backticks, idk why its not showing

3
  • Hey you may want to remove your quicknode rpc address and could you please format all the code correctly? I dont quite get the uiAmount to int thing. Can you not just use amount?
    – Jonas H.
    Jan 31 at 19:58
  • okay! i removed the rpc, thanks for looking out. Trying to fix formatting now, learning as I go Jan 31 at 20:27
  • I tried my best to fix it, i got everything but the top part formatted but those are just variables and that part of the code is working well. For why I am chanign amount, from my understanding I need to use the balance and add 0's at the end to reflect the mint coin decimals. When I run the code its giving me the correct balance of tokens with the correct amount of 0's. I am open to anything, any suggestions? Jan 31 at 20:35

1 Answer 1

1

Im pretty sure you want to use the amount instead of your ui amount calculation. Your calculations cuts off precission of the number.

If you run the following code for example you will see that the amount should be 5123456789 but with your calculations it rounds down to 5000000000.

Amount: 5123456789
Scaled SPL Token balance: 5000000000

Here to test code:

import { getKeypairFromFile } from "@solana-developers/helpers";
import { TOKEN_2022_PROGRAM_ID, burn, createAccount, createMint, getAssociatedTokenAddress, getOrCreateAssociatedTokenAccount, mintTo } from "@solana/spl-token";
import { Connection, Keypair } from "@solana/web3.js";


let connection = new Connection("http://127.0.0.1:8899", "confirmed");

const keyPair = await getKeypairFromFile();

const mintkeyPair = Keypair.generate();

console.log(keyPair.publicKey.toString());
console.log(mintkeyPair.publicKey.toString());

let confirmOptions = {
    preflightCommitment: "confirmed",
    commitment: "confirmed",
};

const mint = await createMint(
    connection,
    keyPair,
    keyPair.publicKey,
    keyPair.publicKey,
    9,
    mintkeyPair,
    confirmOptions,
    TOKEN_2022_PROGRAM_ID,
    );

console.log("mint", mint);

const tokenAccount = await createAccount(
    connection, 
    keyPair, 
    mintkeyPair.publicKey, 
    keyPair.publicKey, 
    undefined, 
    confirmOptions, 
    TOKEN_2022_PROGRAM_ID);

    console.log("tokenAccount", tokenAccount);

    const assotiatedTokenAccount = await getAssociatedTokenAddress
    (
        mintkeyPair.publicKey, 
        keyPair.publicKey,
        false,
        TOKEN_2022_PROGRAM_ID
    );        

    console.log("assotiatedTokenAccount", assotiatedTokenAccount);

const sig = await mintTo(
    connection,
    keyPair,
    mintkeyPair.publicKey,
    tokenAccount,
    keyPair.publicKey,
    5123456789,
    undefined,
    undefined,
    TOKEN_2022_PROGRAM_ID
);

console.log("sig", sig);

const balanceResult = await connection.getTokenAccountBalance(tokenAccount);
let balanceInTokens = balanceResult.value.uiAmount;

// Convert to integer to avoid floating point precision issues
let balanceAsInt = Math.floor(balanceInTokens);

// Zero out the last 9 digits
balanceAsInt = balanceAsInt * 1e9;

let amount = balanceResult.value.amount;
console.log(`Amount: ${amount}`);
console.log(`Scaled SPL Token balance: ${balanceAsInt}`);
1
  • thank you!! I will dive in and use this. Thank you for taking time to answer my question I really appreciate it a lot Jan 31 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.