Skip to content

Commit

Permalink
feat:updated counter tests
Browse files Browse the repository at this point in the history
  • Loading branch information
adpthegreat committed Nov 24, 2024
1 parent 6f2d1c2 commit 34b75c1
Show file tree
Hide file tree
Showing 7 changed files with 171 additions and 53 deletions.
2 changes: 1 addition & 1 deletion basics/counter/poseidon/counter_program/Anchor.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ resolution = true
skip-lint = false

[programs.localnet]
counter_program = "EvcknV23Y3dkbSa4afZNGw2PgoowcfxCy4qvP8Ghogwu"
counter_program = "3DRpGvotDMHtXzHahF1jdzYEiYa52cwpQcqGiNPw9vRd"

[registry]
url = "https://api.apr.dev"
Expand Down
1 change: 1 addition & 0 deletions basics/counter/poseidon/counter_program/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
},
"dependencies": {
"@coral-xyz/anchor": "^0.30.1",
"@solana/web3.js": "^1.95.4",
"anchor-bankrun": "^0.5.0",
"solana-bankrun": "^0.4.0"
},
Expand Down
7 changes: 5 additions & 2 deletions basics/counter/poseidon/counter_program/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use anchor_lang::prelude::*;
declare_id!("EvcknV23Y3dkbSa4afZNGw2PgoowcfxCy4qvP8Ghogwu");
declare_id!("3DRpGvotDMHtXzHahF1jdzYEiYa52cwpQcqGiNPw9vRd");
#[program]
pub mod counter_program {
use super::*;
pub fn initialize_counter(ctx: Context<InitializeCounterContext>) -> Result<()> {
ctx.accounts.counter.count = 0;
ctx.accounts.counter.payer = ctx.accounts.payer.key();
Ok(())
}
pub fn increment(ctx: Context<IncrementContext>) -> Result<()> {
Expand All @@ -18,26 +19,34 @@ pub mod counter_program {
}
#[derive(Accounts)]
pub struct InitializeCounterContext<'info> {
#[account(init, payer = payer, space = 17, seeds = [b"count"], bump)]
pub counter: Account<'info, Counter>,
#[account(mut)]
pub payer: Signer<'info>,
#[account(
init,
payer = payer,
space = 49,
seeds = [b"count",
payer.key().as_ref()],
bump,
)]
pub counter: Account<'info, Counter>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct IncrementContext<'info> {
#[account(mut, seeds = [b"count"], bump)]
#[account(mut)]
pub counter: Account<'info, Counter>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct DecrementContext<'info> {
#[account(mut, seeds = [b"count"], bump)]
#[account(mut)]
pub counter: Account<'info, Counter>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct Counter {
pub payer: Pubkey,
pub count: u64,
pub bump: u8,
}
103 changes: 84 additions & 19 deletions basics/counter/poseidon/counter_program/tests/bankrun.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,35 @@
import assert from 'node:assert';
import { before, describe, it } from 'node:test';
import * as anchor from '@coral-xyz/anchor';
import { Keypair, PublicKey } from '@solana/web3.js';
import { Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js';
import { BankrunProvider } from 'anchor-bankrun';
import { assert } from 'chai';
import { startAnchor } from 'solana-bankrun';
import { BanksClient, BanksTransactionResultWithMeta, startAnchor } from 'solana-bankrun';
import type { CounterProgram } from '../target/types/counter_program';

const IDL = require('../target/idl/counter_program.json');

const PROGRAM_ID = new PublicKey(IDL.address);

async function createAndProcessTransaction(
client: BanksClient,
payer: Keypair,
instruction: TransactionInstruction,
additionalSigners: Keypair[] = [],
): Promise<BanksTransactionResultWithMeta> {
const tx = new Transaction();
// Get the latest blockhash
const [latestBlockhash] = await client.getLatestBlockhash();
tx.recentBlockhash = latestBlockhash;
// Add transaction instructions
tx.add(instruction);
tx.feePayer = payer.publicKey;
//Add signers
tx.sign(payer, ...additionalSigners);
// Process transaction
const result = await client.tryProcessTransaction(tx);
return result;
}

describe('counter_program', async () => {
// Configure the client to use the anchor-bankrun
const context = await startAnchor('', [{ name: 'counter_program', programId: PROGRAM_ID }], []);
Expand All @@ -18,65 +40,108 @@ describe('counter_program', async () => {

const program = new anchor.Program<CounterProgram>(IDL, provider);

const [counterState, _] = anchor.web3.PublicKey.findProgramAddressSync([anchor.utils.bytes.utf8.encode('count')], program.programId);
const counterKeypair = Keypair.generate(); // Generate a new user keypair

before(async () => {
//Transfer SOL to the user account to cover rent
const transferInstruction = SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: counterKeypair.publicKey,
lamports: 2 * LAMPORTS_PER_SOL,
});

await createAndProcessTransaction(context.banksClient, payer.payer, transferInstruction, [payer.payer]);
const userBalance = await context.banksClient.getBalance(counterKeypair.publicKey);
console.log(`User balance after funding: ${userBalance}`);
});

const [counter, _] = anchor.web3.PublicKey.findProgramAddressSync([Buffer.from('count'), counterKeypair.publicKey.toBuffer()], program.programId);

it('Initialize Counter', async () => {
await program.methods
.initializeCounter()
.accounts({
payer: payer.publicKey,
payer: counterKeypair.publicKey,
})
.signers([counterKeypair])
.rpc();

const currentCount = await program.account.counter.fetch(counterState);
const currentCount = await program.account.counter.fetch(counter);

assert(currentCount.count.toNumber() === 0, 'Expected initialized count to be 0');
});

it('Increment Counter', async () => {
await program.methods.increment().accounts({}).rpc();
await program.methods
.increment()
.accounts({
counter: counter,
})
.rpc();

const currentCount = await program.account.counter.fetch(counterState);
const currentCount = await program.account.counter.fetch(counter);

assert(currentCount.count.toNumber() === 1, 'Expected count to be 1');
});

it('Increment Counter Again', async () => {
await program.methods.increment().accounts({ counter: counterState }).rpc();
await program.methods
.increment()
.accounts({
counter: counter,
})
.rpc();

const currentCount = await program.account.counter.fetch(counterState);
const currentCount = await program.account.counter.fetch(counter);

assert(currentCount.count.toNumber() === 2, 'Expected count to be 2');
});

it('Decrement counter', async () => {
await program.methods.decrement().accounts({}).rpc();
await program.methods
.decrement()
.accounts({
counter: counter,
})
.rpc();

const currentCount = await program.account.counter.fetch(counterState);
const currentCount = await program.account.counter.fetch(counter);
assert(currentCount.count.toNumber() === 1, 'Expected count to be 1');
});

it('Increment and decrement multiple times', async () => {
// Increment the counter 5 times
for (let i = 0; i < 5; i++) {
await program.methods.increment().accounts({}).rpc();
await program.methods
.increment()
.accounts({
counter: counter,
})
.rpc();
}

let currentCount = await program.account.counter.fetch(counterState);
let currentCount = await program.account.counter.fetch(counter);
assert.strictEqual(currentCount.count.toNumber(), 6, 'Expected count to be 6 after 5 increments');

// Decrement the counter 4 times
for (let i = 0; i < 4; i++) {
await program.methods.decrement().accounts({}).rpc();
await program.methods
.decrement()
.accounts({
counter: counter,
})
.rpc();
}

currentCount = await program.account.counter.fetch(counterState);
currentCount = await program.account.counter.fetch(counter);
assert.strictEqual(currentCount.count.toNumber(), 2, 'Expected count to be 2 after 4 decrements');
});

it('Cannot decrement below 0', async () => {
// Decrement the counter to 0
await program.methods.decrement().accounts({}).rpc();
await program.methods.decrement().accounts({}).rpc();
const currentCount = await program.account.counter.fetch(counterState);
await program.methods.decrement().accounts({ counter: counter }).rpc();
await program.methods.decrement().accounts({ counter: counter }).rpc();
const currentCount = await program.account.counter.fetch(counter);
assert.strictEqual(currentCount.count.toNumber(), 0, 'Expected count to be 0 after multiple decrements');
});
});
69 changes: 54 additions & 15 deletions basics/counter/poseidon/counter_program/tests/counter_program.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { before, describe, it } from 'node:test';
import * as anchor from '@coral-xyz/anchor';
import { Program } from '@coral-xyz/anchor';
import { Keypair } from '@solana/web3.js';
Expand All @@ -14,7 +15,7 @@ describe('counter_program', () => {

const program = anchor.workspace.CounterProgram as Program<CounterProgram>;

const [counterState, _] = anchor.web3.PublicKey.findProgramAddressSync([anchor.utils.bytes.utf8.encode('count')], program.programId);
const [counter, _] = anchor.web3.PublicKey.findProgramAddressSync([anchor.utils.bytes.utf8.encode('count')], program.programId);

it('Initialize Counter', async () => {
await program.methods
Expand All @@ -24,55 +25,93 @@ describe('counter_program', () => {
})
.rpc();

const currentCount = await program.account.counter.fetch(counterState);
const currentCount = await program.account.counter.fetch(counter);

assert(currentCount.count.toNumber() === 0, 'Expected initialized count to be 0');
});

it('Increment Counter', async () => {
await program.methods.increment().accounts({}).rpc();
await program.methods
.increment()
.accounts({
counter: counter,
})
.rpc();

const currentCount = await program.account.counter.fetch(counterState);
const currentCount = await program.account.counter.fetch(counter);

assert(currentCount.count.toNumber() === 1, 'Expected count to be 1');
});

it('Increment Counter Again', async () => {
await program.methods.increment().accounts({ counter: counterState }).rpc();
await program.methods
.increment()
.accounts({
counter: counter,
})
.rpc();

const currentCount = await program.account.counter.fetch(counterState);
const currentCount = await program.account.counter.fetch(counter);

assert(currentCount.count.toNumber() === 2, 'Expected count to be 2');
});
it('Decrement counter', async () => {
await program.methods.decrement().accounts({}).rpc();
await program.methods
.decrement()
.accounts({
counter: counter,
})
.rpc();

const currentCount = await program.account.counter.fetch(counterState);
const currentCount = await program.account.counter.fetch(counter);
assert(currentCount.count.toNumber() === 1, 'Expected count to be 1');
});
it('Increment and decrement multiple times', async () => {
// Increment the counter 5 times
for (let i = 0; i < 5; i++) {
await program.methods.increment().accounts({}).rpc();
await program.methods
.increment()
.accounts({
counter: counter,
})
.rpc();
}

let currentCount = await program.account.counter.fetch(counterState);
let currentCount = await program.account.counter.fetch(counter);
assert.strictEqual(currentCount.count.toNumber(), 6, 'Expected count to be 6 after 5 increments');

// Decrement the counter 4 times
for (let i = 0; i < 4; i++) {
await program.methods.decrement().accounts({}).rpc();
await program.methods
.decrement()
.accounts({
counter: counter,
})
.rpc();
}

currentCount = await program.account.counter.fetch(counterState);
currentCount = await program.account.counter.fetch(counter);
assert.strictEqual(currentCount.count.toNumber(), 2, 'Expected count to be 2 after 4 decrements');
});

it('Cannot decrement below 0', async () => {
// Decrement the counter to 0
await program.methods.decrement().accounts({}).rpc();
await program.methods.decrement().accounts({}).rpc();
const currentCount = await program.account.counter.fetch(counterState);
await program.methods
.decrement()
.accounts({
counter: counter,
})
.rpc();

await program.methods
.decrement()
.accounts({
counter: counter,
})
.rpc();

const currentCount = await program.account.counter.fetch(counter);

assert.strictEqual(currentCount.count.toNumber(), 0, 'Expected count to be 0 after multiple decrements');
});
});
Loading

0 comments on commit 34b75c1

Please sign in to comment.