aboutsummaryrefslogtreecommitdiffstats
path: root/packages/utils/src/abi_encoder/evm_data_types/address.ts
blob: 52fc8e7b9ff5535f13ef4eb42c518ef04784b5a3 (plain) (blame)
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
/* tslint:disable prefer-function-over-method */
import { DataItem } from 'ethereum-types';
import * as ethUtil from 'ethereumjs-util';
import * as _ from 'lodash';

import { AbstractDataTypes, DataTypeFactory } from '../abstract_data_types';
import { RawCalldata } from '../calldata';
import * as Constants from '../utils/constants';

export class Address extends AbstractDataTypes.Blob {
    public static ERROR_MESSAGE_ADDRESS_MUST_START_WITH_0X = "Address must start with '0x'";
    public static ERROR_MESSAGE_ADDRESS_MUST_BE_20_BYTES = 'Address must be 20 bytes';
    private static readonly _SIZE_KNOWN_AT_COMPILE_TIME: boolean = true;
    private static readonly _ADDRESS_SIZE_IN_BYTES = 20;
    private static readonly _DECODED_ADDRESS_OFFSET_IN_BYTES = Constants.EVM_WORD_WIDTH_IN_BYTES -
    Address._ADDRESS_SIZE_IN_BYTES;

    public static matchType(type: string): boolean {
        return type === 'address';
    }

    public constructor(dataItem: DataItem, dataTypeFactory: DataTypeFactory) {
        super(dataItem, dataTypeFactory, Address._SIZE_KNOWN_AT_COMPILE_TIME);
        if (!Address.matchType(dataItem.type)) {
            throw new Error(`Tried to instantiate Address with bad input: ${dataItem}`);
        }
    }

    public getSignature(): string {
        return 'address';
    }

    public encodeValue(value: string): Buffer {
        if (!_.startsWith(value, '0x')) {
            throw new Error(Address.ERROR_MESSAGE_ADDRESS_MUST_START_WITH_0X);
        }
        const valueBuf = ethUtil.toBuffer(value);
        if (valueBuf.byteLength !== Address._ADDRESS_SIZE_IN_BYTES) {
            throw new Error(Address.ERROR_MESSAGE_ADDRESS_MUST_BE_20_BYTES);
        }
        const encodedValueBuf = ethUtil.setLengthLeft(valueBuf, Constants.EVM_WORD_WIDTH_IN_BYTES);
        return encodedValueBuf;
    }

    public decodeValue(calldata: RawCalldata): string {
        const valueBufPadded = calldata.popWord();
        const valueBuf = valueBufPadded.slice(Address._DECODED_ADDRESS_OFFSET_IN_BYTES);
        const value = ethUtil.bufferToHex(valueBuf);
        return value;
    }
}