close-account.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. describe('close-an-account', () => {
  7. // Configure the client to use the local cluster.
  8. const provider = anchor.AnchorProvider.env();
  9. anchor.setProvider(provider);
  10. const program = anchor.workspace.CloseAccountProgram as Program<CloseAccountProgram>;
  11. const payer = provider.wallet as anchor.Wallet;
  12. // Derive the PDA for the user's account.
  13. const [userAccountAddress] = PublicKey.findProgramAddressSync([Buffer.from('USER'), payer.publicKey.toBuffer()], program.programId);
  14. it('Create Account', async () => {
  15. await program.methods
  16. .createUser('John Doe')
  17. .accounts({
  18. user: payer.publicKey,
  19. userAccount: userAccountAddress,
  20. })
  21. .rpc();
  22. // Fetch the account data
  23. const userAccount = await program.account.userState.fetch(userAccountAddress);
  24. assert.equal(userAccount.name, 'John Doe');
  25. assert.equal(userAccount.user.toBase58(), payer.publicKey.toBase58());
  26. });
  27. it('Close Account', async () => {
  28. await program.methods
  29. .closeUser()
  30. .accounts({
  31. user: payer.publicKey,
  32. userAccount: userAccountAddress,
  33. })
  34. .rpc();
  35. // The account should no longer exist, returning null.
  36. const userAccount = await program.account.userState.fetchNullable(userAccountAddress);
  37. assert.equal(userAccount, null);
  38. });
  39. });