-
Notifications
You must be signed in to change notification settings - Fork 14
/
types.ex
317 lines (231 loc) · 8.02 KB
/
types.ex
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
defmodule Ethers.Types do
@moduledoc "EVM types and compound type definitions"
require Logger
@typedoc """
Ethereum address in its hex format with 0x or in its binary format
## Examples
- `"0xdAC17F958D2ee523a2206206994597C13D831ec7"`
- `<<218, 193, 127, 149, 141, 46, 229, 35, 162, 32, 98, 6, 153, 69, 151, 193, 61, 131, 30, 199>>`
"""
@type t_address :: <<_::336>> | <<_::160>>
@typedoc """
Public key either in its uncompressed format (64 bytes MAY BE prefixed with 0x04) or its
compressed format (32 bytes MUST BE prefixed with 0x02 or 0x03)
It can be hex encoded but only with 0x prefix.
Compressed public key MUST have a prefix.
"""
@type t_pub_key ::
<<_::520>>
| <<_::512>>
| <<_::264>>
| <<_::1042>>
| <<_::1026>>
| <<_::530>>
@typedoc """
keccak hash in its hex format with 0x
## Examples
- `"0xd4288c8e733eb71a39fe2e8dd4912ce54d8d26d9874f30309b26b4b071260422"`
"""
@type t_hash :: <<_::528>>
@type t_bitsizes :: unquote(8..256//8 |> Enum.reduce(&{:|, [], [&1, &2]}))
@type t_bytesizes :: unquote(1..32 |> Enum.reduce(&{:|, [], [&1, &2]}))
@type t_evm_types ::
{:uint, t_bitsizes()}
| {:int, t_bitsizes()}
| {:bytes, t_bytesizes()}
| :bytes
| :string
| :address
| {:array, t_evm_types()}
| {:array, t_evm_types(), non_neg_integer()}
| {:tuple, [t_evm_types()]}
@valid_bitsize_range 8..256//8
defguardp valid_bitsize(bitsize) when bitsize >= 8 and bitsize <= 256 and rem(bitsize, 8) == 0
defguardp valid_bytesize(bytesize) when bytesize >= 1 and bytesize <= 32
@doc """
Converts EVM data types to typespecs for documentation
"""
def to_elixir_type(:address) do
quote do: Ethers.Types.t_address()
end
def to_elixir_type({:array, sub_type, _element_count}) do
to_elixir_type({:array, sub_type})
end
def to_elixir_type({:array, sub_type}) do
sub_type = to_elixir_type(sub_type)
quote do
[unquote(sub_type)]
end
end
def to_elixir_type({:bytes, size}) when valid_bytesize(size) do
quote do: <<_::unquote(size * 8)>>
end
def to_elixir_type(:bytes) do
quote do: binary()
end
def to_elixir_type(:bool) do
quote do: boolean()
end
def to_elixir_type(:function) do
raise "Function type not supported!"
end
def to_elixir_type({:ufixed, _element_count, _precision}) do
quote do: float()
end
def to_elixir_type({:fixed, _element_count, _precision}) do
quote do: float()
end
def to_elixir_type({:int, _}) do
quote do: integer
end
def to_elixir_type(:string) do
quote do: String.t()
end
def to_elixir_type({:tuple, sub_types}) do
sub_types = Enum.map(sub_types, &to_elixir_type/1)
quote do: {unquote_splicing(sub_types)}
end
def to_elixir_type({:uint, _}) do
quote do: non_neg_integer
end
def to_elixir_type(unknown) do
Logger.warning("Unknown type #{inspect(unknown)}")
quote do: term
end
@doc """
Returns the maximum possible value in the given type if supported.
## Examples
iex> Ethers.Types.max({:uint, 8})
255
iex> Ethers.Types.max({:int, 8})
127
iex> Ethers.Types.max({:uint, 16})
65535
iex> Ethers.Types.max({:int, 16})
32767
iex> Ethers.Types.max({:uint, 128})
340282366920938463463374607431768211455
iex> Ethers.Types.max({:int, 128})
170141183460469231731687303715884105727
"""
def max(type)
Enum.each(@valid_bitsize_range, fn bitsize ->
{int_res, uint_res} =
Enum.reduce(1..bitsize, {1, 1}, fn _bsize, {_, acc} -> {acc, 2 * acc} end)
def max({:uint, unquote(bitsize)}) do
unquote(uint_res - 1)
end
def max({:int, unquote(bitsize)}) do
unquote(int_res - 1)
end
end)
@doc """
Returns the minimum possible value in the given type if supported.
## Examples
iex> Ethers.Types.min({:uint, 8})
0
iex> Ethers.Types.min({:int, 8})
-128
iex> Ethers.Types.min({:uint, 16})
0
iex> Ethers.Types.min({:int, 16})
-32768
iex> Ethers.Types.min({:int, 24})
-8388608
iex> Ethers.Types.min({:int, 128})
-170141183460469231731687303715884105728
"""
def min(type)
def min({:uint, bitsize}) when valid_bitsize(bitsize), do: 0
Enum.each(@valid_bitsize_range, fn bitsize ->
int_res = Enum.reduce(1..(bitsize - 1), 1, fn _bsize, acc -> 2 * acc end)
def min({:int, unquote(bitsize)}) do
unquote(-int_res)
end
end)
@doc """
Returns the default value in the given type if supported.
## Examples
iex> Ethers.Types.default(:address)
"0x0000000000000000000000000000000000000000"
iex> Ethers.Types.default({:int, 32})
0
iex> Ethers.Types.default({:uint, 8})
0
iex> Ethers.Types.default({:int, 128})
0
iex> Ethers.Types.default(:string)
""
iex> Ethers.Types.default(:bytes)
""
iex> Ethers.Types.default({:bytes, 8})
<<0, 0, 0, 0, 0, 0, 0, 0>>
"""
def default({type, _}) when type in [:int, :uint], do: 0
def default(:address), do: "0x0000000000000000000000000000000000000000"
def default(type) when type in [:string, :bytes], do: ""
def default({:bytes, size}) when valid_bytesize(size), do: <<0::size*8>>
@doc """
Checks if a given data matches a given solidity type
## Examples
iex> Ethers.Types.matches_type?(false, :bool)
true
iex> Ethers.Types.matches_type?(200, {:uint, 8})
true
iex> Ethers.Types.matches_type?(400, {:uint, 8})
false
iex> Ethers.Types.matches_type?("0xdAC17F958D2ee523a2206206994597C13D831ec7", :address)
true
"""
@spec matches_type?(term(), t_evm_types()) :: boolean()
def matches_type?(value, type)
def matches_type?(value, {:uint, _bsize} = type),
do: is_integer(value) and value >= 0 and value <= max(type)
def matches_type?(value, {:int, _bsize} = type),
do: is_integer(value) and value >= min(type) and value <= max(type)
def matches_type?(value, :address) when is_binary(value) do
byte_size(value) == 20 or (byte_size(value) == 42 and String.starts_with?(value, "0x"))
end
def matches_type?(_value, :address), do: false
def matches_type?(value, :string), do: is_binary(value) and String.valid?(value)
def matches_type?(value, :bytes), do: is_binary(value)
def matches_type?(value, {:bytes, size}) when valid_bytesize(size),
do: is_binary(value) && byte_size(value) == size
def matches_type?(_value, {:bytes, size}),
do: raise(ArgumentError, "Invalid size: #{inspect(size)} (must be 1 <= size <= 32)")
def matches_type?(value, :bool), do: is_boolean(value)
def matches_type?(values, {:array, sub_type, element_count}) do
matches_type?(values, {:array, sub_type}) and Enum.count(values) == element_count
end
def matches_type?(values, {:array, sub_type}) do
is_list(values) and Enum.all?(values, &matches_type?(&1, sub_type))
end
def matches_type?(values, {:tuple, sub_types}) do
if is_tuple(values) and tuple_size(values) == Enum.count(sub_types) do
Enum.zip(sub_types, Tuple.to_list(values))
|> Enum.all?(fn {type, value} -> matches_type?(value, type) end)
else
false
end
end
@doc """
Validates and creates typed values to use with functions or events.
Typed values are useful when there are multiple overloads of same function or event and you need
to specify one of them to be used.
Also raises with ArgumentError in case value does not match the given type.
## Examples
iex> Ethers.Types.typed({:uint, 256}, 5)
{:typed, {:uint, 256}, 5}
iex> Ethers.Types.typed(:bytes, <<0, 1, 2>>)
{:typed, :bytes, <<0, 1, 2>>}
"""
@spec typed(term(), t_evm_types() | nil) :: {:typed, term(), term()} | no_return()
def typed(type, nil), do: {:typed, type, nil}
def typed(type, value) do
if matches_type?(value, type) do
{:typed, type, value}
else
raise ArgumentError, "Value #{inspect(value)} does not match type #{inspect(type)}"
end
end
end