program-derived-addresses.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import * as anchor from "@coral-xyz/anchor";
  2. import { Program } from "@coral-xyz/anchor";
  3. import { ProgramDerivedAddresses } from "../target/types/program_derived_addresses";
  4. import { PublicKey } from "@solana/web3.js";
  5. describe("program-derived-addresses", () => {
  6. // Configure the client to use the local cluster.
  7. const provider = anchor.AnchorProvider.env();
  8. anchor.setProvider(provider);
  9. const wallet = provider.wallet;
  10. const program = anchor.workspace
  11. .ProgramDerivedAddresses as Program<ProgramDerivedAddresses>;
  12. // Derive the PDA that will be used to initialize the dataAccount.
  13. const [dataAccountPDA, bump] = PublicKey.findProgramAddressSync(
  14. [Buffer.from("page_visits"), wallet.publicKey.toBuffer()],
  15. program.programId
  16. );
  17. it("Is initialized!", async () => {
  18. // Initialize the dataAccount using a PDA as the address.
  19. // The PDA doesn't have to be passed in explicity as a signer, the program can "sign" for it.
  20. // This is a feature of PDAs that allows programs to "sign" for PDA that are derived from their programId.
  21. const tx = await program.methods
  22. .new(
  23. wallet.publicKey.toBuffer(), // wallet.publicKey is the payer for the new account
  24. [bump] // bump seed for the PDA found using findProgramAddress
  25. )
  26. .accounts({ dataAccount: dataAccountPDA })
  27. .rpc({ skipPreflight: true });
  28. console.log("Your transaction signature", tx);
  29. // Get the current state of the dataAccount.
  30. const val = await program.methods
  31. .get()
  32. .accounts({ dataAccount: dataAccountPDA })
  33. .view();
  34. console.log("State:", val);
  35. });
  36. it("Visit the page!", async () => {
  37. // Increment the page visits counter.
  38. const tx = await program.methods
  39. .incrementPageVisits()
  40. .accounts({ dataAccount: dataAccountPDA })
  41. .rpc();
  42. console.log("Your transaction signature", tx);
  43. // Get the current state of the dataAccount.
  44. const val = await program.methods
  45. .get()
  46. .accounts({ dataAccount: dataAccountPDA })
  47. .view();
  48. console.log("State:", val);
  49. });
  50. });