transfer-sol.sol 1.2 KB

123456789101112131415161718192021222324252627282930
  1. import "./system_instruction.sol";
  2. @program_id("F1ipperKF9EfD821ZbbYjS319LXYiBmjhzkkf5a26rC")
  3. contract transfer_sol {
  4. @payer(payer) // payer to create new data account
  5. constructor(address payer) {
  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. function transferSolWithCpi(address from, address to, uint64 lamports) public view {
  10. // CPI to transfer SOL using "system_instruction" library
  11. SystemInstruction.transfer(from, to, lamports);
  12. }
  13. // Transfer SOL from program owned account to another address by directly modifying the account data lamports
  14. // This approach only works for accounts owned by the program itself (ex. the dataAccount created in the constructor)
  15. function transferSolWithProgram(uint64 lamports) public {
  16. AccountInfo from = tx.accounts[0]; // first account must be an account owned by the program
  17. AccountInfo to = tx.accounts[1]; // second account must be the intended recipient
  18. print("From: {:}".format(from.key));
  19. print("To: {:}".format(to.key));
  20. from.lamports -= lamports;
  21. to.lamports += lamports;
  22. }
  23. }