test.ts 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import {
  2. Connection,
  3. Keypair,
  4. PublicKey,
  5. sendAndConfirmTransaction,
  6. SystemProgram,
  7. Transaction,
  8. TransactionInstruction,
  9. } from '@solana/web3.js';
  10. import * as borsh from "borsh";
  11. import { Buffer } from "buffer";
  12. function createKeypairFromFile(path: string): Keypair {
  13. return Keypair.fromSecretKey(
  14. Buffer.from(JSON.parse(require('fs').readFileSync(path, "utf-8")))
  15. )
  16. };
  17. describe("Account Data!", () => {
  18. const connection = new Connection(`http://localhost:8899`, 'confirmed');
  19. const payer = createKeypairFromFile(require('os').homedir() + '/.config/solana/id.json');
  20. const PROGRAM_ID: PublicKey = new PublicKey(
  21. "BCw7MQWBugruuYgno5crGUGFNufqGJbPpzZevhRRRQAu"
  22. );
  23. class Assignable {
  24. constructor(properties) {
  25. Object.keys(properties).map((key) => {
  26. return (this[key] = properties[key]);
  27. });
  28. };
  29. };
  30. class AddressInfo extends Assignable {
  31. toBuffer() { return Buffer.from(borsh.serialize(AddressInfoSchema, this)) }
  32. static fromBuffer(buffer: Buffer) {
  33. return borsh.deserialize(AddressInfoSchema, AddressInfo, buffer);
  34. };
  35. };
  36. const AddressInfoSchema = new Map([
  37. [ AddressInfo, {
  38. kind: 'struct',
  39. fields: [
  40. ['name', 'string'],
  41. ['house_number', 'u8'],
  42. ['street', 'string'],
  43. ['city', 'string'],
  44. ],
  45. }]
  46. ]);
  47. const addressInfoAccount = Keypair.generate();
  48. it("Create the address info account", async () => {
  49. console.log(`Payer Address : ${payer.publicKey}`);
  50. console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`);
  51. let ix = new TransactionInstruction({
  52. keys: [
  53. {pubkey: addressInfoAccount.publicKey, isSigner: true, isWritable: true},
  54. {pubkey: payer.publicKey, isSigner: true, isWritable: true},
  55. {pubkey: SystemProgram.programId, isSigner: false, isWritable: false}
  56. ],
  57. programId: PROGRAM_ID,
  58. data: (
  59. new AddressInfo({
  60. name: "Joe C",
  61. house_number: 136,
  62. street: "Mile High Dr.",
  63. city: "Solana Beach",
  64. })
  65. ).toBuffer(),
  66. });
  67. await sendAndConfirmTransaction(
  68. connection,
  69. new Transaction().add(ix),
  70. [payer, addressInfoAccount]
  71. );
  72. });
  73. it("Read the new account's data", async () => {
  74. const accountInfo = await connection.getAccountInfo(addressInfoAccount.publicKey);
  75. const readAddressInfo = AddressInfo.fromBuffer(accountInfo.data);
  76. console.log(`Name : ${readAddressInfo.name}`);
  77. console.log(`House Num: ${readAddressInfo.house_number}`);
  78. console.log(`Street : ${readAddressInfo.street}`);
  79. console.log(`City : ${readAddressInfo.city}`);
  80. });
  81. });