create.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { Buffer } from 'node:buffer';
  2. import { type PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js';
  3. import * as borsh from 'borsh';
  4. import { ReallocInstruction } from './instruction';
  5. export class Create {
  6. instruction: ReallocInstruction;
  7. name: string;
  8. house_number: number;
  9. street: string;
  10. city: string;
  11. constructor(props: {
  12. instruction: ReallocInstruction;
  13. name: string;
  14. house_number: number;
  15. street: string;
  16. city: string;
  17. }) {
  18. this.instruction = props.instruction;
  19. this.name = props.name;
  20. this.house_number = props.house_number;
  21. this.street = props.street;
  22. this.city = props.city;
  23. }
  24. toBuffer() {
  25. return Buffer.from(borsh.serialize(CreateSchema, this));
  26. }
  27. static fromBuffer(buffer: Buffer) {
  28. return borsh.deserialize(CreateSchema, Create, buffer);
  29. }
  30. }
  31. export const CreateSchema = new Map([
  32. [
  33. Create,
  34. {
  35. kind: 'struct',
  36. fields: [
  37. ['instruction', 'u8'],
  38. ['name', 'string'],
  39. ['house_number', 'u8'],
  40. ['street', 'string'],
  41. ['city', 'string'],
  42. ],
  43. },
  44. ],
  45. ]);
  46. export function createCreateInstruction(
  47. target: PublicKey,
  48. payer: PublicKey,
  49. programId: PublicKey,
  50. name: string,
  51. house_number: number,
  52. street: string,
  53. city: string,
  54. ): TransactionInstruction {
  55. const instructionObject = new Create({
  56. instruction: ReallocInstruction.Create,
  57. name,
  58. house_number,
  59. street,
  60. city,
  61. });
  62. const ix = new TransactionInstruction({
  63. keys: [
  64. { pubkey: target, isSigner: false, isWritable: true },
  65. { pubkey: payer, isSigner: true, isWritable: true },
  66. { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
  67. ],
  68. programId: programId,
  69. data: instructionObject.toBuffer(),
  70. });
  71. return ix;
  72. }