-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
interface.ts
588 lines (485 loc) · 21.8 KB
/
interface.ts
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
"use strict";
import { getAddress } from "@ethersproject/address";
import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
import { arrayify, BytesLike, concat, hexDataSlice, hexlify, hexZeroPad, isHexString } from "@ethersproject/bytes";
import { id } from "@ethersproject/hash";
import { keccak256 } from "@ethersproject/keccak256"
import { defineReadOnly, Description, getStatic } from "@ethersproject/properties";
import { AbiCoder, defaultAbiCoder } from "./abi-coder";
import { checkResultErrors, Result } from "./coders/abstract-coder";
import { ConstructorFragment, EventFragment, FormatTypes, Fragment, FunctionFragment, JsonFragment, ParamType } from "./fragments";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
export { checkResultErrors, Result };
export class LogDescription extends Description<LogDescription> {
readonly eventFragment: EventFragment;
readonly name: string;
readonly signature: string;
readonly topic: string;
readonly args: Result
}
export class TransactionDescription extends Description<TransactionDescription> {
readonly functionFragment: FunctionFragment;
readonly name: string;
readonly args: Result;
readonly signature: string;
readonly sighash: string;
readonly value: BigNumber;
}
export class Indexed extends Description<Indexed> {
readonly hash: string;
readonly _isIndexed: boolean;
static isIndexed(value: any): value is Indexed {
return !!(value && value._isIndexed);
}
}
function wrapAccessError(property: string, error: Error): Error {
const wrap = new Error(`deferred error during ABI decoding triggered accessing ${ property }`);
(<any>wrap).error = error;
return wrap;
}
/*
function checkNames(fragment: Fragment, type: "input" | "output", params: Array<ParamType>): void {
params.reduce((accum, param) => {
if (param.name) {
if (accum[param.name]) {
logger.throwArgumentError(`duplicate ${ type } parameter ${ JSON.stringify(param.name) } in ${ fragment.format("full") }`, "fragment", fragment);
}
accum[param.name] = true;
}
return accum;
}, <{ [ name: string ]: boolean }>{ });
}
*/
export class Interface {
readonly fragments: Array<Fragment>;
readonly errors: { [ name: string ]: any };
readonly events: { [ name: string ]: EventFragment };
readonly functions: { [ name: string ]: FunctionFragment };
readonly structs: { [ name: string ]: any };
readonly deploy: ConstructorFragment;
readonly _abiCoder: AbiCoder;
readonly _isInterface: boolean;
constructor(fragments: string | Array<Fragment | JsonFragment | string>) {
logger.checkNew(new.target, Interface);
let abi: Array<Fragment | JsonFragment | string> = [ ];
if (typeof(fragments) === "string") {
abi = JSON.parse(fragments);
} else {
abi = fragments;
}
defineReadOnly(this, "fragments", abi.map((fragment) => {
return Fragment.from(fragment);
}).filter((fragment) => (fragment != null)));
defineReadOnly(this, "_abiCoder", getStatic<() => AbiCoder>(new.target, "getAbiCoder")());
defineReadOnly(this, "functions", { });
defineReadOnly(this, "errors", { });
defineReadOnly(this, "events", { });
defineReadOnly(this, "structs", { });
// Add all fragments by their signature
this.fragments.forEach((fragment) => {
let bucket: { [ name: string ]: Fragment } = null;
switch (fragment.type) {
case "constructor":
if (this.deploy) {
logger.warn("duplicate definition - constructor");
return;
}
//checkNames(fragment, "input", fragment.inputs);
defineReadOnly(this, "deploy", <ConstructorFragment>fragment);
return;
case "function":
//checkNames(fragment, "input", fragment.inputs);
//checkNames(fragment, "output", (<FunctionFragment>fragment).outputs);
bucket = this.functions;
break;
case "event":
//checkNames(fragment, "input", fragment.inputs);
bucket = this.events;
break;
default:
return;
}
let signature = fragment.format();
if (bucket[signature]) {
logger.warn("duplicate definition - " + signature);
return;
}
bucket[signature] = fragment;
});
// If we do not have a constructor add a default
if (!this.deploy) {
defineReadOnly(this, "deploy", ConstructorFragment.from({
payable: false,
type: "constructor"
}));
}
defineReadOnly(this, "_isInterface", true);
}
format(format?: string): string | Array<string> {
if (!format) { format = FormatTypes.full; }
if (format === FormatTypes.sighash) {
logger.throwArgumentError("interface does not support formatting sighash", "format", format);
}
const abi = this.fragments.map((fragment) => fragment.format(format));
// We need to re-bundle the JSON fragments a bit
if (format === FormatTypes.json) {
return JSON.stringify(abi.map((j) => JSON.parse(j)));
}
return abi;
}
// Sub-classes can override these to handle other blockchains
static getAbiCoder(): AbiCoder {
return defaultAbiCoder;
}
static getAddress(address: string): string {
return getAddress(address);
}
static getSighash(functionFragment: FunctionFragment): string {
return hexDataSlice(id(functionFragment.format()), 0, 4);
}
static getEventTopic(eventFragment: EventFragment): string {
return id(eventFragment.format());
}
// Find a function definition by any means necessary (unless it is ambiguous)
getFunction(nameOrSignatureOrSighash: string): FunctionFragment {
if (isHexString(nameOrSignatureOrSighash)) {
for (const name in this.functions) {
if (nameOrSignatureOrSighash === this.getSighash(name)) {
return this.functions[name];
}
}
logger.throwArgumentError("no matching function", "sighash", nameOrSignatureOrSighash);
}
// It is a bare name, look up the function (will return null if ambiguous)
if (nameOrSignatureOrSighash.indexOf("(") === -1) {
const name = nameOrSignatureOrSighash.trim();
const matching = Object.keys(this.functions).filter((f) => (f.split("("/* fix:) */)[0] === name));
if (matching.length === 0) {
logger.throwArgumentError("no matching function", "name", name);
} else if (matching.length > 1) {
logger.throwArgumentError("multiple matching functions", "name", name);
}
return this.functions[matching[0]];
}
// Normlize the signature and lookup the function
const result = this.functions[FunctionFragment.fromString(nameOrSignatureOrSighash).format()];
if (!result) {
logger.throwArgumentError("no matching function", "signature", nameOrSignatureOrSighash);
}
return result;
}
// Find an event definition by any means necessary (unless it is ambiguous)
getEvent(nameOrSignatureOrTopic: string): EventFragment {
if (isHexString(nameOrSignatureOrTopic)) {
const topichash = nameOrSignatureOrTopic.toLowerCase();
for (const name in this.events) {
if (topichash === this.getEventTopic(name)) {
return this.events[name];
}
}
logger.throwArgumentError("no matching event", "topichash", topichash);
}
// It is a bare name, look up the function (will return null if ambiguous)
if (nameOrSignatureOrTopic.indexOf("(") === -1) {
const name = nameOrSignatureOrTopic.trim();
const matching = Object.keys(this.events).filter((f) => (f.split("("/* fix:) */)[0] === name));
if (matching.length === 0) {
logger.throwArgumentError("no matching event", "name", name);
} else if (matching.length > 1) {
logger.throwArgumentError("multiple matching events", "name", name);
}
return this.events[matching[0]];
}
// Normlize the signature and lookup the function
const result = this.events[EventFragment.fromString(nameOrSignatureOrTopic).format()];
if (!result) {
logger.throwArgumentError("no matching event", "signature", nameOrSignatureOrTopic);
}
return result;
}
// Get the sighash (the bytes4 selector) used by Solidity to identify a function
getSighash(functionFragment: FunctionFragment | string): string {
if (typeof(functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
return getStatic<(f: FunctionFragment) => string>(this.constructor, "getSighash")(functionFragment);
}
// Get the topic (the bytes32 hash) used by Solidity to identify an event
getEventTopic(eventFragment: EventFragment | string): string {
if (typeof(eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
return getStatic<(e: EventFragment) => string>(this.constructor, "getEventTopic")(eventFragment);
}
_decodeParams(params: Array<ParamType>, data: BytesLike): Result {
return this._abiCoder.decode(params, data)
}
_encodeParams(params: Array<ParamType>, values: Array<any>): string {
return this._abiCoder.encode(params, values)
}
encodeDeploy(values?: Array<any>): string {
return this._encodeParams(this.deploy.inputs, values || [ ]);
}
// Decode the data for a function call (e.g. tx.data)
decodeFunctionData(functionFragment: FunctionFragment | string, data: BytesLike): Result {
if (typeof(functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
const bytes = arrayify(data);
if (hexlify(bytes.slice(0, 4)) !== this.getSighash(functionFragment)) {
logger.throwArgumentError(`data signature does not match function ${ functionFragment.name }.`, "data", hexlify(bytes));
}
return this._decodeParams(functionFragment.inputs, bytes.slice(4));
}
// Encode the data for a function call (e.g. tx.data)
encodeFunctionData(functionFragment: FunctionFragment | string, values?: Array<any>): string {
if (typeof(functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
return hexlify(concat([
this.getSighash(functionFragment),
this._encodeParams(functionFragment.inputs, values || [ ])
]));
}
// Decode the result from a function call (e.g. from eth_call)
decodeFunctionResult(functionFragment: FunctionFragment | string, data: BytesLike): Result {
if (typeof(functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
let bytes = arrayify(data);
let reason: string = null;
let errorSignature: string = null;
switch (bytes.length % this._abiCoder._getWordSize()) {
case 0:
try {
return this._abiCoder.decode(functionFragment.outputs, bytes);
} catch (error) { }
break;
case 4:
if (hexlify(bytes.slice(0, 4)) === "0x08c379a0") {
errorSignature = "Error(string)";
reason = this._abiCoder.decode([ "string" ], bytes.slice(4))[0];
}
break;
}
return logger.throwError("call revert exception", Logger.errors.CALL_EXCEPTION, {
method: functionFragment.format(),
errorSignature: errorSignature,
errorArgs: [ reason ],
reason: reason
});
}
// Encode the result for a function call (e.g. for eth_call)
encodeFunctionResult(functionFragment: FunctionFragment | string, values?: Array<any>): string {
if (typeof(functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
return hexlify(this._abiCoder.encode(functionFragment.outputs, values || [ ]));
}
// Create the filter for the event with search criteria (e.g. for eth_filterLog)
encodeFilterTopics(eventFragment: EventFragment, values: Array<any>): Array<string | Array<string>> {
if (typeof(eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
if (values.length > eventFragment.inputs.length) {
logger.throwError("too many arguments for " + eventFragment.format(), Logger.errors.UNEXPECTED_ARGUMENT, {
argument: "values",
value: values
})
}
let topics: Array<string | Array<string>> = [];
if (!eventFragment.anonymous) { topics.push(this.getEventTopic(eventFragment)); }
const encodeTopic = (param: ParamType, value: any): string => {
if (param.type === "string") {
return id(value);
} else if (param.type === "bytes") {
return keccak256(hexlify(value));
}
// Check addresses are valid
if (param.type === "address") { this._abiCoder.encode( [ "address" ], [ value ]); }
return hexZeroPad(hexlify(value), 32);
};
values.forEach((value, index) => {
let param = eventFragment.inputs[index];
if (!param.indexed) {
if (value != null) {
logger.throwArgumentError("cannot filter non-indexed parameters; must be null", ("contract." + param.name), value);
}
return;
}
if (value == null) {
topics.push(null);
} else if (param.baseType === "array" || param.baseType === "tuple") {
logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value);
} else if (Array.isArray(value)) {
topics.push(value.map((value) => encodeTopic(param, value)));
} else {
topics.push(encodeTopic(param, value));
}
});
// Trim off trailing nulls
while (topics.length && topics[topics.length - 1] === null) {
topics.pop();
}
return topics;
}
encodeEventLog(eventFragment: EventFragment, values: Array<any>): { data: string, topics: Array<string> } {
if (typeof(eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
const topics: Array<string> = [ ];
const dataTypes: Array<ParamType> = [ ];
const dataValues: Array<string> = [ ];
if (!eventFragment.anonymous) {
topics.push(this.getEventTopic(eventFragment));
}
if (values.length !== eventFragment.inputs.length) {
logger.throwArgumentError("event arguments/values mismatch", "values", values);
}
eventFragment.inputs.forEach((param, index) => {
const value = values[index];
if (param.indexed) {
if (param.type === "string") {
topics.push(id(value))
} else if (param.type === "bytes") {
topics.push(keccak256(value))
} else if (param.baseType === "tuple" || param.baseType === "array") {
// @TOOD
throw new Error("not implemented");
} else {
topics.push(this._abiCoder.encode([ param.type] , [ value ]));
}
} else {
dataTypes.push(param);
dataValues.push(value);
}
});
return {
data: this._abiCoder.encode(dataTypes , dataValues),
topics: topics
};
}
// Decode a filter for the event and the search criteria
decodeEventLog(eventFragment: EventFragment | string, data: BytesLike, topics?: Array<string>): Result {
if (typeof(eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
if (topics != null && !eventFragment.anonymous) {
let topicHash = this.getEventTopic(eventFragment);
if (!isHexString(topics[0], 32) || topics[0].toLowerCase() !== topicHash) {
logger.throwError("fragment/topic mismatch", Logger.errors.INVALID_ARGUMENT, { argument: "topics[0]", expected: topicHash, value: topics[0] });
}
topics = topics.slice(1);
}
let indexed: Array<ParamType> = [];
let nonIndexed: Array<ParamType> = [];
let dynamic: Array<boolean> = [];
eventFragment.inputs.forEach((param, index) => {
if (param.indexed) {
if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") {
indexed.push(ParamType.fromObject({ type: "bytes32", name: param.name }));
dynamic.push(true);
} else {
indexed.push(param);
dynamic.push(false);
}
} else {
nonIndexed.push(param);
dynamic.push(false);
}
});
let resultIndexed = (topics != null) ? this._abiCoder.decode(indexed, concat(topics)): null;
let resultNonIndexed = this._abiCoder.decode(nonIndexed, data);
let result: (Array<any> & { [ key: string ]: any }) = [ ];
let nonIndexedIndex = 0, indexedIndex = 0;
eventFragment.inputs.forEach((param, index) => {
if (param.indexed) {
if (resultIndexed == null) {
result[index] = new Indexed({ _isIndexed: true, hash: null });
} else if (dynamic[index]) {
result[index] = new Indexed({ _isIndexed: true, hash: resultIndexed[indexedIndex++] });
} else {
try {
result[index] = resultIndexed[indexedIndex++];
} catch (error) {
result[index] = error;
}
}
} else {
try {
result[index] = resultNonIndexed[nonIndexedIndex++];
} catch (error) {
result[index] = error;
}
}
// Add the keyword argument if named and safe
if (param.name && result[param.name] == null) {
const value = result[index];
// Make error named values throw on access
if (value instanceof Error) {
Object.defineProperty(result, param.name, {
get: () => { throw wrapAccessError(`property ${ JSON.stringify(param.name) }`, value); }
});
} else {
result[param.name] = value;
}
}
});
// Make all error indexed values throw on access
for (let i = 0; i < result.length; i++) {
const value = result[i];
if (value instanceof Error) {
Object.defineProperty(result, i, {
get: () => { throw wrapAccessError(`index ${ i }`, value); }
});
}
}
return Object.freeze(result);
}
// Given a transaction, find the matching function fragment (if any) and
// determine all its properties and call parameters
parseTransaction(tx: { data: string, value?: BigNumberish }): TransactionDescription {
let fragment = this.getFunction(tx.data.substring(0, 10).toLowerCase())
if (!fragment) { return null; }
return new TransactionDescription({
args: this._abiCoder.decode(fragment.inputs, "0x" + tx.data.substring(10)),
functionFragment: fragment,
name: fragment.name,
signature: fragment.format(),
sighash: this.getSighash(fragment),
value: BigNumber.from(tx.value || "0"),
});
}
// Given an event log, find the matching event fragment (if any) and
// determine all its properties and values
parseLog(log: { topics: Array<string>, data: string}): LogDescription {
let fragment = this.getEvent(log.topics[0]);
if (!fragment || fragment.anonymous) { return null; }
// @TODO: If anonymous, and the only method, and the input count matches, should we parse?
// Probably not, because just because it is the only event in the ABI does
// not mean we have the full ABI; maybe jsut a fragment?
return new LogDescription({
eventFragment: fragment,
name: fragment.name,
signature: fragment.format(),
topic: this.getEventTopic(fragment),
args: this.decodeEventLog(fragment, log.data, log.topics)
});
}
/*
static from(value: Array<Fragment | string | JsonAbi> | string | Interface) {
if (Interface.isInterface(value)) {
return value;
}
if (typeof(value) === "string") {
return new Interface(JSON.parse(value));
}
return new Interface(value);
}
*/
static isInterface(value: any): value is Interface {
return !!(value && value._isInterface);
}
}