-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAbiEncoder.java
More file actions
352 lines (298 loc) · 13.5 KB
/
AbiEncoder.java
File metadata and controls
352 lines (298 loc) · 13.5 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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package org.arkecosystem.crypto.utils;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import org.web3j.utils.Numeric;
public class AbiEncoder extends AbiBase {
public AbiEncoder() throws IOException {
super();
}
public AbiEncoder(String abiFilePath) throws IOException {
super(abiFilePath);
}
public String encodeFunctionCall(String functionName) throws Exception {
return encodeFunctionCall(functionName, Collections.emptyList());
}
public String encodeFunctionCall(String functionName, List<Object> args) throws Exception {
Map<String, Object> parameters = new HashMap<>();
parameters.put("abi", this.abi);
parameters.put("functionName", functionName);
parameters.put("args", args);
return encodeFunctionData(parameters);
}
private String encodeFunctionData(Map<String, Object> parameters) throws Exception {
List<Object> args = (List<Object>) parameters.getOrDefault("args", new ArrayList<>());
Object[] result = prepareEncodeFunctionData(parameters);
Map<String, Object> abiItem = (Map<String, Object>) result[0];
String signature = (String) result[1];
String data;
List<Map<String, Object>> inputs = (List<Map<String, Object>>) abiItem.get("inputs");
if (inputs != null && !inputs.isEmpty()) {
data = encodeAbiParameters(inputs, args);
} else {
data = null;
}
return concatHex(Arrays.asList(signature, data != null ? data : "0x"));
}
private Object[] prepareEncodeFunctionData(Map<String, Object> params) throws Exception {
List<Map<String, Object>> abi = (List<Map<String, Object>>) params.get("abi");
String functionName = (String) params.get("functionName");
if (functionName == null) {
List<Map<String, Object>> functions = new ArrayList<>();
for (Map<String, Object> item : abi) {
if ("function".equals(item.get("type"))) {
functions.add(item);
}
}
if (functions.size() == 1) {
Map<String, Object> abiItem = functions.get(0);
functionName = (String) abiItem.get("name");
} else {
throw new Exception("Function name is not provided and ABI has multiple functions");
}
}
Map<String, Object> abiItem =
getAbiItem(
abi,
functionName,
(List<Object>) params.getOrDefault("args", new ArrayList<>()));
if (abiItem == null) {
throw new Exception("Function not found in ABI: " + functionName);
}
String signature = toFunctionSelector(abiItem);
return new Object[] {abiItem, signature};
}
private Map<String, Object> getAbiItem(
List<Map<String, Object>> abi, String name, List<Object> args) throws Exception {
List<Map<String, Object>> matchingItems = new ArrayList<>();
for (Map<String, Object> item : abi) {
if ("function".equals(item.get("type")) && name.equals(item.get("name"))) {
matchingItems.add(item);
}
}
if (matchingItems.isEmpty()) {
throw new Exception("Function not found in ABI: " + name);
}
for (Map<String, Object> item : matchingItems) {
List<Map<String, Object>> inputs = (List<Map<String, Object>>) item.get("inputs");
if (inputs.size() == args.size()) {
return item;
}
}
throw new Exception("Function with matching arguments not found in ABI: " + name);
}
private String encodeAbiParameters(List<Map<String, Object>> params, List<Object> values)
throws Exception {
if (params.size() != values.size()) {
throw new Exception("Length of parameters and values do not match");
}
List<Map<String, Object>> preparedParams = prepareParams(params, values);
String data = encodeParams(preparedParams);
return data != null && !data.isEmpty() ? data : "0x";
}
private List<Map<String, Object>> prepareParams(
List<Map<String, Object>> params, List<Object> values) throws Exception {
List<Map<String, Object>> preparedParams = new ArrayList<>();
for (int i = 0; i < params.size(); i++) {
Map<String, Object> preparedParam = prepareParam(params.get(i), values.get(i));
preparedParams.add(preparedParam);
}
return preparedParams;
}
private Map<String, Object> prepareParam(Map<String, Object> param, Object value)
throws Exception {
String type = (String) param.get("type");
String[] arrayComponents = getArrayComponents(type);
if (arrayComponents != null) {
String lengthStr = arrayComponents[0];
String innerType = arrayComponents[1];
Integer length =
lengthStr != null && !lengthStr.isEmpty() ? Integer.parseInt(lengthStr) : null;
Map<String, Object> innerParam = new HashMap<>();
innerParam.put("name", param.get("name"));
innerParam.put("type", innerType);
return encodeArray(value, length, innerParam);
}
switch (type) {
case "tuple":
return encodeTuple(value, param);
case "address":
return encodeAddress((String) value);
case "bool":
return encodeBool((Boolean) value);
default:
if (type.startsWith("uint") || type.startsWith("int")) {
boolean signed = type.startsWith("int");
return encodeNumber(value, signed);
} else if (type.startsWith("bytes")) {
return encodeBytes((String) value, param);
} else if ("string".equals(type)) {
return encodeString((String) value);
} else {
throw new Exception("Invalid ABI type: " + type);
}
}
}
private Map<String, Object> encodeArray(Object value, Integer length, Map<String, Object> param)
throws Exception {
boolean dynamic = length == null;
if (!(value instanceof List)) {
throw new Exception("Invalid array value");
}
List<Object> valueList = (List<Object>) value;
if (!dynamic && valueList.size() != length) {
throw new Exception("Array length mismatch");
}
boolean dynamicChild = false;
List<Map<String, Object>> preparedParams = new ArrayList<>();
for (Object v : valueList) {
Map<String, Object> preparedParam = prepareParam(param, v);
if ((Boolean) preparedParam.get("dynamic")) {
dynamicChild = true;
}
preparedParams.add(preparedParam);
}
if (dynamic || dynamicChild) {
String data = encodeParams(preparedParams);
if (dynamic) {
String lengthHex = String.format("%064x", valueList.size());
return Map.of("dynamic", true, "encoded", "0x" + lengthHex + data.substring(2));
}
if (dynamicChild) {
return Map.of("dynamic", true, "encoded", data);
}
}
StringBuilder encoded = new StringBuilder();
for (Map<String, Object> p : preparedParams) {
encoded.append(stripHexPrefix((String) p.get("encoded")));
}
return Map.of("dynamic", false, "encoded", "0x" + encoded.toString());
}
private String encodeParams(List<Map<String, Object>> preparedParams) {
int staticSize = 0;
for (Map<String, Object> param : preparedParams) {
boolean dynamic = (Boolean) param.get("dynamic");
if (dynamic) {
staticSize += 32;
} else {
staticSize += (stripHexPrefix((String) param.get("encoded")).length()) / 2;
}
}
List<String> staticParams = new ArrayList<>();
List<String> dynamicParams = new ArrayList<>();
int dynamicSize = 0;
for (Map<String, Object> param : preparedParams) {
boolean dynamic = (Boolean) param.get("dynamic");
if (dynamic) {
String offset = String.format("%064x", staticSize + dynamicSize);
staticParams.add(offset);
dynamicParams.add(stripHexPrefix((String) param.get("encoded")));
dynamicSize += (stripHexPrefix((String) param.get("encoded")).length()) / 2;
} else {
staticParams.add(stripHexPrefix((String) param.get("encoded")));
}
}
return "0x" + String.join("", staticParams) + String.join("", dynamicParams);
}
private Map<String, Object> encodeAddress(String value) throws Exception {
if (!isValidAddress(value)) {
throw new Exception("Invalid address: " + value);
}
value = stripHexPrefix(value).toLowerCase();
// Pad the string to 64 characters with leading zeros
String paddedValue = String.format("%64s", value).replace(' ', '0');
return Map.of("dynamic", false, "encoded", "0x" + paddedValue);
}
private Map<String, Object> encodeBool(Boolean value) {
String encoded = String.format("%064x", value ? 1 : 0);
return Map.of("dynamic", false, "encoded", "0x" + encoded);
}
private Map<String, Object> encodeNumber(Object value, boolean signed) throws Exception {
BigInteger bigValue;
if (value instanceof BigInteger) {
bigValue = (BigInteger) value;
} else if (value instanceof Number) {
bigValue = BigInteger.valueOf(((Number) value).longValue());
} else if (value instanceof String) {
bigValue = new BigInteger((String) value);
} else {
throw new Exception("Invalid number value");
}
if (signed) {
if (bigValue.compareTo(BigInteger.ZERO) < 0) {
bigValue = BigInteger.ONE.shiftLeft(256).add(bigValue);
}
} else {
if (bigValue.compareTo(BigInteger.ZERO) < 0) {
throw new Exception("Negative value provided for unsigned integer type");
}
}
String hex = bigValue.toString(16);
String encoded = "0".repeat(Math.max(0, 64 - hex.length())) + hex;
return Map.of("dynamic", false, "encoded", "0x" + encoded);
}
private Map<String, Object> encodeBytes(String value, Map<String, Object> param)
throws Exception {
int bytesSize = (stripHexPrefix(value).length()) / 2;
String paramType = (String) param.get("type");
String paramSizeStr = paramType.substring(5);
if (paramSizeStr.isEmpty()) {
String lengthHex = String.format("%064x", bytesSize);
String valuePadded = stripHexPrefix(value);
int padding = (32 - (bytesSize % 32)) % 32;
if (padding > 0) {
valuePadded = valuePadded + "0".repeat(padding * 2);
}
return Map.of("dynamic", true, "encoded", "0x" + lengthHex + valuePadded);
}
int paramSize = Integer.parseInt(paramSizeStr);
if (bytesSize != paramSize) {
throw new Exception(
"Bytes size mismatch: expected " + paramSize + ", got " + bytesSize);
}
String valuePadded = String.format("%-64s", stripHexPrefix(value)).replace(' ', '0');
return Map.of("dynamic", false, "encoded", "0x" + valuePadded);
}
private Map<String, Object> encodeString(String value) {
String hexValue = Numeric.toHexStringNoPrefix(value.getBytes());
String lengthHex = String.format("%064x", value.length());
String valuePadded = hexValue;
int padding = (32 - (value.length() % 32)) % 32;
if (padding > 0) {
valuePadded = valuePadded + "00".repeat(padding);
}
return Map.of("dynamic", true, "encoded", "0x" + lengthHex + valuePadded);
}
private Map<String, Object> encodeTuple(Object value, Map<String, Object> param)
throws Exception {
boolean dynamic = false;
List<Map<String, Object>> preparedParams = new ArrayList<>();
List<Map<String, Object>> components = (List<Map<String, Object>>) param.get("components");
Map<String, Object> valueMap;
if (value instanceof Map) {
valueMap = (Map<String, Object>) value;
} else {
throw new Exception("Tuple value must be a Map");
}
for (Map<String, Object> component : components) {
String key = (String) component.get("name");
if (!valueMap.containsKey(key)) {
throw new Exception("Tuple value missing component: " + key);
}
Map<String, Object> preparedParam = prepareParam(component, valueMap.get(key));
if ((Boolean) preparedParam.get("dynamic")) {
dynamic = true;
}
preparedParams.add(preparedParam);
}
if (dynamic) {
String encoded = encodeParams(preparedParams);
return Map.of("dynamic", true, "encoded", encoded);
}
StringBuilder encoded = new StringBuilder("0x");
for (Map<String, Object> p : preparedParams) {
encoded.append(stripHexPrefix((String) p.get("encoded")));
}
return Map.of("dynamic", false, "encoded", encoded.toString());
}
}