Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to create the pool #362

Open
Mutharasuait opened this issue Mar 12, 2025 · 0 comments
Open

Unable to create the pool #362

Mutharasuait opened this issue Mar 12, 2025 · 0 comments

Comments

@Mutharasuait
Copy link

I cloned a repository to my local machine and deployed the Token Swap program on the Solana devnet, which generated an IDL file. I connected this to a Node.js program using the IDL and program ID. Calling the 'createAMM' function works fine, but calling the 'createPool' function returns some errors. I’ve attached the error details and code below.

Error: Failed to create Pool: SimulateError at AnchorProvider.simulate (C:\BLOCKCHAIN\solana\node_modules\@project-serum\anchor\dist\cjs\provider.js:181:19) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async MethodsBuilder.simulate [as _simulateFn] (C:\BLOCKCHAIN\solana\node_modules\@project-serum\anchor\dist\cjs\program\namespace\simulate.js:17:24) at async createPool (C:\BLOCKCHAIN\solana\pool.js:182:27) at async C:\BLOCKCHAIN\solana\pool.js:207:9 { simulationResponse: { accounts: null, err: { InstructionError: [Array] }, innerInstructions: null, logs: [ 'Program ComputeBudget111111111111111111111111111111 invoke [1]', 'Program ComputeBudget111111111111111111111111111111 success', 'Program ComputeBudget111111111111111111111111111111 invoke [1]', 'Program ComputeBudget111111111111111111111111111111 success', 'Program H74BkJ2MGWf93BtZ3ya5AKToLWTi66GPMdMYU5Ssvbpx invoke [1]', 'Program log: Instruction: CreatePool', 'Program H74BkJ2MGWf93BtZ3ya5AKToLWTi66GPMdMYU5Ssvbpx consumed 12859 of 499700 compute units', 'Program H74BkJ2MGWf93BtZ3ya5AKToLWTi66GPMdMYU5Ssvbpx failed: Access violation in stack frame 5 at address 0x200005ff8 of size 8' ], replacementBlockhash: null, returnData: null, unitsConsumed: 500000 } } Main execution failed: SimulateError at AnchorProvider.simulate (C:\BLOCKCHAIN\solana\node_modules\@project-serum\anchor\dist\cjs\provider.js:181:19) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async MethodsBuilder.simulate [as _simulateFn] (C:\BLOCKCHAIN\solana\node_modules\@project-serum\anchor\dist\cjs\program\namespace\simulate.js:17:24) at async createPool (C:\BLOCKCHAIN\solana\pool.js:182:27) at async C:\BLOCKCHAIN\solana\pool.js:207:9 { simulationResponse: { accounts: null, err: { InstructionError: [Array] }, innerInstructions: null, logs: [ 'Program ComputeBudget111111111111111111111111111111 invoke [1]', 'Program ComputeBudget111111111111111111111111111111 success', 'Program ComputeBudget111111111111111111111111111111 invoke [1]', 'Program ComputeBudget111111111111111111111111111111 success', 'Program H74BkJ2MGWf93BtZ3ya5AKToLWTi66GPMdMYU5Ssvbpx invoke [1]', 'Program log: Instruction: CreatePool', 'Program H74BkJ2MGWf93BtZ3ya5AKToLWTi66GPMdMYU5Ssvbpx consumed 12859 of 499700 compute units', 'Program H74BkJ2MGWf93BtZ3ya5AKToLWTi66GPMdMYU5Ssvbpx failed: Access violation in stack frame 5 at address 0x200005ff8 of size 8' ], replacementBlockhash: null, returnData: null, unitsConsumed: 500000 } }

Code: `const { Keypair, PublicKey, SystemProgram, ComputeBudgetProgram, Transaction } = require('@solana/web3.js');
const { Wallet, AnchorProvider, Program } = require('@project-serum/anchor');
const { TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, createAssociatedTokenAccountInstruction, createMint } = require('@solana/spl-token');
const { clusterApiUrl, Connection } = require('@solana/web3.js');
const idl = require('./idl1.json');

const PRIVATE_KEY_B58 = new Uint8Array(]); // Replace with your private key
const walletKeypair = Keypair.fromSecretKey(PRIVATE_KEY_B58);
const wallet = new Wallet(walletKeypair);
const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');
const provider = new AnchorProvider(connection, wallet, { commitment: 'confirmed', skipPreflight: false });
const programId = new PublicKey('H74BkJ2MGWf93BtZ3ya5AKToLWTi66GPMdMYU5Ssvbpx');
const program = new Program(idl, programId, provider);

const AUTHORITY_SEED = [97, 117, 116, 104, 111, 114, 105, 116, 121];
const LIQUIDITY_SEED = [108, 105, 113, 117, 105, 100, 105, 116, 121];

async function checkMint(mint) {
const mintInfo = await connection.getAccountInfo(mint);
if (!mintInfo) throw new Error(Mint ${mint.toString()} does not exist);
console.log(Mint ${mint.toString()} exists);
}

async function ensureATA(mint, authority, payer) {
const ata = await getAssociatedTokenAddress(mint, authority, true);
const accountInfo = await connection.getAccountInfo(ata);
if (!accountInfo) {
console.log(Creating ATA for mint ${mint.toString()});
const tx = await provider.sendAndConfirm(
new Transaction().add(
createAssociatedTokenAccountInstruction(
payer.publicKey,
ata,
authority,
mint,
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID
)
),
[payer]
);
console.log(ATA created: ${ata.toString()}, tx: ${tx});
}
return ata;
}

async function createMints() {
const mintA = await createMint(
connection,
walletKeypair,
walletKeypair.publicKey, // Mint authority
null, // Freeze authority (null means no freeze authority)
6 // Decimals
);

const mintB = await createMint(
    connection,
    walletKeypair,
    walletKeypair.publicKey, // Mint authority
    null,                   // Freeze authority (null means no freeze authority)
    6                       // Decimals
);

console.log("Mint A:", mintA.toString());
console.log("Mint B:", mintB.toString());

return { mintA, mintB };

}

async function createAmm() {
try {
console.log("Starting AMM creation...");
const ammKeypair = Keypair.generate();
const ammId = ammKeypair.publicKey;
const fee = 300;

    const [ammAccount, bump] = await PublicKey.findProgramAddress(
        [ammId.toBuffer()],
        program.programId
    );

    console.log("AMM PDA Bump:", bump);

    const tx = await program.methods
        .createAmm(ammId, fee)
        .accounts({
            amm: ammAccount,
            admin: walletKeypair.publicKey,
            payer: walletKeypair.publicKey,
            systemProgram: SystemProgram.programId,
        })
        .preInstructions([
            ComputeBudgetProgram.setComputeUnitLimit({ units: 500000 }),
            ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 20000 }),
        ])
        .signers([walletKeypair])
        .rpc({ commitment: 'confirmed', maxRetries: 5 });

    console.log("AMM Account Address:", ammAccount.toString());
    console.log("AMM ID:", ammId.toString());
    console.log("Transaction signature:", tx);
    return { ammAccount, ammId };
} catch (err) {
    console.error("Failed to create AMM:", err);
    throw err;
}

}

async function createPool(ammAccount, ammId, mintA, mintB) {
try {
console.log("Starting pool creation...");
const balance = await connection.getBalance(walletKeypair.publicKey);
console.log("Payer Balance:", balance / 1e9, "SOL");

    if (mintA.equals(mintB)) throw new Error("mintA and mintB must be different!");
    // if (mintA.toBuffer().compare(mintB.toBuffer()) >= 0) throw new Error("mintA must be less than mintB");

    await checkMint(mintA);
    await checkMint(mintB);

    const ammData = await program.account.amm.fetch(ammAccount);
    console.log("AMM Data:", ammData);

    const [poolPDA] = await PublicKey.findProgramAddress(
        [ammAccount.toBuffer(), mintA.toBuffer(), mintB.toBuffer()],
        program.programId
    );
    const seeds = [
        ammAccount.toBuffer(), // 32 bytes
        mintA.toBuffer(),      // 32 bytes
        mintB.toBuffer(),      // 32 bytes
    ];

    console.log("Total seed bytes:", seeds.reduce((acc, seed) => acc + seed.length, 0));

    const [poolAuthority] = await PublicKey.findProgramAddress(
        [ammAccount.toBuffer(), mintA.toBuffer(), mintB.toBuffer(), AUTHORITY_SEED],
        program.programId
    );
    const [mintLiquidity] = await PublicKey.findProgramAddress(
        [ammAccount.toBuffer(), mintA.toBuffer(), mintB.toBuffer(), LIQUIDITY_SEED],
        program.programId
    );

    const poolAccountA = await ensureATA(mintA, poolAuthority, walletKeypair);
    const poolAccountB = await ensureATA(mintB, poolAuthority, walletKeypair);

    console.log("Pool Accounts:", {
        amm: ammAccount.toString(),
        pool: poolPDA.toString(),
        poolAuthority: poolAuthority.toString(),
        mintLiquidity: mintLiquidity.toString(),
        mintA: mintA.toString(),
        mintB: mintB.toString(),
        poolAccountA: poolAccountA.toString(),
        poolAccountB: poolAccountB.toString(),
        payer: walletKeypair.publicKey.toString(),
    });

    const tx = program.methods
        .createPool()
        .accounts({
            amm: ammAccount,
            pool: poolPDA,
            poolAuthority: poolAuthority,
            mintLiquidity: mintLiquidity,
            mintA: mintA,
            mintB: mintB,
            poolAccountA: poolAccountA,
            poolAccountB: poolAccountB,
            payer: walletKeypair.publicKey,
            tokenProgram: TOKEN_PROGRAM_ID,
            associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
            systemProgram: SystemProgram.programId,
        })
        .preInstructions([
            ComputeBudgetProgram.setComputeUnitLimit({ units: 500000 }),
            ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 20000 }),
        ])
        .signers([walletKeypair]);

    const simulated = await tx.simulate();
    console.log("Simulation Logs:", simulated.logs);

    const txHash = await tx.rpc({ commitment: 'confirmed', maxRetries: 5 });
    console.log("Pool PDA Address:", poolPDA.toString());
    console.log("Transaction signature:", txHash);
} catch (err) {
    console.error("Failed to create Pool:", err);
    throw err;
}

}

(async () => {
try {
console.log("Script starting...");

    // Create mints
    const { mintA, mintB } = await createMints();

    // Create AMM
    const ammResult = await createAmm();
    if (!ammResult) return;
    const { ammAccount, ammId } = ammResult;

    // Create pool
    await createPool(ammAccount, ammId, mintA, mintB);
} catch (err) {
    console.error("Main execution failed:", err);
}

})();`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant