aboutsummaryrefslogtreecommitdiffstats
path: root/packages/contracts/src/utils/asset_proxy_utils.ts
blob: 63de7252d3f087b233a7bf6578ecd8941a3dd93e (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
import { BigNumber } from '@0xproject/utils';
import BN = require('bn.js');
import ethUtil = require('ethereumjs-util');

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 encodeERC20V1ProxyData(tokenAddress: string): string {
    const encodedAssetProxyId = encodeAssetProxyId(AssetProxyId.ERC20V1);
    const encodedAddress = encodeAddress(tokenAddress);
    const encodedMetadata = Buffer.concat([encodedAssetProxyId, encodedAddress]);
    const encodedMetadataHex = ethUtil.bufferToHex(encodedMetadata);
    return encodedMetadataHex;
}

export function encodeERC20ProxyData(tokenAddress: string): string {
    const encodedAssetProxyId = encodeAssetProxyId(AssetProxyId.ERC20);
    const encodedAddress = encodeAddress(tokenAddress);
    const encodedMetadata = Buffer.concat([encodedAssetProxyId, encodedAddress]);
    const encodedMetadataHex = ethUtil.bufferToHex(encodedMetadata);
    return encodedMetadataHex;
}

export function encodeERC721ProxyData(tokenAddress: string, tokenId: BigNumber): string {
    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;
}