All files / src/util transform.js

100% Statements 103/103
100% Branches 102/102
100% Functions 25/25
100% Lines 94/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252              14x 128x 91x   37x 1x   36x     80x   48x     81x 81x 81x 2x     79x 127x 35x       44x         115x 115x 46x 2x 2x 1x 1x 1x   2x         44x               44x       51x 51x 51x 3x   48x 23x                 25x 25x 2x     24x       52x 52x 24x 1x 1x 1x         23x             24x       50x 50x 50x       28x           22x 22x           1x 2x               21x 62x 62x 24x         3x   3x           1x     2x               2x 3x 2x           21x             21x     14x       24x 24x 23x       24x 1x       24x           3x 3x 2x       3x 1x       3x           14x 14x     14x       12x 12x 1x 11x 10x   12x           6x 6x 1x 5x 4x   6x        
/**
 * @file transform protobuf
 * @author atom-yang
 */
import { base58, decodeAddressRep } from './utils';
import { inputAddressFormatter } from './formatters';
 
const isWrappedBytes = (resolvedType, name) => {
  if (!resolvedType.name || resolvedType.name !== name) {
    return false;
  }
  if (!resolvedType.fieldsArray || resolvedType.fieldsArray.length !== 1) {
    return false;
  }
  return resolvedType.fieldsArray[0].type === 'bytes';
};
 
const isAddress = resolvedType => isWrappedBytes(resolvedType, 'Address');
 
const isHash = resolvedType => isWrappedBytes(resolvedType, 'Hash');
 
export function transform(inputType, origin, transformers = []) {
  const fieldsLength = (inputType.fieldsArray || []).length;
  let result = origin;
  if (fieldsLength === 0) {
    return origin;
  }
  // eslint-disable-next-line no-restricted-syntax
  for (const { filter, transformer } of transformers) {
    if (filter(inputType) && origin) {
      return transformer(origin);
    }
  }
  // eslint-disable-next-line no-restricted-syntax
  Object.keys(inputType.fields).forEach(field => {
    const {
      rule,
      name,
      resolvedType
    } = inputType.fields[field];
    if (resolvedType) {
      if (rule && rule === 'repeated') {
        let value = origin[name];
        if (value && Array.isArray(value)) {
          value = value
            .filter(v => v !== null && v !== undefined)
            .map(item => transform(resolvedType, item, transformers));
        }
        result = {
          ...result,
          [name]: value
        };
      } else {
        result = {
          ...result,
          [name]: origin[name] !== null && origin[name] !== undefined
            ? transform(resolvedType, origin[name], transformers) : origin[name]
        };
      }
    }
  });
  return result;
}
 
export function transformMapToArray(inputType, origin) {
  const fieldsLength = inputType.fieldsArray ? inputType.fieldsArray.length : 0;
  let result = origin;
  if (!origin) {
    return origin;
  }
  if (fieldsLength === 0 || (fieldsLength === 1 && !inputType.fieldsArray[0].resolvedType)) {
    return origin;
  }
  // Params which satisfy address or hash format satisfy above first.
  // if (isAddress(inputType) || isHash(inputType)) {
  //   return origin;
  // }
  const {
    fields,
    options = {}
  } = inputType;
  if (fieldsLength === 2 && fields.value && fields.key && options.map_entry === true) {
    return Object.keys(origin).map(key => ({ key, value: origin[key] }));
  }
  // eslint-disable-next-line no-restricted-syntax
  Object.keys(inputType.fields).forEach(field => {
    const {
      name,
      resolvedType
    } = inputType.fields[field];
    if (resolvedType) {
      if (origin[name] && Array.isArray(origin[name])) {
        let value = origin[name];
        value = value.map(item => transformMapToArray(resolvedType, item));
        result = {
          ...result,
          [name]: value
        };
      } else {
        result = {
          ...result,
          [name]: transformMapToArray(resolvedType, origin[name])
        };
      }
    }
  });
  return result;
}
 
export function transformArrayToMap(inputType, origin) {
  const fieldsLength = (inputType.fieldsArray || []).length;
  let result = origin;
  if (
    fieldsLength === 0
    || (fieldsLength === 1 && !inputType.fieldsArray[0].resolvedType)
  ) {
    return origin;
  }
  // Params which satisfy address or hash format satisfy above first.
  // if (isAddress(inputType) || isHash(inputType)) {
  //   return origin;
  // }
  const { fields, options = {} } = inputType;
  if (
    fieldsLength === 2
    && fields.value
    && fields.key
    && options.map_entry === true
  ) {
    return origin.reduce(
      (acc, v) => ({
        ...acc,
        [v.key]: v.value,
      }),
      {}
    );
  }
  // eslint-disable-next-line no-restricted-syntax
  Object.keys(fields).forEach(field => {
    const { name, resolvedType } = fields[field];
    if (resolvedType && origin !== null && origin !== undefined) {
      if (origin[name] && Array.isArray(origin[name])) {
        const {
          fieldsArray = [],
          fields: resolvedFields,
          options: resolvedOptions = {},
        } = resolvedType;
        // eslint-disable-next-line max-len
        if (
          fieldsArray.length === 2
          && resolvedFields.value
          && resolvedFields.key
          && resolvedOptions.map_entry === true
        ) {
          result = {
            ...result,
            [name]: origin[name].reduce(
              (acc, v) => ({
                ...acc,
                [v.key]: v.value,
              }),
              {}
            ),
          };
        } else {
          let value = origin[name];
          value = value.map(item => transformArrayToMap(resolvedType, item));
          result = {
            ...result,
            [name]: value,
          };
        }
      } else {
        result = {
          ...result,
          [name]: transformArrayToMap(resolvedType, origin[name]),
        };
      }
    }
  });
  return result;
}
 
export const INPUT_TRANSFORMERS = [
  {
    filter: isAddress,
    transformer: origin => {
      let result = origin;
      if (typeof origin === 'string') {
        result = {
          value: Buffer.from(decodeAddressRep(inputAddressFormatter(origin)), 'hex')
        };
      }
      if (Array.isArray(origin)) {
        result = origin.map(h => ({
          value: Buffer.from(decodeAddressRep(inputAddressFormatter(h)), 'hex')
        }));
      }
      return result;
    }
  },
  {
    filter: isHash,
    transformer: origin => {
      let result = origin;
      if (typeof origin === 'string') {
        result = {
          value: Buffer.from(origin.replace('0x', ''), 'hex')
        };
      }
      if (Array.isArray(origin)) {
        result = origin.map(h => ({
          value: Buffer.from(h.replace('0x', ''), 'hex')
        }));
      }
      return result;
    }
  },
];
 
export function encodeAddress(str) {
  const buf = Buffer.from(str, 'base64');
  return base58.encode(buf);
}
 
export const OUTPUT_TRANSFORMERS = [
  {
    filter: isAddress,
    transformer: origin => {
      let result = origin;
      if (Array.isArray(result)) {
        result = result.map(h => encodeAddress(h.value));
      } else if (typeof result !== 'string') {
        result = encodeAddress(result.value);
      }
      return result;
    }
  },
  {
    filter: isHash,
    transformer: origin => {
      let result = origin;
      if (Array.isArray(result)) {
        result = result.map(h => Buffer.from(h.value, 'base64').toString('hex'));
      } else if (typeof result !== 'string') {
        result = Buffer.from(result.value, 'base64').toString('hex');
      }
      return result;
    }
  },
];