test.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {
  2. Connection,
  3. Keypair,
  4. sendAndConfirmTransaction,
  5. SystemProgram,
  6. Transaction,
  7. TransactionInstruction,
  8. } from '@solana/web3.js';
  9. import * as borsh from "borsh";
  10. import { Buffer } from "buffer";
  11. function createKeypairFromFile(path: string): Keypair {
  12. return Keypair.fromSecretKey(
  13. Buffer.from(JSON.parse(require('fs').readFileSync(path, "utf-8")))
  14. )
  15. };
  16. describe("Create a system account", async () => {
  17. const connection = new Connection(`http://localhost:8899`, 'confirmed');
  18. const payer = createKeypairFromFile(require('os').homedir() + '/.config/solana/id.json');
  19. const program = createKeypairFromFile('./program/target/so/program-keypair.json');
  20. class Assignable {
  21. constructor(properties) {
  22. Object.keys(properties).map((key) => {
  23. return (this[key] = properties[key]);
  24. });
  25. };
  26. };
  27. class AddressData extends Assignable {
  28. toBuffer() {
  29. return Buffer.from(borsh.serialize(AddressDataSchema, this));
  30. }
  31. };
  32. const AddressDataSchema = new Map([
  33. [
  34. AddressData, {
  35. kind: 'struct',
  36. fields: [
  37. ['name', 'string'],
  38. ['address', 'string'],
  39. ]
  40. }
  41. ]
  42. ]);
  43. it("Create the account", async () => {
  44. const newKeypair = Keypair.generate();
  45. const addressData = new AddressData({
  46. name: "Marcus",
  47. address: "123 Main St. San Francisco, CA"
  48. });
  49. // We're just going to serialize our object here so we can check
  50. // the size on the client side against the program logs
  51. //
  52. const addressDataBuffer = addressData.toBuffer();
  53. console.log(`Address data buffer length: ${addressDataBuffer.length}`)
  54. let ix = new TransactionInstruction({
  55. keys: [
  56. {pubkey: payer.publicKey, isSigner: true, isWritable: true},
  57. {pubkey: newKeypair.publicKey, isSigner: true, isWritable: true},
  58. {pubkey: SystemProgram.programId, isSigner: false, isWritable: false}
  59. ],
  60. programId: program.publicKey,
  61. data: addressDataBuffer,
  62. });
  63. await sendAndConfirmTransaction(
  64. connection,
  65. new Transaction().add(ix),
  66. [payer, newKeypair]
  67. );
  68. });
  69. });