📄 src/web3/utils/strings.test.ts
D-OPEN SOVEREIGN
1import { describe, it, expect } from 'vitest';
2import { bytes4ToString, stringToBytes4 } from './strings';
3
4describe('stringToBytes4', () => {
5  it('encodes a 4-character string into a 0x-prefixed 4-byte hex value', () => {
6    const hex = stringToBytes4('test');
7    expect(hex).toMatch(/^0x[0-9a-f]{8}$/);
8  });
9
10  it('pads shorter strings out to 4 bytes', () => {
11    const hex = stringToBytes4('ab');
12    expect(hex).toHaveLength(10);
13    expect(hex.startsWith('0x')).toBe(true);
14  });
15
16  it('truncates the encoded value to 4 bytes', () => {
17    const hex = stringToBytes4('toolongstring');
18    expect(hex).toHaveLength(10);
19  });
20});
21
22describe('bytes4ToString', () => {
23  it('decodes a hex string back to text, stripping null padding', () => {
24    const hex = stringToBytes4('test');
25    expect(bytes4ToString(hex)).toBe('test');
26  });
27
28  it('round-trips a short, padded value without trailing null characters', () => {
29    const hex = stringToBytes4('ab');
30    const decoded = bytes4ToString(hex);
31    expect(decoded).toBe('ab');
32    expect(decoded).not.toContain('\0');
33  });
34
35  it('accepts hex input missing the 0x prefix', () => {
36    const withPrefix = stringToBytes4('test');
37    const withoutPrefix = withPrefix.slice(2);
38    expect(bytes4ToString(withoutPrefix)).toBe(bytes4ToString(withPrefix));
39  });
40});
41