test.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import {
  2. Connection,
  3. Keypair,
  4. PublicKey,
  5. sendAndConfirmTransaction,
  6. SystemProgram,
  7. Transaction,
  8. TransactionInstruction,
  9. } from '@solana/web3.js';
  10. import * as borsh from "borsh";
  11. import { Buffer } from "buffer";
  12. function createKeypairFromFile(path: string): Keypair {
  13. return Keypair.fromSecretKey(
  14. Buffer.from(JSON.parse(require('fs').readFileSync(path, "utf-8")))
  15. )
  16. };
  17. describe("PDAs", () => {
  18. const connection = new Connection(`http://localhost:8899`, 'confirmed');
  19. const payer = createKeypairFromFile(require('os').homedir() + '/.config/solana/id.json');
  20. const PROGRAM_ID: PublicKey = new PublicKey(
  21. "BCw7MQWBugruuYgno5crGUGFNufqGJbPpzZevhRRRQAu"
  22. );
  23. class Assignable {
  24. constructor(properties) {
  25. Object.keys(properties).map((key) => {
  26. return (this[key] = properties[key]);
  27. });
  28. };
  29. };
  30. class PageVisits extends Assignable {
  31. toBuffer() { return Buffer.from(borsh.serialize(PageVisitsSchema, this)) }
  32. static fromBuffer(buffer: Buffer) {
  33. return borsh.deserialize(PageVisitsSchema, PageVisits, buffer);
  34. };
  35. };
  36. const PageVisitsSchema = new Map([
  37. [ PageVisits, {
  38. kind: 'struct',
  39. fields: [ ['page_visits', 'u32'], ['bump', 'u8'] ],
  40. }]
  41. ]);
  42. class IncrementPageVisits extends Assignable {
  43. toBuffer() { return Buffer.from(borsh.serialize(IncrementPageVisitsSchema, this)) }
  44. };
  45. const IncrementPageVisitsSchema = new Map([
  46. [ IncrementPageVisits, {
  47. kind: 'struct',
  48. fields: [],
  49. }]
  50. ]);
  51. const testUser = Keypair.generate();
  52. it("Create a test user", async () => {
  53. let ix = SystemProgram.createAccount({
  54. fromPubkey: payer.publicKey,
  55. lamports: await connection.getMinimumBalanceForRentExemption(0),
  56. newAccountPubkey: testUser.publicKey,
  57. programId: SystemProgram.programId,
  58. space: 0,
  59. });
  60. await sendAndConfirmTransaction(
  61. connection,
  62. new Transaction().add(ix),
  63. [payer, testUser]
  64. );
  65. console.log(`Local Wallet: ${payer.publicKey}`);
  66. console.log(`Created User: ${testUser.publicKey}`);
  67. });
  68. function derivePageVisitsPda(userPubkey: PublicKey) {
  69. return PublicKey.findProgramAddressSync(
  70. [Buffer.from("page_visits"), userPubkey.toBuffer()],
  71. PROGRAM_ID,
  72. )
  73. }
  74. it("Create the page visits tracking PDA", async () => {
  75. const [pageVisitsPda, pageVisitsBump] = derivePageVisitsPda(testUser.publicKey);
  76. let ix = new TransactionInstruction({
  77. keys: [
  78. {pubkey: pageVisitsPda, isSigner: false, isWritable: true},
  79. {pubkey: testUser.publicKey, isSigner: false, isWritable: false},
  80. {pubkey: payer.publicKey, isSigner: true, isWritable: true},
  81. {pubkey: SystemProgram.programId, isSigner: false, isWritable: false}
  82. ],
  83. programId: PROGRAM_ID,
  84. data: (new PageVisits({page_visits: 0, bump: pageVisitsBump})).toBuffer(),
  85. });
  86. await sendAndConfirmTransaction(
  87. connection,
  88. new Transaction().add(ix),
  89. [payer]
  90. );
  91. });
  92. it("Visit the page!", async () => {
  93. const [pageVisitsPda, _] = derivePageVisitsPda(testUser.publicKey);
  94. let ix = new TransactionInstruction({
  95. keys: [
  96. {pubkey: pageVisitsPda, isSigner: false, isWritable: true},
  97. {pubkey: payer.publicKey, isSigner: true, isWritable: true},
  98. ],
  99. programId: PROGRAM_ID,
  100. data: new IncrementPageVisits({}).toBuffer(),
  101. });
  102. await sendAndConfirmTransaction(
  103. connection,
  104. new Transaction().add(ix),
  105. [payer]
  106. );
  107. });
  108. it("Visit the page!", async () => {
  109. const [pageVisitsPda, _] = derivePageVisitsPda(testUser.publicKey);
  110. let ix = new TransactionInstruction({
  111. keys: [
  112. {pubkey: pageVisitsPda, isSigner: false, isWritable: true},
  113. {pubkey: payer.publicKey, isSigner: true, isWritable: true},
  114. ],
  115. programId: PROGRAM_ID,
  116. data: new IncrementPageVisits({}).toBuffer(),
  117. });
  118. await sendAndConfirmTransaction(
  119. connection,
  120. new Transaction().add(ix),
  121. [payer]
  122. );
  123. });
  124. it("Read page visits", async () => {
  125. const [pageVisitsPda, _] = derivePageVisitsPda(testUser.publicKey);
  126. const accountInfo = await connection.getAccountInfo(pageVisitsPda);
  127. const readPageVisits = PageVisits.fromBuffer(accountInfo.data);
  128. console.log(`Number of page visits: ${readPageVisits.page_visits}`);
  129. });
  130. });