program-derived-addresses.sol 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. @seed(abi.encode(payer)) // additional seed using the payer address
  17. @bump(bump) // bump seed to derive the pda
  18. constructor(address payer, bytes1 bump) {
  19. // Independently derive the PDA address from the seeds, bump, and programId
  20. (address pda, bytes1 _bump) = try_find_program_address(["page_visits", abi.encode(payer)], type(program_derived_addresses).program_id);
  21. // Verify that the bump passed to the constructor matches the bump derived from the seeds and programId
  22. // This ensures that only the canonical pda address can be used to create the account (first bump that generates a valid pda address)
  23. require(bump == _bump, 'INVALID_BUMP');
  24. // The PageVisits instance is initialized with pageVisits set to zero and bump set to the bump passed to the constructor
  25. accountData = PageVisits(0, bump);
  26. }
  27. // Increments the pageVisits by one.
  28. function incrementPageVisits() public {
  29. accountData.pageVisits += 1;
  30. }
  31. // Returns the accountData (pageVisits and bump) stored on the account
  32. function get() public view returns (PageVisits) {
  33. return accountData;
  34. }
  35. }