-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevm.lib.js
More file actions
611 lines (536 loc) · 22 KB
/
Copy pathevm.lib.js
File metadata and controls
611 lines (536 loc) · 22 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
(function() {
const _M = {};
const Charset = Java.type("java.nio.charset.Charset");
const JavaString = Java.type("java.lang.String");
const CharBuffer = Java.type('java.nio.CharBuffer');
const HashUtil = Java.type("nova.utils2b.utils.HashUtil");
const ByteBuffer = Java.type('java.nio.ByteBuffer');
const BigFloat = Java.type('java.math.BigDecimal');
const BigInteger = Java.type('java.math.BigInteger');
const RoundingMode = Java.type('java.math.RoundingMode');
const Thread = Java.type('java.lang.Thread');
const SafeMC = new java.math.MathContext(14, RoundingMode.DOWN);
const MaxUint256 = new BigFloat(new BigInteger("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16));
const HalfUint256 = MaxUint256.divide(new BigFloat(2), 0, RoundingMode.HALF_UP);
const ZeroAddress = "0x0000000000000000000000000000000000000000";
const web3 = {
RawTx: Java.type("org.web3j.crypto.RawTransaction"),
TxEncoder: Java.type("org.web3j.crypto.TransactionEncoder"),
Numeric: Java.type("org.web3j.utils.Numeric"),
Credentials: Java.type("org.web3j.crypto.Credentials"),
}
_M.credentials = function(privateKey) {
return web3.Credentials.create(privateKey);
}
function newBigInteger(value) {
if(value instanceof BigInteger) return value;
if(value instanceof BigFloat) return new BigInteger(value.setScale(0, RoundingMode.HALF_EVEN).toPlainString())
if(typeof value === 'string' && value.startsWith('0x')) return new BigInteger(value.slice(2), 16)
return new BigInteger(value);
}
function newBigFloat(value) {
if(value instanceof BigFloat) return value;
if(value instanceof BigInteger) return new BigFloat(value, SafeMC);
if(typeof value === 'string' && value.startsWith('0x')) return new BigFloat(new BigInteger(value.slice(2), 16), SafeMC);
return new BigFloat(value, SafeMC);
}
function padStart(str, len, char) {
var strLen = str.length;
if(strLen >= len) return str;
return String(char).repeat(len - strLen) + str;
}
function padEnd(str, len, char) {
var strLen = str.length;
if(strLen >= len) return str;
return str + String(char).repeat(len - strLen);
}
function rpcCall(url, method, params) {
const id = `${Math.floor(Math.random() * 100000000)}`;
const body = JSON.stringify({
jsonrpc: "2.0",
method: method,
params: params,
id: id,
});
// print("请求-> ", body)
const headers = {
"Content-Type": "application/json",
}
const resp = $httpc.postRaw(url, body, {}, headers);
const respJson = JSON.parse(new JavaString(resp.bytes));
// print("响应-> ", JSON.stringify(respJson))
if(respJson.error) {
throw new Error(`RPC请求错误[${method}]: ${respJson.error.message}`);
}
return respJson.result;
}
function padTo32Bytes(hex) {
return padStart(hex.replace(/^0x/, ""), 64, "0");
}
function hexToString(hex, encoding = "UTF-8") {
const charset = Charset.forName(encoding);
const bytes = [];
for(let i = 0; i < hex.length; i += 2) {
bytes.push(parseInt(hex.substr(i, 2), 16));
}
const byteBuffer = ByteBuffer.wrap(bytes);
const charBuffer = charset.decode(byteBuffer);
return charBuffer.toString();
}
function toHex(value) {
if(typeof value === "string" && value.startsWith("0x")) {
return value.slice(2);
}
if(typeof value === "string") {
const charset = Charset.forName("utf-8");
const charBuffer = CharBuffer.wrap(value.split(''));
const bytes = charset.encode(charBuffer).array();
return Java.from(bytes).map(b => padStart((b & 0xff).toString(16), 2, '0')).join('');
}
if(typeof value === "number") {
value = newBigFloat(value);
}
if(value instanceof BigFloat) {
value = newBigInteger(value.setScale(0).toPlainString());
}
if(typeof value === "bigint") {
value = newBigInteger(value.toString());
}
if(value instanceof BigInteger) {
if(value.compareTo(BigInteger.ZERO) >= 0) {
return value.toString(16);
}
//负数, 补码
var hex = value.abs().toString(16);
return padStart(hex, 64, 'f');
}
throw new Error("Unsupported value toHex: " + value);
}
function getFunctionSignature(abiItem) {
var abiType = abiItem.type;
if(abiType !== 'function' && abiType !== 'event') {
throw new Error('Invalid ABI item type: ' + abiType);
}
const types = abiItem.inputs.map(formatParamType);
return `${abiItem.name}(${types.join(',')})`;
}
function formatParamType(input) {
if(input.type === 'tuple') {
const components = input.components.map(formatParamType).join(',');
return `(${components})`;
}
else if(input.type.endsWith('[]')) {
// dynamic array of base type
const base = {components: input.components, type: input.type.slice(0, -2)};
return `${formatParamType(base)}[]`;
}
else if(input.type.match(/\[[0-9]+\]$/)) {
// fixed array of base type
const match = input.type.match(/^(.+)\[([0-9]+)\]$/);
const base = {components: input.components, type: match[1]};
return `${formatParamType(base)}[${match[2]}]`;
}
else {
return input.type;
}
}
_M.JsonRpc = function(url, chainId) {
this.url = url;
this.chainId = chainId;
this.__noSuchMethod__ = function(name) {
var params = [].slice.call(arguments, 1);
return rpcCall(this.url, 'eth_' + name, params);
}
}
_M.JsonRpc.prototype.nonce = function(addr) {
return newBigInteger(Date.now())
}
_M.JsonRpc.prototype.call = function(to, data, from) {
var params = {
to: to,
from: from || ZeroAddress,
value: '0x0',
data: data
};
return rpcCall(this.url, 'eth_call', [params, "latest"]);
}
_M.JsonRpc.prototype.estimateGas = function(tx, block = "latest") {
var args = {};
if(tx.chainId) args.chainId = '0x'+toHex(tx.chainId)
if(tx.nonce) args.nonce = '0x'+toHex(tx.nonce);
if(tx.to) args.to = tx.to;
if(tx.from) args.from = tx.from;
if(tx.value) args.value = '0x'+toHex(tx.value);
if(tx.data) args.input = tx.data.startsWith('0x') ? tx.data : '0x'+tx.data;
if(tx.gasLimit) args.gasLimit = '0x'+toHex(tx.gasLimit);
if(tx.maxPriorityFeePerGas) args.maxPriorityFeePerGas = '0x'+toHex(tx.maxPriorityFeePerGas);
if(tx.maxFeePerGas) args.maxFeePerGas = '0x'+toHex(tx.maxFeePerGas);
return rpcCall(this.url, 'eth_estimateGas', [args, block]);
}
//ref: https://docs.web3j.io/latest/transactions/EIP_transaction_types/eip1559_transaction/
_M.JsonRpc.prototype.sendTx = function(pk, tx) {
//long chainId, BigInteger nonce, BigInteger gasLimit, String to, BigInteger value, String data, BigInteger maxPriorityFeePerGas, BigInteger maxFeePerGas
var cred = _M.credentials(pk);
tx.chainId = this.chainId;
tx.nonce = this.getTransactionCount(cred.address, 'latest');
tx.from = cred.getAddress();
tx.gasLimit = tx.gasLimit || 250000;
tx.maxPriorityFeePerGas = tx.maxPriorityFeePerGas || 0;
tx.maxFeePerGas = tx.maxFeePerGas || this.gasPrice();
tx.value = tx.value || 0;
var estimateGas = this.estimateGas(tx);
var sig = 'createTransaction(long,BigInteger,BigInteger,String,BigInteger,String,BigInteger,BigInteger)'
var rawTx = web3.RawTx[sig](
this.chainId,
newBigInteger(tx.nonce),
newBigInteger(estimateGas),
tx.to,
newBigInteger(tx.value),
tx.data,
newBigInteger(tx.maxPriorityFeePerGas),
newBigInteger(tx.maxFeePerGas)
);
var signedMsg = web3.TxEncoder.signMessage(rawTx, cred);
signedMsg = web3.Numeric.toHexString(signedMsg);
return rpcCall(this.url, 'eth_sendRawTransaction', [signedMsg]);
}
_M.JsonRpc.prototype.wait = function(hash, timeout, interval) {
// confirms = confirms||1;
timeout = timeout || 20000;
interval = interval || 2000;
var start = Date.now();
while(true) {
var receipt = this.getTransactionReceipt(hash);
if(receipt) {
if(receipt.status === '0x1') {
var gasPrice = newBigInteger(0)
if(receipt.effectiveGasPrice) {
gasPrice = newBigInteger(receipt.effectiveGasPrice);
}
receipt.gasPrice = gasPrice;
receipt.gasUsed = newBigInteger(receipt.gasUsed);
receipt.fee = new BigFloat(gasPrice.multiply(receipt.gasUsed)).setScale(18, RoundingMode.HALF_UP);
return receipt;
}
throw new Error('Transaction failed: ' + receipt.status);
}
if(Date.now() - start > timeout) {
throw new Error('Transaction timeout');
}
Thread.sleep(interval);
}
}
const makeFunc = function(contract, fnName) {
const abi = contract.fnMap[fnName].abi;
const fn = function() {
var args = Array.from(arguments);
var callData = contract.encodeFunctionCall(fnName, args);
var res = contract.rpc.call(contract.address, callData)
return contract.decodeFunctionResult(fnName, res);
}
fn.sendTx = function(pk, args, opts) {
var callData = contract.encodeFunctionCall(fnName, args);
var tx = {
to: contract.address,
data: callData,
value: 0,
}
if(opts) {
for(const key in opts) {
tx[key] = opts[key];
}
}
return contract.rpc.sendTx(pk, tx);
}
fn.encode = function() {
var args = Array.from(arguments);
return contract.encodeFunctionCall(fnName, args);
}
fn.decode = function(res) {
return contract.decodeFunctionResult(fnName, res);
}
return fn;
}
_M.Contract = function(addr, abi, rpc) {
this.address = addr;
this.rpc = rpc;
this.abi = abi;
this.fnMap = {};
this.eventMap = {};
this._init();
this.__noSuchProperty__ = function(name) {
if(name in this.fnMap) return makeFunc(this, name);
return undefined;
}
}
_M.Contract.prototype._init = function() {
for each(const item in this.abi) {
if(item.type === "function") {
const sig = this._getSignature(item);
const selector = this._getSelector(sig);
// print(item.name, selector)
this.fnMap[item.name] = {
abi: item,
signature: sig,
selector: selector,
};
}
else if(item.type === "event") {
const sig = this._getSignature(item);
const topic0 = this._getSelector(sig, 64);
this.eventMap[topic0] = {
abi: item,
signature: sig,
};
}
}
}
_M.Contract.prototype.parseLogs = function(logs) {
const results = [];
// print('topics', Object.keys(this.eventMap).join("\n"))
for(const log of logs) {
const topic0 = log.topics[0].replace(/^0x/, "").toLowerCase();
const evt = this.eventMap[topic0];
if(!evt) continue;
const abi = evt.abi;
const decoded = {};
let topicIndex = 1;
let dataOffset = 0;
const data = log.data.replace(/^0x/, "");
const dataChunks = data.match(/.{64}/g) || [];
for(let i = 0; i < abi.inputs.length; i++) {
const input = abi.inputs[i];
const name = input.name || `param${i}`;
if(input.indexed) {
const topic = log.topics[topicIndex++].replace(/^0x/, "");
decoded[name] = this._decodeSingle(input, topic, []);
}
else {
const hex = dataChunks[dataOffset++];
decoded[name] = this._decodeSingle(input, hex, dataChunks);
}
}
results.push({
name: abi.name,
decoded: decoded,
raw: log
});
}
return results;
}
_M.Contract.prototype._getSignature = function(item) {
return getFunctionSignature(item);
}
_M.Contract.prototype._getSelector = function(signature, len) {
len = len || 8;
const hash = HashUtil.keccak256(signature);
return hash.slice(0, len); // 4 bytes
}
_M.Contract.prototype.encodeFunctionCall = function(name, args) {
const fn = this.fnMap[name];
if(!fn) throw new Error(`Function ${name} not found in ABI`);
const selector = fn.selector;
if(args.length !== fn.abi.inputs.length) {
throw new Error(`Invalid arguments count for function ${name}`)
}
const r = this._encodeParameters(fn.abi.inputs, args);
const data = r.head + r.tail;
if(data) {
// print(name)
// print(data.match(/.{64}/g).join("\n"))
}
return "0x" + selector + r.head + r.tail;
}
_M.Contract.prototype.decodeFunctionResult = function(name, data) {
const fn = this.fnMap[name];
if(!fn) throw new Error(`Function ${name} not found in ABI`);
var out = this._decodeParameters(fn.abi.outputs, data);
if(fn.abi.outputs.length === 1) {
return out[0];
}
return out;
}
_M.Contract.prototype._encodeParameters = function(inputs, args) {
const headParts = [];
const tailParts = [];
let dynamicOffset = (inputs.length) * 32;
for(let i = 0; i < inputs.length; i++) {
const input = inputs[i];
const val = args[i];
if(this._isDynamic(input)) {
headParts.push(padTo32Bytes(dynamicOffset.toString(16)));
const encoded = this._encodeSingle(input, val);
tailParts.push(encoded);
dynamicOffset += encoded.length / 2;
}
else {
const encoded = this._encodeSingle(input, val);
headParts.push(encoded);
}
}
return {
head: headParts.join(""),
tail: tailParts.join("")
};
}
_M.Contract.prototype._encodeSingle = function(input, value) {
const type = input.type;
const self = this;
if(type.match(/\[\]$/)) { // 动态数组处理
const baseType = type.replace("[]", "");
const arrayLen = padTo32Bytes(toHex(value.length));
const heads = [arrayLen];
const tails = [];
let offset = (value.length * 64) / 2;
for each(var v in value) {
const inp = {type: baseType, components: input.components};
const r = self._encodeParameters([inp], [v]);
if(this._isDynamic(inp)) {
heads.push(padTo32Bytes(toHex(offset)));
tails.push(r.tail);
offset += r.tail.length / 2;
}
else {
heads.push(r.head);
}
}
// print(heads.join(','), "\n", tails.join(','))
return heads.join('') + tails.join('');
}
if(type === "address") {
return padTo32Bytes(toHex(value));
}
if(type === "bool") {
return padTo32Bytes(value ? "1" : "0");
}
if(type.match(/^uint/)) {
return padTo32Bytes(toHex(newBigInteger(value)));
}
if(type.match(/^int/)) {
const bitSize = parseInt(type.slice(3));
const byteLen = bitSize / 8;
const valueHex = toHex(newBigInteger(value));
const padded = padStart(valueHex, byteLen * 2, "0");
return padTo32Bytes(padded);
}
if(type === "string" || type === "bytes") {
const raw = toHex(value);
const len = raw.length / 2;
const data = padEnd(raw, Math.ceil(raw.length / 64) * 64, "0");
return padTo32Bytes(toHex(len)) + data;
}
if(type.match(/^bytes\d+/)) {
return padEnd(toHex(value), 64, "0");
}
if(type === "tuple") {
const r = this._encodeParameters(input.components, value);
return r.head + r.tail;
}
throw new Error("Unsupported type: " + type);
}
_M.Contract.prototype._decodeParameters = function(outputs, data) {
const clean = data.replace(/^0x/, "");
const chunks = clean.match(/.{64}/g);
if(!chunks) return [];
var self = this;
var results = [];
for(var i = 0; i < outputs.length; i++) {
const result = self._decodeSingle(outputs[i], chunks[i], clean);
results.push(result);
}
// return outputs.map((output, i) => {
// var decoded = self._decodeSingle(output, chunks[i], clean)
// print('decode', JSON.stringify(output), decoded, decoded.class);
// return decoded;
// });
return results;
}
_M.Contract.prototype._decodeSingle = function(output, hex, fullData) {
const type = output.type;
const self = this;
if(type.match(/\[\]$/)) { // 动态数组解码
let offset = parseInt(hex, 16) * 2;
const lenHex = fullData.slice(offset, offset + 64);
const len = parseInt(lenHex, 16);
const elements = [];
for(let i = 0; i < len; i++) {
let dataOffset = (offset + 64) + i * 64;
if(this._isDynamic(output)) {
const elOffsetHex = fullData.slice(dataOffset, dataOffset + 64);
dataOffset = parseInt(elOffsetHex, 16) * 2 + (offset + 64);
}
var item = fullData.slice(dataOffset);
const el = this._decodeParameters([{
type: type.replace('[]', ''),
components: output.components
}], item)[0];
elements.push(el);
}
return elements;
}
if(type === "address") {
return "0x" + hex.slice(24);
}
if(type === "bool") {
return hex.endsWith("1");
}
if(type.match(/^uint/)) {
return (new BigFloat(web3.Numeric.toBigInt(hex), 0)).setScale(18, RoundingMode.HALF_EVEN);
}
if(type.match(/^int/)) {
const bitSize = parseInt(type.slice(3));
const byteLen = bitSize / 8;
const dataHex = hex.slice(64 - byteLen * 2); // 截取有效位
let value = new BigInteger(dataHex, 16);
const threshold = new BigInteger("2").pow(bitSize - 1);
// 补码负数处理
if(value.compareTo(threshold) >= 0) {
const max = new BigInteger("2").pow(bitSize);
value = value.subtract(max);
}
return (new BigFloat(value)).setScale(18, RoundingMode.HALF_EVEN);
}
if(type === "string" || type === "bytes") {
const offset = parseInt(hex, 16) * 2;
const lenHex = fullData.slice(offset, offset + 64);
const len = parseInt(lenHex, 16);
const strHex = fullData.slice(offset + 64, offset + 64 + len * 2);
return type === 'string' ? hexToString(strHex) : "0x" + strHex;
}
if(type.match(/^bytes\d+/)) {
const len = parseInt(type.slice(5));
const dataHex = hex.slice(0, len * 2); // 截取有效位
return "0x" + dataHex;
}
if(type === "tuple") {
const components = this._decodeParameters(output.components, fullData);
return components.reduce((acc, val, i) => {
acc[output.components[i].name] = val;
return acc;
}, {});
}
throw new Error("Unsupported decode type: " + type);
}
_M.Contract.prototype._isDynamic = function(input) {
const self = this;
if(input.type.endsWith('[]')) return true; // 动态数组总是动态类型
if(input.type.match(/\[[0-9]+\]$/)) { // 固定数组判断元素类型
const baseType = input.type.replace(/\[[0-9]+\]$/, '');
return self._isDynamic({type: baseType});
}
if(input.type === "string" || input.type === "bytes") return true;
if(input.type === "tuple") {
return input.components.some(c => self._isDynamic(c));
}
return false;
}
_M.MaxUint256 = MaxUint256;
_M.HalfUint256 = HalfUint256;
_M.ZeroAddress = ZeroAddress;
_M.BigFloat = BigFloat;
_M.EVEN = RoundingMode.HALF_EVEN;
_M.toHex = toHex;
_M.newBigFloat = newBigFloat;
_M.SafeMC = SafeMC;
return _M;
})();