instruction.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import * as borsh from "borsh";
  2. import { Buffer } from "buffer";
  3. import {
  4. PublicKey,
  5. SystemProgram,
  6. TransactionInstruction
  7. } from '@solana/web3.js';
  8. export enum InstructionType {
  9. CpiTransfer,
  10. ProgramTransfer,
  11. }
  12. export class TransferInstruction {
  13. instruction: InstructionType;
  14. amount: number;
  15. constructor(props: {
  16. instruction: InstructionType,
  17. amount: number,
  18. }) {
  19. this.instruction = props.instruction;
  20. this.amount = props.amount;
  21. }
  22. toBuffer() {
  23. return Buffer.from(borsh.serialize(TransferInstructionSchema, this))
  24. };
  25. static fromBuffer(buffer: Buffer) {
  26. return borsh.deserialize(TransferInstructionSchema, TransferInstruction, buffer);
  27. };
  28. };
  29. export const TransferInstructionSchema = new Map([
  30. [ TransferInstruction, {
  31. kind: 'struct',
  32. fields: [
  33. ['instruction', 'u8'],
  34. ['amount', 'u64'],
  35. ],
  36. }]
  37. ]);
  38. export function createTransferInstruction(
  39. payerPubkey: PublicKey,
  40. recipientPubkey: PublicKey,
  41. programId: PublicKey,
  42. instruction: InstructionType,
  43. amount: number,
  44. ): TransactionInstruction {
  45. const instructionObject = new TransferInstruction({
  46. instruction,
  47. amount,
  48. });
  49. const ix = new TransactionInstruction({
  50. keys: [
  51. {pubkey: payerPubkey, isSigner: true, isWritable: true},
  52. {pubkey: recipientPubkey, isSigner: false, isWritable: true},
  53. {pubkey: SystemProgram.programId, isSigner: false, isWritable: false}
  54. ],
  55. programId,
  56. data: instructionObject.toBuffer(),
  57. });
  58. return ix;
  59. }