coder-accounts.spec.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import * as assert from "assert";
  2. import { createNodeArray } from "typescript";
  3. import { BorshCoder } from "../src";
  4. import { sha256 } from "js-sha256";
  5. import { ACCOUNT_DISCRIMINATOR_SIZE } from "../src/coder/borsh/accounts";
  6. describe("coder.accounts", () => {
  7. test("Can encode and decode user-defined accounts, including those with consecutive capital letters", () => {
  8. const idl = {
  9. version: "0.0.0",
  10. name: "basic_0",
  11. instructions: [
  12. {
  13. name: "initialize",
  14. accounts: [],
  15. args: [],
  16. },
  17. ],
  18. accounts: [
  19. {
  20. name: "MemberDAO",
  21. type: {
  22. kind: "struct" as const,
  23. fields: [
  24. {
  25. name: "name",
  26. type: "string" as const,
  27. },
  28. ],
  29. },
  30. },
  31. ],
  32. };
  33. const coder = new BorshCoder(idl);
  34. const memberDAO = {
  35. name: "test",
  36. };
  37. coder.accounts.encode("MemberDAO", memberDAO).then((encoded) => {
  38. // start of encoded account = account discriminator
  39. assert.deepEqual(
  40. encoded.subarray(0, ACCOUNT_DISCRIMINATOR_SIZE),
  41. Buffer.from(sha256.digest("account:MemberDAO")).subarray(
  42. 0,
  43. ACCOUNT_DISCRIMINATOR_SIZE
  44. )
  45. );
  46. assert.deepEqual(coder.accounts.decode("MemberDAO", encoded), memberDAO);
  47. });
  48. });
  49. });