create.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. import { MyInstruction } from '.';
  9. export class Create {
  10. instruction: MyInstruction;
  11. name: string;
  12. constructor(props: { instruction: MyInstruction; name: string }) {
  13. this.instruction = props.instruction;
  14. this.name = props.name;
  15. }
  16. toBuffer() {
  17. return Buffer.from(borsh.serialize(CreateSchema, this));
  18. }
  19. static fromBuffer(buffer: Buffer) {
  20. return borsh.deserialize(CreateSchema, Create, buffer);
  21. }
  22. }
  23. export const CreateSchema = new Map([
  24. [
  25. Create,
  26. {
  27. kind: 'struct',
  28. fields: [
  29. ['instruction', 'u8'],
  30. ['name', 'string'],
  31. ],
  32. },
  33. ],
  34. ]);
  35. export function createCreateUserInstruction(
  36. target: PublicKey,
  37. payer: PublicKey,
  38. programId: PublicKey,
  39. name: string
  40. ): TransactionInstruction {
  41. const instructionObject = new Create({
  42. instruction: MyInstruction.CreateUser,
  43. name,
  44. });
  45. const ix = new TransactionInstruction({
  46. keys: [
  47. { pubkey: target, isSigner: false, isWritable: true },
  48. { pubkey: payer, isSigner: true, isWritable: true },
  49. { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
  50. ],
  51. programId: programId,
  52. data: instructionObject.toBuffer(),
  53. });
  54. return ix;
  55. }