Skip to content

Commit

Permalink
feat: add VersionedMessage.deserializeMessageVersion utility function (
Browse files Browse the repository at this point in the history
  • Loading branch information
jstarry authored Aug 29, 2022
1 parent 757e46c commit ada493f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
15 changes: 12 additions & 3 deletions web3.js/src/message/versioned.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,26 @@ import {MessageV0} from './v0';
export type VersionedMessage = Message | MessageV0;
// eslint-disable-next-line no-redeclare
export const VersionedMessage = {
deserialize: (serializedMessage: Uint8Array): VersionedMessage => {
deserializeMessageVersion(serializedMessage: Uint8Array): 'legacy' | number {
const prefix = serializedMessage[0];
const maskedPrefix = prefix & VERSION_PREFIX_MASK;

// if the highest bit of the prefix is not set, the message is not versioned
if (maskedPrefix === prefix) {
return Message.from(serializedMessage);
return 'legacy';
}

// the lower 7 bits of the prefix indicate the message version
const version = maskedPrefix;
return maskedPrefix;
},

deserialize: (serializedMessage: Uint8Array): VersionedMessage => {
const version =
VersionedMessage.deserializeMessageVersion(serializedMessage);
if (version === 'legacy') {
return Message.from(serializedMessage);
}

if (version === 0) {
return MessageV0.deserialize(serializedMessage);
} else {
Expand Down
28 changes: 28 additions & 0 deletions web3.js/test/message-tests/versioned.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import {expect} from 'chai';

import {VersionedMessage} from '../../src/message';

describe('VersionedMessage', () => {
it('deserializeMessageVersion', () => {
const bufferWithLegacyPrefix = new Uint8Array([1]);
expect(
VersionedMessage.deserializeMessageVersion(bufferWithLegacyPrefix),
).to.eq('legacy');

for (const version of [0, 1, 127]) {
const bufferWithVersionPrefix = new Uint8Array([(1 << 7) + version]);
expect(
VersionedMessage.deserializeMessageVersion(bufferWithVersionPrefix),
).to.eq(version);
}
});

it('deserialize failure', () => {
const bufferWithV1Prefix = new Uint8Array([(1 << 7) + 1]);
expect(() => {
VersionedMessage.deserialize(bufferWithV1Prefix);
}).to.throw(
'Transaction message version 1 deserialization is not supported',
);
});
});

0 comments on commit ada493f

Please sign in to comment.