Skip to content

Commit c7839fa

Browse files
author
adpthegreat
committed
updated tests, updated code to use newly added String<Number> type from poseidon
1 parent 55d896f commit c7839fa

File tree

8 files changed

+134
-87
lines changed

8 files changed

+134
-87
lines changed

basics/close-account/poseidon/close_account_program/Anchor.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ resolution = true
55
skip-lint = false
66

77
[programs.localnet]
8-
close_account_program = "2q4uoWExFAbZjeDe4n3miipsT9bX9vLnkSetCfZYF2VT"
8+
close_account_program = "DDhy3V9AQE4wrJ3DXC5Yop2p56J6TiBRaz4zjnYnK8ao"
99

1010
[registry]
1111
url = "https://api.apr.dev"

basics/close-account/poseidon/close_account_program/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
"dependencies": {
99
"@coral-xyz/anchor": "^0.30.1",
1010
"anchor-bankrun": "^0.5.0",
11-
"solana-bankrun": "^0.4.0"
11+
"solana-bankrun": "^0.4.0",
12+
"@solana/web3.js": "^1.95.4"
1213
},
1314
"devDependencies": {
1415
"@types/bn.js": "^5.1.0",

basics/close-account/poseidon/close_account_program/pnpm-lock.yaml

Lines changed: 5 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
use anchor_lang::prelude::*;
2-
declare_id!("2q4uoWExFAbZjeDe4n3miipsT9bX9vLnkSetCfZYF2VT");
2+
declare_id!("DDhy3V9AQE4wrJ3DXC5Yop2p56J6TiBRaz4zjnYnK8ao");
33
#[program]
44
pub mod close_account {
55
use super::*;
6-
pub fn create_user(ctx: Context<CreateUserContext>, name: u32) -> Result<()> {
7-
ctx.accounts.user_account.user_bump = ctx.bumps.user_account;
8-
ctx.accounts.user_account.user = ctx.accounts.user.key();
9-
ctx.accounts.user_account.name = name;
6+
pub fn create_user(ctx: Context<CreateUserContext>, name: String) -> Result<()> {
7+
ctx.accounts.user_state.user_bump = ctx.bumps.user_state;
8+
ctx.accounts.user_state.user = ctx.accounts.user.key();
9+
ctx.accounts.user_state.name = name;
1010
Ok(())
1111
}
1212
pub fn close_user(ctx: Context<CloseUserContext>) -> Result<()> {
@@ -20,25 +20,25 @@ pub struct CreateUserContext<'info> {
2020
#[account(
2121
init,
2222
payer = user,
23-
space = 42,
23+
space = 95,
2424
seeds = [b"USER",
2525
user.key().as_ref()],
2626
bump,
2727
)]
28-
pub user_account: Account<'info, UserAccount>,
28+
pub user_state: Account<'info, UserState>,
2929
pub system_program: Program<'info, System>,
3030
}
3131
#[derive(Accounts)]
3232
pub struct CloseUserContext<'info> {
33+
#[account(mut, seeds = [b"USER", user.key().as_ref()], bump, close = user)]
34+
pub user_account: Account<'info, UserState>,
3335
#[account(mut)]
3436
pub user: Signer<'info>,
35-
#[account(mut, seeds = [b"USER", user.key().as_ref()], bump, close = user)]
36-
pub user_account: Account<'info, UserAccount>,
3737
pub system_program: Program<'info, System>,
3838
}
3939
#[account]
40-
pub struct UserAccount {
40+
pub struct UserState {
4141
pub user_bump: u8,
42-
pub name: u32,
42+
pub name: String,
4343
pub user: Pubkey,
4444
}
Lines changed: 59 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,96 @@
11
import assert from 'node:assert';
22
import { describe, it } from 'node:test';
33
import * as anchor from '@coral-xyz/anchor';
4-
import { PublicKey } from '@solana/web3.js';
4+
import {
5+
Keypair,
6+
LAMPORTS_PER_SOL,
7+
PublicKey,
8+
SystemProgram,
9+
Transaction,
10+
TransactionInstruction,
11+
TransactionMessage,
12+
VersionedTransaction,
13+
sendAndConfirmTransaction,
14+
} from '@solana/web3.js';
515
import { BankrunProvider } from 'anchor-bankrun';
6-
import { startAnchor } from 'solana-bankrun';
7-
import type { CloseAccountProgram } from '../target/types/close_account_program';
16+
import { BanksClient, BanksTransactionResultWithMeta, startAnchor } from 'solana-bankrun';
17+
import type { CloseAccount } from '../target/types/close_account';
818

9-
const IDL = require('../target/idl/close_account_program.json');
19+
const IDL = require('../target/idl/close_account');
1020
const PROGRAM_ID = new PublicKey(IDL.address);
1121

22+
async function createAndProcessTransaction(
23+
client: BanksClient,
24+
payer: Keypair,
25+
instruction: TransactionInstruction,
26+
additionalSigners: Keypair[] = [],
27+
): Promise<BanksTransactionResultWithMeta> {
28+
const tx = new Transaction();
29+
// Get the latest blockhash and minimum rent-exempt balance
30+
const [latestBlockhash] = await client.getLatestBlockhash();
31+
tx.recentBlockhash = latestBlockhash;
32+
// Add transaction instructions
33+
tx.add(instruction);
34+
tx.feePayer = payer.publicKey;
35+
//Add signers
36+
tx.sign(payer, ...additionalSigners);
37+
const result = await client.tryProcessTransaction(tx);
38+
return result;
39+
}
40+
1241
describe('Close an account', async () => {
1342
// Configure the client to use the local cluster.
14-
const context = await startAnchor('', [{ name: 'close_account', programId: PROGRAM_ID }], []);
43+
const context = await startAnchor('', [{ name: 'close_account_program', programId: PROGRAM_ID }], []);
1544
const provider = new BankrunProvider(context);
1645

1746
const payer = provider.wallet as anchor.Wallet;
18-
const program = new anchor.Program<CloseAccountProgram>(IDL, provider);
47+
const program = new anchor.Program<CloseAccount>(IDL, provider);
1948
// Derive the PDA for the user's account.
20-
const [userAccountAddress] = PublicKey.findProgramAddressSync([Buffer.from('USER'), payer.publicKey.toBuffer()], program.programId);
49+
const user = Keypair.generate(); // Generate a new user keypair
50+
51+
//Transfer SOL to the user account to cover rent
52+
const transferInstruction = SystemProgram.transfer({
53+
fromPubkey: payer.publicKey,
54+
toPubkey: user.publicKey,
55+
lamports: 2 * LAMPORTS_PER_SOL,
56+
});
57+
58+
await createAndProcessTransaction(context.banksClient, payer.payer, transferInstruction, [payer.payer]);
59+
60+
const [userAccount, userAccountBump] = PublicKey.findProgramAddressSync([Buffer.from('USER'), user.publicKey.toBuffer()], program.programId);
2161

2262
it('Can create an account', async () => {
23-
const userId = anchor.BN(76362);
2463
await program.methods
25-
.createUser(userId)
64+
.createUser('Jacob')
2665
.accounts({
27-
user: payer.publicKey,
66+
user: user.publicKey,
2867
})
68+
.signers([user])
2969
.rpc();
3070

3171
// Fetch the account data
32-
const userAccount = await program.account.userAccount.fetch(userAccountAddress);
33-
assert.notEqual(userAccount, null);
72+
const userAccountData = await program.account.userState.fetch(userAccount);
73+
assert.equal(userAccountData.name, 'Jacob');
74+
assert.equal(userAccountData.user.toBase58(), user.publicKey.toBase58());
75+
assert.notEqual(userAccountData, null);
3476
});
3577

3678
it('Can close an Account', async () => {
3779
await program.methods
3880
.closeUser()
3981
.accounts({
40-
user: payer.publicKey,
82+
user: user.publicKey,
4183
})
84+
.signers([user])
4285
.rpc();
4386

4487
// The account should no longer exist, returning null.
4588
try {
46-
const userAccount = await program.account.userAccount.fetchNullable(userAccountAddress);
47-
assert.equal(userAccount, null);
89+
const userAccountData = await program.account.userState.fetchNullable(userAccount);
90+
assert.equal(userAccountData, null);
4891
} catch (err) {
4992
// Won't return null and will throw an error in anchor-bankrun'
50-
assert.equal(err.message, `Could not find ${userAccountAddress}`);
93+
assert.equal(err.message, `Could not find ${userAccount}`);
5194
}
5295
});
5396
});
Lines changed: 45 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,45 @@
1-
import assert from 'node:assert';
2-
import * as anchor from '@coral-xyz/anchor';
3-
import type { Program } from '@coral-xyz/anchor';
4-
import { PublicKey } from '@solana/web3.js';
5-
import type { CloseAccountProgram } from '../target/types/close_account_program';
6-
7-
describe('Close an account', () => {
8-
// Configure the client to use the local cluster.
9-
const provider = anchor.AnchorProvider.env();
10-
anchor.setProvider(provider);
11-
12-
const program = anchor.workspace.CloseAccountProgram as Program<CloseAccountProgram>;
13-
const payer = provider.wallet as anchor.Wallet;
14-
15-
// Derive the PDA for the user's account.
16-
const [userAccountAddress] = PublicKey.findProgramAddressSync([Buffer.from('USER'), payer.publicKey.toBuffer()], program.programId);
17-
18-
it('can create an account', async () => {
19-
const userId = anchor.BN(76362);
20-
21-
await program.methods
22-
.createUser(userId)
23-
.accounts({
24-
user: payer.publicKey,
25-
})
26-
.rpc();
27-
28-
// Fetch the account data
29-
const userAccount = await program.account.userAccount.fetch(userAccountAddress);
30-
assert.notEqual(userAccount, null);
31-
});
32-
33-
it('can close an account', async () => {
34-
await program.methods
35-
.closeUser()
36-
.accounts({
37-
user: payer.publicKey,
38-
})
39-
.rpc();
40-
41-
// The account should no longer exist, returning null.
42-
const userAccount = await program.account.userAccount.fetchNullable(userAccountAddress);
43-
assert.equal(userAccount, null);
44-
});
45-
});
1+
// import assert from 'node:assert';
2+
// import * as anchor from '@coral-xyz/anchor';
3+
// import type { Program } from '@coral-xyz/anchor';
4+
// import { PublicKey } from '@solana/web3.js';
5+
// import type { CloseAccount } from '../target/types/close_account';
6+
7+
// describe('Close an account', () => {
8+
// // Configure the client to use the local cluster.
9+
// const provider = anchor.AnchorProvider.env();
10+
// anchor.setProvider(provider);
11+
12+
// const program = anchor.workspace.CloseAccountProgram as Program<CloseAccount>;
13+
// const payer = provider.wallet as anchor.Wallet;
14+
15+
// // Derive the PDA for the user's account.
16+
// const [userAccountAddress] = PublicKey.findProgramAddressSync([Buffer.from('USER'), payer.publicKey.toBuffer()], program.programId);
17+
18+
// it('can create an account', async () => {
19+
// const userId = anchor.BN(76362);
20+
21+
// await program.methods
22+
// .createUser(userId)
23+
// .accounts({
24+
// user: payer.publicKey,
25+
// })
26+
// .rpc();
27+
28+
// // Fetch the account data
29+
// const userAccount = await program.account.userAccount.fetch(userAccountAddress);
30+
// assert.notEqual(userAccount, null);
31+
// });
32+
33+
// it('can close an account', async () => {
34+
// await program.methods
35+
// .closeUser()
36+
// .accounts({
37+
// user: payer.publicKey,
38+
// })
39+
// .rpc();
40+
41+
// // The account should no longer exist, returning null.
42+
// const userAccount = await program.account.userAccount.fetchNullable(userAccountAddress);
43+
// assert.equal(userAccount, null);
44+
// });
45+
// });

basics/close-account/poseidon/close_account_program/ts-programs/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,6 @@
1010
"author": "",
1111
"license": "ISC",
1212
"dependencies": {
13-
"@solanaturbine/poseidon": "^0.0.4"
13+
"@solanaturbine/poseidon": "^0.0.8"
1414
}
1515
}
Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
1-
import { Account, Pubkey, Result, Signer, u8, u32 } from '@solanaturbine/poseidon';
1+
import { Account, String as PoseidonString, Pubkey, Result, Signer, u8 } from '@solanaturbine/poseidon';
22

33
export default class CloseAccount {
4-
static PROGRAM_ID = new Pubkey('2q4uoWExFAbZjeDe4n3miipsT9bX9vLnkSetCfZYF2VT');
4+
static PROGRAM_ID = new Pubkey('DDhy3V9AQE4wrJ3DXC5Yop2p56J6TiBRaz4zjnYnK8ao');
55

6-
createUser(user: Signer, userAccount: UserAccount, userId: u32): Result {
7-
userAccount.derive(['USER', user.key]).init();
6+
createUser(user: Signer, userState: UserState, name: PoseidonString<50>): Result {
7+
userState.derive(['USER', user.key]).init();
88

9-
userAccount.userBump = userAccount.getBump();
9+
userState.userBump = userState.getBump();
1010

11-
userAccount.user = user.key;
11+
userState.user = user.key;
1212

13-
userAccount.userId = userId;
13+
userState.name = name;
1414
}
15-
closeUser(userAccount: UserAccount, user: Signer): Result {
15+
closeUser(userAccount: UserState, user: Signer): Result {
1616
userAccount.derive(['USER', user.key]).close(user);
1717
}
1818
}
1919

20-
export interface UserAccount extends Account {
20+
export interface UserState extends Account {
2121
userBump: u8;
22-
userId: u32;
22+
name: PoseidonString<50>;
2323
user: Pubkey;
2424
}

0 commit comments

Comments
 (0)