create.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { Buffer } from 'node:buffer';
  2. import { PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js';
  3. import { MyInstruction, closeAccountSchema } from '.';
  4. export class Create {
  5. instruction: MyInstruction;
  6. name: string;
  7. constructor(props: { instruction: MyInstruction; name: string }) {
  8. this.instruction = props.instruction;
  9. this.name = props.name;
  10. }
  11. toBuffer() {
  12. const textBuffer = Buffer.alloc(64);
  13. const buffer = Buffer.alloc(1000);
  14. textBuffer.write('foobarbaz', 0, 'utf-8');
  15. closeAccountSchema.encode(
  16. {
  17. CreateUser: Array.from(textBuffer),
  18. },
  19. buffer,
  20. );
  21. return buffer.subarray(0, closeAccountSchema.getSpan(buffer));
  22. }
  23. }
  24. export function createCreateUserInstruction(payer: PublicKey, target: PublicKey, programId: PublicKey, name: string): TransactionInstruction {
  25. const instructionObject = new Create({
  26. instruction: MyInstruction.CreateUser,
  27. name,
  28. });
  29. const seed = 'USER';
  30. const seedBytes = new Uint8Array(seed.split('').map((char) => char.charCodeAt(0)));
  31. const [pda, _] = PublicKey.findProgramAddressSync([seedBytes, payer.toBuffer()], programId);
  32. const data = instructionObject.toBuffer();
  33. const ix = new TransactionInstruction({
  34. keys: [
  35. { pubkey: payer, isSigner: true, isWritable: true },
  36. { pubkey: pda, isSigner: false, isWritable: true },
  37. { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
  38. ],
  39. programId: programId,
  40. data,
  41. });
  42. return ix;
  43. }