instruction.ts 1.5 KB

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