Repository navigation
Expand file tree
/
Copy pathasset.ts
More file actions
114 lines (104 loc) · 2.35 KB
/
Copy pathasset.ts
File metadata and controls
114 lines (104 loc) · 2.35 KB
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
import {
object,
selectiveUnion,
StringNumberStruct,
} from '@metamask/keyring-utils';
import type { Infer } from '@metamask/superstruct';
import { literal, string } from '@metamask/superstruct';
import {
CaipAssetIdStruct,
CaipAssetTypeStruct,
isPlainObject,
} from '@metamask/utils';
/**
* Fungible asset amount struct.
*/
export const FungibleAssetAmountStruct = object({
/**
* Asset unit (symbol).
*/
unit: string(),
/**
* The human-readable asset amount with decimals applied (e.g., "1.5" for 1.5 SOL).
* This is kept for backward compatibility with existing consumers.
*/
amount: StringNumberStruct,
/**
* The raw blockchain balance without decimals applied (e.g., "1500000000" for 1.5 SOL).
* This provides precision for calculations using BigInt/BigNumber.
*/
rawAmount: string(),
});
/**
* Fungible asset struct.
*/
export const FungibleAssetStruct = object({
/**
* It is a fungible asset.
*/
fungible: literal(true),
/**
* Asset type (CAIP-19).
*/
type: CaipAssetTypeStruct,
...FungibleAssetAmountStruct.schema,
});
/**
* Non-fungible asset struct.
*/
export const NonFungibleAssetStruct = object({
/**
* It is a non-fungible asset.
*/
fungible: literal(false),
/**
* Asset ID (CAIP-19).
*/
id: CaipAssetIdStruct,
});
/**
* Asset struct. This represents a fungible or non-fungible asset. Fungible
* assets include an amount and a unit in addition to the asset type. While
* non-fungible assets include only an asset ID.
*
* See {@link NonFungibleAssetStruct} and {@link FungibleAssetStruct}.
*
* All assets have a `fungible` property that is used to tag the union and
* allow the following pattern:
*
* ```ts
* if (asset.fungible) {
* // Use asset.type
* } else {
* // Use asset.id
* }
* ```
*
* @example
* ```ts
* {
* fungible: true,
* type: 'eip155:1/slip44:60',
* unit: 'ETH',
* amount: '0.01',
* rawAmount: '10000000000000000',
* }
* ```
*
* @example
* ```ts
* {
* fungible: false,
* id: 'eip155:1/erc721:0x06012c8cf97BEaD5deAe237070F9587f8E7A266d/771769',
* }
* ```
*/
export const AssetStruct = selectiveUnion((value: any) => {
return isPlainObject(value) && !value.fungible
? NonFungibleAssetStruct
: FungibleAssetStruct;
});
/**
* Asset type {@see AssetStruct}.
*/
export type Asset = Infer<typeof AssetStruct>;