ethers.js/packages/abi/lib/interface.js

536 lines
23 KiB
JavaScript
Raw Normal View History

2019-05-15 01:48:48 +03:00
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var address_1 = require("@ethersproject/address");
var bignumber_1 = require("@ethersproject/bignumber");
var bytes_1 = require("@ethersproject/bytes");
var hash_1 = require("@ethersproject/hash");
var keccak256_1 = require("@ethersproject/keccak256");
var properties_1 = require("@ethersproject/properties");
var abi_coder_1 = require("./abi-coder");
2020-04-25 10:54:54 +03:00
var abstract_coder_1 = require("./coders/abstract-coder");
exports.checkResultErrors = abstract_coder_1.checkResultErrors;
2019-05-15 01:48:48 +03:00
var fragments_1 = require("./fragments");
2019-08-02 09:10:58 +03:00
var logger_1 = require("@ethersproject/logger");
var _version_1 = require("./_version");
var logger = new logger_1.Logger(_version_1.version);
2019-05-15 01:48:48 +03:00
var LogDescription = /** @class */ (function (_super) {
__extends(LogDescription, _super);
function LogDescription() {
return _super !== null && _super.apply(this, arguments) || this;
}
return LogDescription;
}(properties_1.Description));
exports.LogDescription = LogDescription;
var TransactionDescription = /** @class */ (function (_super) {
__extends(TransactionDescription, _super);
function TransactionDescription() {
return _super !== null && _super.apply(this, arguments) || this;
}
return TransactionDescription;
}(properties_1.Description));
exports.TransactionDescription = TransactionDescription;
var Indexed = /** @class */ (function (_super) {
__extends(Indexed, _super);
function Indexed() {
return _super !== null && _super.apply(this, arguments) || this;
}
2019-06-12 00:57:04 +03:00
Indexed.isIndexed = function (value) {
return !!(value && value._isIndexed);
};
2019-05-15 01:48:48 +03:00
return Indexed;
}(properties_1.Description));
exports.Indexed = Indexed;
2020-04-25 10:54:54 +03:00
function wrapAccessError(property, error) {
var wrap = new Error("deferred error during ABI decoding triggered accessing " + property);
wrap.error = error;
return wrap;
}
2020-05-13 06:31:51 +03:00
/*
function checkNames(fragment: Fragment, type: "input" | "output", params: Array<ParamType>): void {
params.reduce((accum, param) => {
2020-04-25 10:54:54 +03:00
if (param.name) {
if (accum[param.name]) {
2020-05-13 06:31:51 +03:00
logger.throwArgumentError(`duplicate ${ type } parameter ${ JSON.stringify(param.name) } in ${ fragment.format("full") }`, "fragment", fragment);
2020-04-25 10:54:54 +03:00
}
accum[param.name] = true;
}
return accum;
2020-05-13 06:31:51 +03:00
}, <{ [ name: string ]: boolean }>{ });
2020-04-25 10:54:54 +03:00
}
2020-05-13 06:31:51 +03:00
*/
2019-05-15 01:48:48 +03:00
var Interface = /** @class */ (function () {
function Interface(fragments) {
var _newTarget = this.constructor;
var _this = this;
2019-08-02 09:10:58 +03:00
logger.checkNew(_newTarget, Interface);
2019-05-15 01:48:48 +03:00
var abi = [];
if (typeof (fragments) === "string") {
abi = JSON.parse(fragments);
}
else {
abi = fragments;
}
properties_1.defineReadOnly(this, "fragments", abi.map(function (fragment) {
return fragments_1.Fragment.from(fragment);
}).filter(function (fragment) { return (fragment != null); }));
2019-06-12 08:01:04 +03:00
properties_1.defineReadOnly(this, "_abiCoder", properties_1.getStatic((_newTarget), "getAbiCoder")());
2019-05-15 01:48:48 +03:00
properties_1.defineReadOnly(this, "functions", {});
properties_1.defineReadOnly(this, "errors", {});
properties_1.defineReadOnly(this, "events", {});
properties_1.defineReadOnly(this, "structs", {});
// Add all fragments by their signature
this.fragments.forEach(function (fragment) {
var bucket = null;
switch (fragment.type) {
case "constructor":
if (_this.deploy) {
2019-08-02 09:10:58 +03:00
logger.warn("duplicate definition - constructor");
2019-05-15 01:48:48 +03:00
return;
}
2020-05-13 06:31:51 +03:00
//checkNames(fragment, "input", fragment.inputs);
2019-05-15 01:48:48 +03:00
properties_1.defineReadOnly(_this, "deploy", fragment);
return;
case "function":
2020-05-13 06:31:51 +03:00
//checkNames(fragment, "input", fragment.inputs);
//checkNames(fragment, "output", (<FunctionFragment>fragment).outputs);
2019-05-15 01:48:48 +03:00
bucket = _this.functions;
break;
case "event":
2020-05-13 06:31:51 +03:00
//checkNames(fragment, "input", fragment.inputs);
2019-05-15 01:48:48 +03:00
bucket = _this.events;
break;
default:
return;
}
var signature = fragment.format();
if (bucket[signature]) {
2019-08-02 09:10:58 +03:00
logger.warn("duplicate definition - " + signature);
2019-05-15 01:48:48 +03:00
return;
}
bucket[signature] = fragment;
});
2020-04-25 10:54:54 +03:00
// If we do not have a constructor add a default
2019-05-15 01:48:48 +03:00
if (!this.deploy) {
2020-04-25 10:54:54 +03:00
properties_1.defineReadOnly(this, "deploy", fragments_1.ConstructorFragment.from({
payable: false,
type: "constructor"
}));
2019-05-15 01:48:48 +03:00
}
2019-06-12 00:57:04 +03:00
properties_1.defineReadOnly(this, "_isInterface", true);
2019-05-15 01:48:48 +03:00
}
2020-01-08 03:58:04 +03:00
Interface.prototype.format = function (format) {
if (!format) {
format = fragments_1.FormatTypes.full;
}
if (format === fragments_1.FormatTypes.sighash) {
2020-04-24 06:35:39 +03:00
logger.throwArgumentError("interface does not support formatting sighash", "format", format);
2020-01-08 03:58:04 +03:00
}
var abi = this.fragments.map(function (fragment) { return fragment.format(format); });
// We need to re-bundle the JSON fragments a bit
if (format === fragments_1.FormatTypes.json) {
return JSON.stringify(abi.map(function (j) { return JSON.parse(j); }));
}
return abi;
};
// Sub-classes can override these to handle other blockchains
2019-05-15 01:48:48 +03:00
Interface.getAbiCoder = function () {
return abi_coder_1.defaultAbiCoder;
};
Interface.getAddress = function (address) {
return address_1.getAddress(address);
};
2020-01-08 03:58:04 +03:00
Interface.getSighash = function (functionFragment) {
2019-05-15 01:48:48 +03:00
return bytes_1.hexDataSlice(hash_1.id(functionFragment.format()), 0, 4);
};
2020-02-26 13:06:48 +03:00
Interface.getEventTopic = function (eventFragment) {
2019-05-15 01:48:48 +03:00
return hash_1.id(eventFragment.format());
};
2020-01-08 03:58:04 +03:00
// Find a function definition by any means necessary (unless it is ambiguous)
2019-05-15 01:48:48 +03:00
Interface.prototype.getFunction = function (nameOrSignatureOrSighash) {
if (bytes_1.isHexString(nameOrSignatureOrSighash)) {
2019-11-20 12:57:38 +03:00
for (var name_1 in this.functions) {
if (nameOrSignatureOrSighash === this.getSighash(name_1)) {
return this.functions[name_1];
}
}
logger.throwArgumentError("no matching function", "sighash", nameOrSignatureOrSighash);
2019-05-15 01:48:48 +03:00
}
// It is a bare name, look up the function (will return null if ambiguous)
if (nameOrSignatureOrSighash.indexOf("(") === -1) {
2019-11-20 12:57:38 +03:00
var name_2 = nameOrSignatureOrSighash.trim();
var matching = Object.keys(this.functions).filter(function (f) { return (f.split("(" /* fix:) */)[0] === name_2); });
if (matching.length === 0) {
logger.throwArgumentError("no matching function", "name", name_2);
}
else if (matching.length > 1) {
logger.throwArgumentError("multiple matching functions", "name", name_2);
}
return this.functions[matching[0]];
2019-05-15 01:48:48 +03:00
}
// Normlize the signature and lookup the function
2019-11-20 12:57:38 +03:00
var result = this.functions[fragments_1.FunctionFragment.fromString(nameOrSignatureOrSighash).format()];
if (!result) {
logger.throwArgumentError("no matching function", "signature", nameOrSignatureOrSighash);
}
return result;
2019-05-15 01:48:48 +03:00
};
2020-01-08 03:58:04 +03:00
// Find an event definition by any means necessary (unless it is ambiguous)
2019-05-15 01:48:48 +03:00
Interface.prototype.getEvent = function (nameOrSignatureOrTopic) {
if (bytes_1.isHexString(nameOrSignatureOrTopic)) {
2019-11-20 12:57:38 +03:00
var topichash = nameOrSignatureOrTopic.toLowerCase();
for (var name_3 in this.events) {
if (topichash === this.getEventTopic(name_3)) {
return this.events[name_3];
}
}
logger.throwArgumentError("no matching event", "topichash", topichash);
2019-05-15 01:48:48 +03:00
}
// It is a bare name, look up the function (will return null if ambiguous)
if (nameOrSignatureOrTopic.indexOf("(") === -1) {
2019-11-20 12:57:38 +03:00
var name_4 = nameOrSignatureOrTopic.trim();
var matching = Object.keys(this.events).filter(function (f) { return (f.split("(" /* fix:) */)[0] === name_4); });
if (matching.length === 0) {
logger.throwArgumentError("no matching event", "name", name_4);
}
else if (matching.length > 1) {
logger.throwArgumentError("multiple matching events", "name", name_4);
}
return this.events[matching[0]];
}
// Normlize the signature and lookup the function
var result = this.events[fragments_1.EventFragment.fromString(nameOrSignatureOrTopic).format()];
if (!result) {
logger.throwArgumentError("no matching event", "signature", nameOrSignatureOrTopic);
2019-05-15 01:48:48 +03:00
}
2019-11-20 12:57:38 +03:00
return result;
2019-05-15 01:48:48 +03:00
};
2020-01-08 03:58:04 +03:00
// Get the sighash (the bytes4 selector) used by Solidity to identify a function
2019-05-15 01:48:48 +03:00
Interface.prototype.getSighash = function (functionFragment) {
if (typeof (functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
2020-01-08 03:58:04 +03:00
return properties_1.getStatic(this.constructor, "getSighash")(functionFragment);
2019-05-15 01:48:48 +03:00
};
2020-01-08 03:58:04 +03:00
// Get the topic (the bytes32 hash) used by Solidity to identify an event
2019-05-15 01:48:48 +03:00
Interface.prototype.getEventTopic = function (eventFragment) {
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
2020-02-26 13:06:48 +03:00
return properties_1.getStatic(this.constructor, "getEventTopic")(eventFragment);
2019-05-15 01:48:48 +03:00
};
2019-09-28 09:36:19 +03:00
Interface.prototype._decodeParams = function (params, data) {
return this._abiCoder.decode(params, data);
};
2019-05-15 01:48:48 +03:00
Interface.prototype._encodeParams = function (params, values) {
return this._abiCoder.encode(params, values);
};
Interface.prototype.encodeDeploy = function (values) {
return this._encodeParams(this.deploy.inputs, values || []);
};
2020-01-08 03:58:04 +03:00
// Decode the data for a function call (e.g. tx.data)
2019-09-28 09:36:19 +03:00
Interface.prototype.decodeFunctionData = function (functionFragment, data) {
if (typeof (functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
var bytes = bytes_1.arrayify(data);
if (bytes_1.hexlify(bytes.slice(0, 4)) !== this.getSighash(functionFragment)) {
logger.throwArgumentError("data signature does not match function " + functionFragment.name + ".", "data", bytes_1.hexlify(bytes));
}
return this._decodeParams(functionFragment.inputs, bytes.slice(4));
};
2020-01-08 03:58:04 +03:00
// Encode the data for a function call (e.g. tx.data)
2019-05-15 01:48:48 +03:00
Interface.prototype.encodeFunctionData = function (functionFragment, values) {
if (typeof (functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
return bytes_1.hexlify(bytes_1.concat([
this.getSighash(functionFragment),
this._encodeParams(functionFragment.inputs, values || [])
]));
};
2020-01-08 03:58:04 +03:00
// Decode the result from a function call (e.g. from eth_call)
2019-05-15 01:48:48 +03:00
Interface.prototype.decodeFunctionResult = function (functionFragment, data) {
if (typeof (functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
var bytes = bytes_1.arrayify(data);
var reason = null;
var errorSignature = null;
switch (bytes.length % this._abiCoder._getWordSize()) {
case 0:
try {
return this._abiCoder.decode(functionFragment.outputs, bytes);
}
catch (error) { }
break;
case 4:
if (bytes_1.hexlify(bytes.slice(0, 4)) === "0x08c379a0") {
errorSignature = "Error(string)";
2020-01-08 03:58:04 +03:00
reason = this._abiCoder.decode(["string"], bytes.slice(4))[0];
2019-05-15 01:48:48 +03:00
}
break;
}
2019-08-02 09:10:58 +03:00
return logger.throwError("call revert exception", logger_1.Logger.errors.CALL_EXCEPTION, {
2019-05-15 01:48:48 +03:00
method: functionFragment.format(),
errorSignature: errorSignature,
errorArgs: [reason],
reason: reason
});
};
2020-01-08 03:58:04 +03:00
// Encode the result for a function call (e.g. for eth_call)
2019-09-28 09:36:19 +03:00
Interface.prototype.encodeFunctionResult = function (functionFragment, values) {
if (typeof (functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
return bytes_1.hexlify(this._abiCoder.encode(functionFragment.outputs, values || []));
};
2020-01-08 03:58:04 +03:00
// Create the filter for the event with search criteria (e.g. for eth_filterLog)
2019-05-15 01:48:48 +03:00
Interface.prototype.encodeFilterTopics = function (eventFragment, values) {
var _this = this;
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
if (values.length > eventFragment.inputs.length) {
2019-08-02 09:10:58 +03:00
logger.throwError("too many arguments for " + eventFragment.format(), logger_1.Logger.errors.UNEXPECTED_ARGUMENT, {
2019-05-15 01:48:48 +03:00
argument: "values",
value: values
});
}
var topics = [];
if (!eventFragment.anonymous) {
topics.push(this.getEventTopic(eventFragment));
}
2020-05-02 00:00:44 +03:00
var encodeTopic = function (param, value) {
if (param.type === "string") {
return hash_1.id(value);
}
else if (param.type === "bytes") {
return keccak256_1.keccak256(bytes_1.hexlify(value));
}
// Check addresses are valid
if (param.type === "address") {
_this._abiCoder.encode(["address"], [value]);
}
return bytes_1.hexZeroPad(bytes_1.hexlify(value), 32);
};
2019-05-15 01:48:48 +03:00
values.forEach(function (value, index) {
var param = eventFragment.inputs[index];
if (!param.indexed) {
if (value != null) {
2019-08-02 09:10:58 +03:00
logger.throwArgumentError("cannot filter non-indexed parameters; must be null", ("contract." + param.name), value);
2019-05-15 01:48:48 +03:00
}
return;
}
if (value == null) {
topics.push(null);
}
2020-05-02 00:00:44 +03:00
else if (param.baseType === "array" || param.baseType === "tuple") {
2019-08-02 09:10:58 +03:00
logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value);
2019-05-15 01:48:48 +03:00
}
2020-05-02 00:00:44 +03:00
else if (Array.isArray(value)) {
topics.push(value.map(function (value) { return encodeTopic(param, value); }));
}
2019-05-15 01:48:48 +03:00
else {
2020-05-02 00:00:44 +03:00
topics.push(encodeTopic(param, value));
2019-05-15 01:48:48 +03:00
}
});
// Trim off trailing nulls
while (topics.length && topics[topics.length - 1] === null) {
topics.pop();
}
return topics;
};
2020-04-25 10:54:54 +03:00
Interface.prototype.encodeEventLog = function (eventFragment, values) {
var _this = this;
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
var topics = [];
var dataTypes = [];
var dataValues = [];
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(function (param, index) {
var value = values[index];
if (param.indexed) {
if (param.type === "string") {
topics.push(hash_1.id(value));
}
else if (param.type === "bytes") {
topics.push(keccak256_1.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
};
};
2020-01-08 03:58:04 +03:00
// Decode a filter for the event and the search criteria
2019-05-15 01:48:48 +03:00
Interface.prototype.decodeEventLog = function (eventFragment, data, topics) {
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
if (topics != null && !eventFragment.anonymous) {
2019-05-24 02:13:44 +03:00
var topicHash = this.getEventTopic(eventFragment);
if (!bytes_1.isHexString(topics[0], 32) || topics[0].toLowerCase() !== topicHash) {
2019-08-02 09:10:58 +03:00
logger.throwError("fragment/topic mismatch", logger_1.Logger.errors.INVALID_ARGUMENT, { argument: "topics[0]", expected: topicHash, value: topics[0] });
2019-05-24 02:13:44 +03:00
}
2019-05-15 01:48:48 +03:00
topics = topics.slice(1);
}
var indexed = [];
var nonIndexed = [];
var dynamic = [];
eventFragment.inputs.forEach(function (param, index) {
if (param.indexed) {
if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") {
indexed.push(fragments_1.ParamType.fromObject({ type: "bytes32", name: param.name }));
dynamic.push(true);
}
else {
indexed.push(param);
dynamic.push(false);
}
}
else {
nonIndexed.push(param);
dynamic.push(false);
}
});
var resultIndexed = (topics != null) ? this._abiCoder.decode(indexed, bytes_1.concat(topics)) : null;
2020-09-08 02:55:52 +03:00
var resultNonIndexed = this._abiCoder.decode(nonIndexed, data, true);
2019-05-15 01:48:48 +03:00
var result = [];
var nonIndexedIndex = 0, indexedIndex = 0;
eventFragment.inputs.forEach(function (param, index) {
if (param.indexed) {
if (resultIndexed == null) {
2019-06-12 00:57:04 +03:00
result[index] = new Indexed({ _isIndexed: true, hash: null });
2019-05-15 01:48:48 +03:00
}
else if (dynamic[index]) {
2019-06-12 00:57:04 +03:00
result[index] = new Indexed({ _isIndexed: true, hash: resultIndexed[indexedIndex++] });
2019-05-15 01:48:48 +03:00
}
else {
2020-04-25 10:54:54 +03:00
try {
result[index] = resultIndexed[indexedIndex++];
}
catch (error) {
result[index] = error;
}
2019-05-15 01:48:48 +03:00
}
}
else {
2020-04-25 10:54:54 +03:00
try {
result[index] = resultNonIndexed[nonIndexedIndex++];
}
catch (error) {
result[index] = error;
}
2019-05-15 01:48:48 +03:00
}
2020-04-25 10:54:54 +03:00
// Add the keyword argument if named and safe
2020-01-08 03:58:04 +03:00
if (param.name && result[param.name] == null) {
2020-04-25 10:54:54 +03:00
var value_1 = result[index];
// Make error named values throw on access
if (value_1 instanceof Error) {
Object.defineProperty(result, param.name, {
get: function () { throw wrapAccessError("property " + JSON.stringify(param.name), value_1); }
});
}
else {
result[param.name] = value_1;
}
2020-01-08 03:58:04 +03:00
}
2019-05-15 01:48:48 +03:00
});
2020-04-25 10:54:54 +03:00
var _loop_1 = function (i) {
var value = result[i];
if (value instanceof Error) {
Object.defineProperty(result, i, {
get: function () { throw wrapAccessError("index " + i, value); }
});
}
};
// Make all error indexed values throw on access
for (var i = 0; i < result.length; i++) {
_loop_1(i);
}
2020-03-31 00:24:33 +03:00
return Object.freeze(result);
2019-05-15 01:48:48 +03:00
};
2020-01-08 03:58:04 +03:00
// Given a transaction, find the matching function fragment (if any) and
// determine all its properties and call parameters
2019-05-15 01:48:48 +03:00
Interface.prototype.parseTransaction = function (tx) {
var 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_1.BigNumber.from(tx.value || "0"),
});
};
2020-01-08 03:58:04 +03:00
// Given an event log, find the matching event fragment (if any) and
// determine all its properties and values
2019-05-15 01:48:48 +03:00
Interface.prototype.parseLog = function (log) {
var 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?
2020-01-08 03:58:04 +03:00
// 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?
2019-05-15 01:48:48 +03:00
return new LogDescription({
eventFragment: fragment,
name: fragment.name,
signature: fragment.format(),
topic: this.getEventTopic(fragment),
2020-01-08 03:58:04 +03:00
args: this.decodeEventLog(fragment, log.data, log.topics)
2019-05-15 01:48:48 +03:00
});
};
2019-06-12 00:57:04 +03:00
/*
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);
}
*/
Interface.isInterface = function (value) {
return !!(value && value._isInterface);
};
2019-05-15 01:48:48 +03:00
return Interface;
}());
exports.Interface = Interface;
2020-07-13 15:03:56 +03:00
//# sourceMappingURL=interface.js.map