test.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. const addressDataBuffer = addressData.toBuffer();
  50. console.log(`Address data buffer length: ${addressDataBuffer.length}`)
  51. let ix = new TransactionInstruction({
  52. keys: [
  53. {pubkey: payer.publicKey, isSigner: true, isWritable: true},
  54. {pubkey: newKeypair.publicKey, isSigner: true, isWritable: true},
  55. {pubkey: SystemProgram.programId, isSigner: false, isWritable: false}
  56. ],
  57. programId: program.publicKey,
  58. data: addressDataBuffer,
  59. });
  60. await sendAndConfirmTransaction(
  61. connection,
  62. new Transaction().add(ix),
  63. [payer, newKeypair]
  64. );
  65. });
  66. });