UNPKG

2.88 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.StringDataType = void 0;
4const ethereum_types_1 = require("ethereum-types");
5const ethUtil = require("ethereumjs-util");
6const blob_1 = require("../abstract_data_types/types/blob");
7const constants_1 = require("../utils/constants");
8class StringDataType extends blob_1.AbstractBlobDataType {
9 constructor(dataItem, dataTypeFactory) {
10 super(dataItem, dataTypeFactory, StringDataType._SIZE_KNOWN_AT_COMPILE_TIME);
11 if (!StringDataType.matchType(dataItem.type)) {
12 throw new Error(`Tried to instantiate String with bad input: ${dataItem}`);
13 }
14 }
15 static matchType(type) {
16 return type === ethereum_types_1.SolidityTypes.String;
17 }
18 // Disable prefer-function-over-method for inherited abstract methods.
19 /* tslint:disable prefer-function-over-method */
20 encodeValue(value) {
21 // Encoded value is of the form: <length><value>, with each field padded to be word-aligned.
22 // 1/3 Construct the value
23 const valueBuf = Buffer.from(value);
24 const valueLengthInBytes = valueBuf.byteLength;
25 const wordsToStoreValuePadded = Math.ceil(valueLengthInBytes / constants_1.constants.EVM_WORD_WIDTH_IN_BYTES);
26 const bytesToStoreValuePadded = wordsToStoreValuePadded * constants_1.constants.EVM_WORD_WIDTH_IN_BYTES;
27 const valueBufPadded = ethUtil.setLengthRight(valueBuf, bytesToStoreValuePadded);
28 // 2/3 Construct the length
29 const lengthBuf = ethUtil.toBuffer(valueLengthInBytes);
30 const lengthBufPadded = ethUtil.setLengthLeft(lengthBuf, constants_1.constants.EVM_WORD_WIDTH_IN_BYTES);
31 // 3/3 Combine length and value
32 const encodedValue = Buffer.concat([lengthBufPadded, valueBufPadded]);
33 return encodedValue;
34 }
35 decodeValue(calldata) {
36 // Encoded value is of the form: <length><value>, with each field padded to be word-aligned.
37 // 1/2 Decode length
38 const lengthBufPadded = calldata.popWord();
39 const lengthHexPadded = ethUtil.bufferToHex(lengthBufPadded);
40 const length = parseInt(lengthHexPadded, constants_1.constants.HEX_BASE);
41 // 2/2 Decode value
42 const wordsToStoreValuePadded = Math.ceil(length / constants_1.constants.EVM_WORD_WIDTH_IN_BYTES);
43 const valueBufPadded = calldata.popWords(wordsToStoreValuePadded);
44 const valueBuf = valueBufPadded.slice(0, length);
45 const value = valueBuf.toString('UTF-8');
46 return value;
47 }
48 getDefaultValue() {
49 return StringDataType._DEFAULT_VALUE;
50 }
51 getSignatureType() {
52 return ethereum_types_1.SolidityTypes.String;
53 }
54}
55exports.StringDataType = StringDataType;
56StringDataType._SIZE_KNOWN_AT_COMPILE_TIME = false;
57StringDataType._DEFAULT_VALUE = '';
58//# sourceMappingURL=string.js.map
\No newline at end of file