instruction.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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: { instruction: InstructionType; amount: number }) {
  12. this.instruction = props.instruction;
  13. this.amount = props.amount;
  14. }
  15. toBuffer() {
  16. return Buffer.from(borsh.serialize(TransferInstructionSchema, this));
  17. }
  18. static fromBuffer(buffer: Buffer) {
  19. return borsh.deserialize(TransferInstructionSchema, TransferInstruction, buffer);
  20. }
  21. }
  22. export const TransferInstructionSchema = new Map([
  23. [
  24. TransferInstruction,
  25. {
  26. kind: 'struct',
  27. fields: [
  28. ['instruction', 'u8'],
  29. ['amount', 'u64'],
  30. ],
  31. },
  32. ],
  33. ]);
  34. export function createTransferInstruction(
  35. payerPubkey: PublicKey,
  36. recipientPubkey: PublicKey,
  37. programId: PublicKey,
  38. instruction: InstructionType,
  39. amount: number,
  40. systemProgramId?: boolean,
  41. ): TransactionInstruction {
  42. const instructionObject = new TransferInstruction({
  43. instruction,
  44. amount,
  45. });
  46. const keys = [
  47. { pubkey: payerPubkey, isSigner: true, isWritable: true },
  48. { pubkey: recipientPubkey, isSigner: false, isWritable: true },
  49. ];
  50. if (systemProgramId) {
  51. keys.push({
  52. pubkey: SystemProgram.programId,
  53. isSigner: false,
  54. isWritable: false,
  55. });
  56. }
  57. const ix = new TransactionInstruction({
  58. keys: keys,
  59. programId,
  60. data: instructionObject.toBuffer(),
  61. });
  62. return ix;
  63. }