Skip to content

Commit

Permalink
refactor: extract to internal methods
Browse files Browse the repository at this point in the history
  • Loading branch information
CJ42 committed Nov 9, 2023
1 parent 8b1d1ff commit 380513a
Showing 1 changed file with 25 additions and 23 deletions.
48 changes: 25 additions & 23 deletions src/lib/decodeData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,32 +33,41 @@ import { decodeKeyValue, encodeArrayKey } from './utils';
const tupleValueTypesRegex = /bytes(\d+)/;
const valueContentsBytesRegex = /Bytes(\d+)/;

export const isValidTuple = (valueType: string, valueContent: string) => {
if (valueType.length <= 2 && valueContent.length <= 2) {
const isValidTupleDefinition = (tupleContent: string): boolean => {
if (tupleContent.length <= 2) {
return false;
}

if (
valueType[0] !== '(' &&
valueType[valueType.length - 1] !== ')' &&
valueContent[0] !== '(' &&
valueContent[valueContent.length - 1] !== ')'
) {
if (tupleContent[0] !== '(' && tupleContent.at(-1) !== ')') {
return false;
}

// At this stage, we can assume the user is trying to use a tuple, let's throw errors instead of returning
// false
return true;
};

let valueTypeToDecode = valueType;
const extractValueTypesFromTuple = (tupleContent: string): string[] => {
let valueTypeToDecode = tupleContent;

if (valueType.includes(COMPACT_BYTES_ARRAY_STRING)) {
valueTypeToDecode = valueType.replace(COMPACT_BYTES_ARRAY_STRING, '');
if (tupleContent.includes(COMPACT_BYTES_ARRAY_STRING)) {
valueTypeToDecode = tupleContent.replace(COMPACT_BYTES_ARRAY_STRING, '');
}

const valueTypeParts = valueTypeToDecode
return valueTypeToDecode
.substring(1, valueTypeToDecode.length - 1)
.split(',');
};

export const isValidTuple = (valueType: string, valueContent: string) => {
if (
!isValidTupleDefinition(valueType) ||
!isValidTupleDefinition(valueContent)
) {
return false;
}

// At this stage, we can assume the user is trying to use a tuple, let's throw errors instead of returning
// false

const valueTypeParts = extractValueTypesFromTuple(valueType);

const valueContentParts = valueContent
.substring(1, valueContent.length - 1)
Expand Down Expand Up @@ -139,15 +148,8 @@ export const decodeTupleKeyValue = (
): Array<string> => {
// We assume data has already been validated at this stage

let valueTypeToDecode = valueType;

if (valueType.includes('[CompactBytesArray')) {
valueTypeToDecode = valueType.replace(COMPACT_BYTES_ARRAY_STRING, '');
}
const valueTypeParts = extractValueTypesFromTuple(valueType);

const valueTypeParts = valueTypeToDecode
.substring(1, valueTypeToDecode.length - 1)
.split(',');
const valueContentParts = valueContent
.substring(1, valueContent.length - 1)
.split(',');
Expand Down

0 comments on commit 380513a

Please sign in to comment.