aboutsummaryrefslogtreecommitdiffstats
path: root/packages/contracts/src/utils/asset_proxy_utils.ts
blob: 835f444f6852030703318e08e348fcf80a81d6e1 (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
52
53
54
55
56
57
import { BigNumber } from '@0xproject/utils';
import BN = require('bn.js');
import ethUtil = require('ethereumjs-util');
import * as Web3 from 'web3';

import { AssetProxyId } from './types';

export function encodeAssetProxyId(assetProxyId: AssetProxyId): Buffer {
    const formattedAssetProxyId = new BN(assetProxyId);
    const encodedAssetProxyId = ethUtil.toUnsigned(formattedAssetProxyId);
    return encodedAssetProxyId;
}

export function encodeAddress(address: string): Buffer {
    if (!ethUtil.isValidAddress(address)) {
        throw new Error(`Invalid Address: ${address}`);
    }
    const encodedAddress = ethUtil.toBuffer(address);
    return encodedAddress;
}

export function encodeUint256(value: BigNumber): Buffer {
    const formattedValue = new BN(value.toString(10));
    const encodedValue = ethUtil.toUnsigned(formattedValue);
    return encodedValue;
}

export function encodeERC20ProxyMetadata_V1(tokenAddress: string) {
    // Encode metadata
    const encodedAssetProxyId = encodeAssetProxyId(AssetProxyId.ERC20_V1);
    const encodedAddress = encodeAddress(tokenAddress);
    const encodedMetadata = Buffer.concat([encodedAssetProxyId, encodedAddress]);
    const encodedMetadataHex = ethUtil.bufferToHex(encodedMetadata);

    return encodedMetadataHex;
}

export function encodeERC20ProxyMetadata(tokenAddress: string) {
    // Encode metadata
    const encodedAssetProxyId = encodeAssetProxyId(AssetProxyId.ERC20);
    const encodedAddress = encodeAddress(tokenAddress);
    const encodedMetadata = Buffer.concat([encodedAssetProxyId, encodedAddress]);
    const encodedMetadataHex = ethUtil.bufferToHex(encodedMetadata);

    return encodedMetadataHex;
}

export function encodeERC721ProxyMetadata(tokenAddress: string, tokenId: BigNumber) {
    // Encode metadata
    const encodedAssetProxyId = encodeAssetProxyId(AssetProxyId.ERC721);
    const encodedAddress = encodeAddress(tokenAddress);
    const encodedTokenId = encodeUint256(tokenId);
    const encodedMetadata = Buffer.concat([encodedAssetProxyId, encodedAddress, encodedTokenId]);
    const encodedMetadataHex = ethUtil.bufferToHex(encodedMetadata);

    return encodedMetadataHex;
}