program-derived-addresses.sol 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import "solana";
  2. @program_id("F1ipperKF9EfD821ZbbYjS319LXYiBmjhzkkf5a26rC")
  3. contract program_derived_addresses {
  4. // A private instance of the PageVisits struct
  5. // This is the data that is stored in the account
  6. PageVisits private accountData;
  7. // The PageVisits struct definition
  8. struct PageVisits {
  9. uint32 pageVisits;
  10. bytes1 bump;
  11. }
  12. // The constructor is used to create a new account
  13. // The seeds, bump, and programId are used to derive a unique and deterministic pda (program derived address) to use as the account address
  14. @payer(payer) // "payer" is the account that pays for creating the account
  15. @seed("page_visits") // hardcoded seed
  16. constructor(
  17. @seed bytes payer, // additional seed using the payer address
  18. @bump bytes1 bump // bump seed to derive the pda
  19. ) {
  20. // Independently derive the PDA address from the seeds, bump, and programId
  21. (address pda, bytes1 _bump) = try_find_program_address(["page_visits", payer], type(program_derived_addresses).program_id);
  22. // Verify that the bump passed to the constructor matches the bump derived from the seeds and programId
  23. // This ensures that only the canonical pda address can be used to create the account (first bump that generates a valid pda address)
  24. require(bump == _bump, 'INVALID_BUMP');
  25. // The PageVisits instance is initialized with pageVisits set to zero and bump set to the bump passed to the constructor
  26. accountData = PageVisits(0, bump);
  27. }
  28. // Increments the pageVisits by one.
  29. function incrementPageVisits() public {
  30. accountData.pageVisits += 1;
  31. }
  32. // Returns the accountData (pageVisits and bump) stored on the account
  33. function get() public view returns (PageVisits) {
  34. return accountData;
  35. }
  36. }