Skip to content

Commit

Permalink
Allow byte values shorter than specified size (#12)
Browse files Browse the repository at this point in the history
* Allow shorter values for fixed byte types

* Allow shorter values for address type

* Fix padding of address
  • Loading branch information
Mrtenz authored Oct 10, 2022
1 parent cfc6684 commit 75f1aa8
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 5 deletions.
14 changes: 14 additions & 0 deletions src/parsers/address.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,20 @@ describe('address', () => {
'0x0000000000000000000000004bbeeb066ed09b7aed07bf39eee0460dfa261520',
);
});

it('encodes a short address', () => {
expect(
bytesToHex(
address.encode({
type: 'address',
buffer: new Uint8Array(),
value: '0x4bbeeb',
}),
),
).toBe(
'0x00000000000000000000000000000000000000000000000000000000004bbeeb',
);
});
});

describe('decode', () => {
Expand Down
4 changes: 2 additions & 2 deletions src/parsers/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ import { Parser } from './parser';
export const getAddress = (value: BytesLike): Uint8Array => {
const bytesValue = createBytes(value);
assert(
bytesValue.length === 20,
bytesValue.length <= 20,
new ParserError(
`Invalid address value. Expected address to be 20 bytes long, but received ${bytesValue.length} bytes.`,
),
);

return bytesValue;
return padStart(bytesValue, 20);
};

export const address: Parser<BytesLike, string> = {
Expand Down
18 changes: 16 additions & 2 deletions src/parsers/fixed-bytes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,29 @@ describe('fixedBytes', () => {
);
});

it('encodes a value shorter than the specified size', () => {
expect(
bytesToHex(
fixedBytes.encode({
type: 'bytes32',
value: '0xabcdef1234567890',
buffer: new Uint8Array(),
}),
),
).toBe(
'0xabcdef1234567890000000000000000000000000000000000000000000000000',
);
});

it('throws if the length is invalid', () => {
expect(() =>
fixedBytes.encode({
type: 'bytes32',
type: 'bytes1',
value: '0xabcdef123456789',
buffer: new Uint8Array(),
}),
).toThrow(
'Expected a value of length 32, but received a value of length 8.',
'Expected a value of length 1, but received a value of length 8.',
);
});
});
Expand Down
2 changes: 1 addition & 1 deletion src/parsers/fixed-bytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export const fixedBytes: Parser<BytesLike, Uint8Array> = {
const bufferValue = createBytes(value);

assert(
bufferValue.length === length,
bufferValue.length <= length,
new ParserError(
`Expected a value of length ${length}, but received a value of length ${bufferValue.length}.`,
),
Expand Down

0 comments on commit 75f1aa8

Please sign in to comment.