parsers.test.ts 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import {
  2. accountNode,
  3. fieldDiscriminatorNode,
  4. instructionArgumentNode,
  5. instructionNode,
  6. numberTypeNode,
  7. numberValueNode,
  8. programNode,
  9. rootNode,
  10. sizePrefixTypeNode,
  11. stringTypeNode,
  12. structFieldTypeNode,
  13. structTypeNode,
  14. } from '@codama/nodes';
  15. import { describe, expect, test } from 'vitest';
  16. import { parseAccountData, parseInstructionData } from '../src';
  17. import { hex } from './_setup';
  18. describe('parseAccountData', () => {
  19. test('it parses some account data from a root node', () => {
  20. const root = rootNode(
  21. programNode({
  22. accounts: [
  23. accountNode({
  24. data: structTypeNode([
  25. structFieldTypeNode({
  26. defaultValue: numberValueNode(9),
  27. name: 'discriminator',
  28. type: numberTypeNode('u8'),
  29. }),
  30. structFieldTypeNode({
  31. name: 'firstname',
  32. type: sizePrefixTypeNode(stringTypeNode('utf8'), numberTypeNode('u16')),
  33. }),
  34. structFieldTypeNode({
  35. name: 'age',
  36. type: numberTypeNode('u8'),
  37. }),
  38. ]),
  39. discriminators: [fieldDiscriminatorNode('discriminator')],
  40. name: 'myAccount',
  41. }),
  42. ],
  43. name: 'myProgram',
  44. publicKey: '1111',
  45. }),
  46. );
  47. const result = parseAccountData(root, hex('090500416c6963652a'));
  48. expect(result).toStrictEqual({
  49. data: { age: 42, discriminator: 9, firstname: 'Alice' },
  50. path: [root, root.program, root.program.accounts[0]],
  51. });
  52. });
  53. });
  54. describe('parseInstructionData', () => {
  55. test('it parses some instruction data from a root node', () => {
  56. const root = rootNode(
  57. programNode({
  58. instructions: [
  59. instructionNode({
  60. arguments: [
  61. instructionArgumentNode({
  62. defaultValue: numberValueNode(9),
  63. name: 'discriminator',
  64. type: numberTypeNode('u8'),
  65. }),
  66. instructionArgumentNode({
  67. name: 'firstname',
  68. type: sizePrefixTypeNode(stringTypeNode('utf8'), numberTypeNode('u16')),
  69. }),
  70. instructionArgumentNode({
  71. name: 'age',
  72. type: numberTypeNode('u8'),
  73. }),
  74. ],
  75. discriminators: [fieldDiscriminatorNode('discriminator')],
  76. name: 'myInstruction',
  77. }),
  78. ],
  79. name: 'myProgram',
  80. publicKey: '1111',
  81. }),
  82. );
  83. const result = parseInstructionData(root, hex('090500416c6963652a'));
  84. expect(result).toStrictEqual({
  85. data: { age: 42, discriminator: 9, firstname: 'Alice' },
  86. path: [root, root.program, root.program.instructions[0]],
  87. });
  88. });
  89. });