transfer-sol.sol 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  1. import "../libraries/system_instruction.sol";
  2. @program_id("F1ipperKF9EfD821ZbbYjS319LXYiBmjhzkkf5a26rC")
  3. contract transfer_sol {
  4. @payer(payer) // payer to create new data account
  5. constructor() {
  6. // No data is stored in the account in this example
  7. }
  8. // Transfer SOL from one account to another using CPI (Cross Program Invocation) to the System program
  9. @mutableSigner(sender)
  10. @mutableAccount(recipient)
  11. function transferSolWithCpi(uint64 lamports) external {
  12. // CPI to transfer SOL using "system_instruction" library
  13. SystemInstruction.transfer(tx.accounts.sender.key, tx.accounts.recipient.key, lamports);
  14. }
  15. // Transfer SOL from program owned account to another address by directly modifying the account data lamports
  16. // This approach only works for accounts owned by the program itself (ex. the dataAccount created in the constructor)
  17. @mutableAccount(sender)
  18. @mutableAccount(recipient)
  19. function transferSolWithProgram(uint64 lamports) external {
  20. AccountInfo from = tx.accounts.sender; // first account must be an account owned by the program
  21. AccountInfo to = tx.accounts.recipient; // second account must be the intended recipient
  22. print("From: {:}".format(from.key));
  23. print("To: {:}".format(to.key));
  24. from.lamports -= lamports;
  25. to.lamports += lamports;
  26. }
  27. }