user_stats.spec.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // SPDX-License-Identifier: Apache-2.0
  2. import { loadContract } from "./setup";
  3. import { Keypair, PublicKey } from "@solana/web3.js";
  4. import { utils } from '@coral-xyz/anchor';
  5. import expect from "expect";
  6. describe('PDA hash table', function () {
  7. // A PDA (Program derived address) hash table is a way to store values for a provided key
  8. // on a unique account on chain, resembling a hash table. This is an example for achieving
  9. // so with Solidity.
  10. it('Table functions', async function test_table() {
  11. const { program, payer } = await loadContract("UserStats");
  12. // A user's public key will be the key for the hash table in this example.
  13. const myUser = Keypair.generate();
  14. // The actual 'hash' for our hash table is PDA. We utilize `findProgramAddress`, using the user's
  15. // public key as a seed and a 'user-stats' as another seed for randomness. This function will
  16. // return the same bump and PDA if the seeds and the program id are the same.
  17. const [userStatsPDA, bump] = PublicKey.findProgramAddressSync(
  18. [
  19. utils.bytes.utf8.encode('user-stats'),
  20. myUser.publicKey.toBuffer(),
  21. ],
  22. program.programId
  23. );
  24. // We create the account to hold the user's related information. The generated PDA becomes the
  25. // data account for our contract.
  26. // If a contract for `userStatsPDA` already exists, this function will fail.
  27. await program.methods.new(myUser.publicKey, bump, "user-one", 25)
  28. .accounts({
  29. dataAccount: userStatsPDA,
  30. wallet: payer.publicKey,
  31. })
  32. .signers([payer])
  33. .rpc();
  34. // To read the information from the contract, the data account is also necessary
  35. // If there is no contract created for `userStatsPDA`, this function will fail.
  36. let res = await program.methods.returnStats()
  37. .accounts({ dataAccount: userStatsPDA })
  38. .view();
  39. expect(res.return0).toBe("user-one");
  40. expect(res.return1).toBe(25);
  41. expect(res.return2).toBe(bump);
  42. // These function update the information in the contract.
  43. // If there is no contract created for `userStatsPDA`, these calls will fail.
  44. await program.methods.changeUserName("new-user-one")
  45. .accounts({ dataAccount: userStatsPDA })
  46. .rpc();
  47. await program.methods.changeLevel(20)
  48. .accounts({ dataAccount: userStatsPDA })
  49. .rpc();
  50. res = await program.methods.returnStats()
  51. .accounts({ dataAccount: userStatsPDA })
  52. .view();
  53. expect(res.return0).toBe("new-user-one");
  54. expect(res.return1).toBe(20);
  55. expect(res.return2).toBe(bump);
  56. });
  57. });