2
0
mirror of synced 2025-02-23 03:28:22 +00:00

Updated dist files.

This commit is contained in:
Richard Moore 2019-05-14 18:48:48 -04:00
parent 1f9cc05552
commit 7c3ed406c2
No known key found for this signature in database
GPG Key ID: 525F70A6FCABC295
276 changed files with 22668 additions and 0 deletions

1
packages/abi/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.128";

3
packages/abi/_version.js Normal file
View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.128";

15
packages/abi/abi-coder.d.ts vendored Normal file
View File

@ -0,0 +1,15 @@
import { BytesLike } from "@ethersproject/bytes";
import { Coder, Reader, Writer } from "./coders/abstract-coder";
import { ParamType } from "./fragments";
export declare type CoerceFunc = (type: string, value: any) => any;
export declare class AbiCoder {
readonly coerceFunc: CoerceFunc;
constructor(coerceFunc?: CoerceFunc);
_getCoder(param: ParamType): Coder;
_getWordSize(): number;
_getReader(data: Uint8Array): Reader;
_getWriter(): Writer;
encode(types: Array<string | ParamType>, values: Array<any>): string;
decode(types: Array<string | ParamType>, data: BytesLike): any;
}
export declare const defaultAbiCoder: AbiCoder;

112
packages/abi/abi-coder.js Normal file
View File

@ -0,0 +1,112 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
var bytes_1 = require("@ethersproject/bytes");
var errors = __importStar(require("@ethersproject/errors"));
var properties_1 = require("@ethersproject/properties");
var abstract_coder_1 = require("./coders/abstract-coder");
var address_1 = require("./coders/address");
var array_1 = require("./coders/array");
var boolean_1 = require("./coders/boolean");
var bytes_2 = require("./coders/bytes");
var fixed_bytes_1 = require("./coders/fixed-bytes");
var null_1 = require("./coders/null");
var number_1 = require("./coders/number");
var string_1 = require("./coders/string");
var tuple_1 = require("./coders/tuple");
var fragments_1 = require("./fragments");
var paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
var paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
var AbiCoder = /** @class */ (function () {
function AbiCoder(coerceFunc) {
var _newTarget = this.constructor;
errors.checkNew(_newTarget, AbiCoder);
properties_1.defineReadOnly(this, "coerceFunc", coerceFunc || null);
}
AbiCoder.prototype._getCoder = function (param) {
var _this = this;
switch (param.baseType) {
case "address":
return new address_1.AddressCoder(param.name);
case "bool":
return new boolean_1.BooleanCoder(param.name);
case "string":
return new string_1.StringCoder(param.name);
case "bytes":
return new bytes_2.BytesCoder(param.name);
case "array":
return new array_1.ArrayCoder(this._getCoder(param.arrayChildren), param.arrayLength, param.name);
case "tuple":
return new tuple_1.TupleCoder((param.components || []).map(function (component) {
return _this._getCoder(component);
}), param.name);
case "":
return new null_1.NullCoder(param.name);
}
// u?int[0-9]*
var match = param.type.match(paramTypeNumber);
if (match) {
var size = parseInt(match[2] || "256");
if (size === 0 || size > 256 || (size % 8) !== 0) {
errors.throwError("invalid " + match[1] + " bit length", errors.INVALID_ARGUMENT, {
arg: "param",
value: param
});
}
return new number_1.NumberCoder(size / 8, (match[1] === "int"), param.name);
}
// bytes[0-9]+
match = param.type.match(paramTypeBytes);
if (match) {
var size = parseInt(match[1]);
if (size === 0 || size > 32) {
errors.throwError("invalid bytes length", errors.INVALID_ARGUMENT, {
arg: "param",
value: param
});
}
return new fixed_bytes_1.FixedBytesCoder(size, param.name);
}
return errors.throwError("invalid type", errors.INVALID_ARGUMENT, {
arg: "type",
value: param.type
});
};
AbiCoder.prototype._getWordSize = function () { return 32; };
AbiCoder.prototype._getReader = function (data) {
return new abstract_coder_1.Reader(data, this._getWordSize(), this.coerceFunc);
};
AbiCoder.prototype._getWriter = function () {
return new abstract_coder_1.Writer(this._getWordSize());
};
AbiCoder.prototype.encode = function (types, values) {
var _this = this;
if (types.length !== values.length) {
errors.throwError("types/values length mismatch", errors.INVALID_ARGUMENT, {
count: { types: types.length, values: values.length },
value: { types: types, values: values }
});
}
var coders = types.map(function (type) { return _this._getCoder(fragments_1.ParamType.from(type)); });
var coder = (new tuple_1.TupleCoder(coders, "_"));
var writer = this._getWriter();
coder.encode(writer, values);
return writer.data;
};
AbiCoder.prototype.decode = function (types, data) {
var _this = this;
var coders = types.map(function (type) { return _this._getCoder(fragments_1.ParamType.from(type)); });
var coder = new tuple_1.TupleCoder(coders, "_");
return coder.decode(this._getReader(bytes_1.arrayify(data)));
};
return AbiCoder;
}());
exports.AbiCoder = AbiCoder;
exports.defaultAbiCoder = new AbiCoder();

41
packages/abi/coders/abstract-coder.d.ts vendored Normal file
View File

@ -0,0 +1,41 @@
import { BytesLike } from "@ethersproject/bytes";
import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
export declare type CoerceFunc = (type: string, value: any) => any;
export declare abstract class Coder {
readonly name: string;
readonly type: string;
readonly localName: string;
readonly dynamic: boolean;
constructor(name: string, type: string, localName: string, dynamic: boolean);
_throwError(message: string, value: any): void;
abstract encode(writer: Writer, value: any): number;
abstract decode(reader: Reader): any;
}
export declare class Writer {
readonly wordSize: number;
_data: Uint8Array;
_padding: Uint8Array;
constructor(wordSize?: number);
readonly data: string;
readonly length: number;
_writeData(data: Uint8Array): number;
writeBytes(value: BytesLike): number;
_getValue(value: BigNumberish): Uint8Array;
writeValue(value: BigNumberish): number;
writeUpdatableValue(): (value: BigNumberish) => void;
}
export declare class Reader {
readonly wordSize: number;
readonly _data: Uint8Array;
readonly _coerceFunc: CoerceFunc;
_offset: number;
constructor(data: BytesLike, wordSize?: number, coerceFunc?: CoerceFunc);
readonly data: string;
readonly consumed: number;
static coerce(name: string, value: any): any;
coerce(name: string, value: any): any;
_peekBytes(offset: number, length: number): Uint8Array;
subReader(offset: number): Reader;
readBytes(length: number): Uint8Array;
readValue(): BigNumber;
}

View File

@ -0,0 +1,143 @@
"use trict";
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var bytes_1 = require("@ethersproject/bytes");
var bignumber_1 = require("@ethersproject/bignumber");
var errors = __importStar(require("@ethersproject/errors"));
var properties_1 = require("@ethersproject/properties");
var Coder = /** @class */ (function () {
function Coder(name, type, localName, dynamic) {
this.name = name;
this.type = type;
this.localName = localName;
this.dynamic = dynamic;
}
Coder.prototype._throwError = function (message, value) {
errors.throwError(message, errors.INVALID_ARGUMENT, {
argument: this.localName,
coder: this,
value: value
});
};
return Coder;
}());
exports.Coder = Coder;
var Writer = /** @class */ (function () {
function Writer(wordSize) {
properties_1.defineReadOnly(this, "wordSize", wordSize || 32);
this._data = bytes_1.arrayify([]);
this._padding = new Uint8Array(wordSize);
}
Object.defineProperty(Writer.prototype, "data", {
get: function () { return bytes_1.hexlify(this._data); },
enumerable: true,
configurable: true
});
Object.defineProperty(Writer.prototype, "length", {
get: function () { return this._data.length; },
enumerable: true,
configurable: true
});
Writer.prototype._writeData = function (data) {
this._data = bytes_1.concat([this._data, data]);
return data.length;
};
// Arrayish items; padded on the right to wordSize
Writer.prototype.writeBytes = function (value) {
var bytes = bytes_1.arrayify(value);
if (bytes.length % this.wordSize) {
bytes = bytes_1.concat([bytes, this._padding.slice(bytes.length % this.wordSize)]);
}
return this._writeData(bytes);
};
Writer.prototype._getValue = function (value) {
var bytes = bytes_1.arrayify(bignumber_1.BigNumber.from(value));
if (bytes.length > this.wordSize) {
errors.throwError("value out-of-bounds", errors.BUFFER_OVERRUN, {
length: this.wordSize,
offset: bytes.length
});
}
if (bytes.length % this.wordSize) {
bytes = bytes_1.concat([this._padding.slice(bytes.length % this.wordSize), bytes]);
}
return bytes;
};
// BigNumberish items; padded on the left to wordSize
Writer.prototype.writeValue = function (value) {
return this._writeData(this._getValue(value));
};
Writer.prototype.writeUpdatableValue = function () {
var _this = this;
var offset = this.length;
this.writeValue(0);
return function (value) {
_this._data.set(_this._getValue(value), offset);
};
};
return Writer;
}());
exports.Writer = Writer;
var Reader = /** @class */ (function () {
function Reader(data, wordSize, coerceFunc) {
properties_1.defineReadOnly(this, "_data", bytes_1.arrayify(data));
properties_1.defineReadOnly(this, "wordSize", wordSize || 32);
properties_1.defineReadOnly(this, "_coerceFunc", coerceFunc);
this._offset = 0;
}
Object.defineProperty(Reader.prototype, "data", {
get: function () { return bytes_1.hexlify(this._data); },
enumerable: true,
configurable: true
});
Object.defineProperty(Reader.prototype, "consumed", {
get: function () { return this._offset; },
enumerable: true,
configurable: true
});
// The default Coerce function
Reader.coerce = function (name, value) {
var match = name.match("^u?int([0-9]+)$");
if (match && parseInt(match[1]) <= 48) {
value = value.toNumber();
}
return value;
};
Reader.prototype.coerce = function (name, value) {
if (this._coerceFunc) {
return this._coerceFunc(name, value);
}
return Reader.coerce(name, value);
};
Reader.prototype._peekBytes = function (offset, length) {
var alignedLength = Math.ceil(length / this.wordSize) * this.wordSize;
if (this._offset + alignedLength > this._data.length) {
errors.throwError("data out-of-bounds", errors.BUFFER_OVERRUN, {
length: this._data.length,
offset: this._offset + alignedLength
});
}
return this._data.slice(this._offset, this._offset + alignedLength);
};
Reader.prototype.subReader = function (offset) {
return new Reader(this._data.slice(this._offset + offset), this.wordSize, this._coerceFunc);
};
Reader.prototype.readBytes = function (length) {
var bytes = this._peekBytes(0, length);
this._offset += bytes.length;
// @TODO: Make sure the length..end bytes are all 0?
return bytes.slice(0, length);
};
Reader.prototype.readValue = function () {
return bignumber_1.BigNumber.from(this.readBytes(this.wordSize));
};
return Reader;
}());
exports.Reader = Reader;

6
packages/abi/coders/address.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
import { Coder, Reader, Writer } from "./abstract-coder";
export declare class AddressCoder extends Coder {
constructor(localName: string);
encode(writer: Writer, value: string): number;
decode(reader: Reader): any;
}

View File

@ -0,0 +1,38 @@
"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 bytes_1 = require("@ethersproject/bytes");
var abstract_coder_1 = require("./abstract-coder");
var AddressCoder = /** @class */ (function (_super) {
__extends(AddressCoder, _super);
function AddressCoder(localName) {
return _super.call(this, "address", "address", localName, false) || this;
}
AddressCoder.prototype.encode = function (writer, value) {
try {
address_1.getAddress(value);
}
catch (error) {
this._throwError(error.message, value);
}
return writer.writeValue(value);
};
AddressCoder.prototype.decode = function (reader) {
return address_1.getAddress(bytes_1.hexZeroPad(reader.readValue().toHexString(), 20));
};
return AddressCoder;
}(abstract_coder_1.Coder));
exports.AddressCoder = AddressCoder;

7
packages/abi/coders/anonymous.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
import { Coder, Reader, Writer } from "./abstract-coder";
export declare class AnonymousCoder extends Coder {
private coder;
constructor(coder: Coder);
encode(writer: Writer, value: any): number;
decode(reader: Reader): any;
}

View File

@ -0,0 +1,33 @@
"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 abstract_coder_1 = require("./abstract-coder");
// Clones the functionality of an existing Coder, but without a localName
var AnonymousCoder = /** @class */ (function (_super) {
__extends(AnonymousCoder, _super);
function AnonymousCoder(coder) {
var _this = _super.call(this, coder.name, coder.type, undefined, coder.dynamic) || this;
_this.coder = coder;
return _this;
}
AnonymousCoder.prototype.encode = function (writer, value) {
return this.coder.encode(writer, value);
};
AnonymousCoder.prototype.decode = function (reader) {
return this.coder.decode(reader);
};
return AnonymousCoder;
}(abstract_coder_1.Coder));
exports.AnonymousCoder = AnonymousCoder;

10
packages/abi/coders/array.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
import { Coder, Reader, Writer } from "./abstract-coder";
export declare function pack(writer: Writer, coders: Array<Coder>, values: Array<any>): number;
export declare function unpack(reader: Reader, coders: Array<Coder>): Array<any>;
export declare class ArrayCoder extends Coder {
readonly coder: Coder;
readonly length: number;
constructor(coder: Coder, length: number, localName: string);
encode(writer: Writer, value: Array<any>): number;
decode(reader: Reader): any;
}

View File

@ -0,0 +1,158 @@
"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 __());
};
})();
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var errors = __importStar(require("@ethersproject/errors"));
var abstract_coder_1 = require("./abstract-coder");
var anonymous_1 = require("./anonymous");
function pack(writer, coders, values) {
if (Array.isArray(values)) {
// do nothing
}
else if (values && typeof (values) === "object") {
var arrayValues_1 = [];
coders.forEach(function (coder) {
arrayValues_1.push(values[coder.localName]);
});
values = arrayValues_1;
}
else {
errors.throwError("invalid tuple value", errors.INVALID_ARGUMENT, {
coderType: "tuple",
value: values
});
}
if (coders.length !== values.length) {
errors.throwError("types/value length mismatch", errors.INVALID_ARGUMENT, {
coderType: "tuple",
value: values
});
}
var staticWriter = new abstract_coder_1.Writer(writer.wordSize);
var dynamicWriter = new abstract_coder_1.Writer(writer.wordSize);
var updateFuncs = [];
coders.forEach(function (coder, index) {
var value = values[index];
if (coder.dynamic) {
// Get current dynamic offset (for the future pointer)
var dynamicOffset_1 = dynamicWriter.length;
// Encode the dynamic value into the dynamicWriter
coder.encode(dynamicWriter, value);
// Prepare to populate the correct offset once we are done
var updateFunc_1 = staticWriter.writeUpdatableValue();
updateFuncs.push(function (baseOffset) {
updateFunc_1(baseOffset + dynamicOffset_1);
});
}
else {
coder.encode(staticWriter, value);
}
});
// Backfill all the dynamic offsets, now that we know the static length
updateFuncs.forEach(function (func) { func(staticWriter.length); });
var length = writer.writeBytes(staticWriter.data);
length += writer.writeBytes(dynamicWriter.data);
return length;
}
exports.pack = pack;
function unpack(reader, coders) {
var values = [];
// A reader anchored to this base
var baseReader = reader.subReader(0);
// The amount of dynamic data read; to consume later to synchronize
var dynamicLength = 0;
coders.forEach(function (coder) {
var value = null;
if (coder.dynamic) {
var offset = reader.readValue();
var offsetReader = baseReader.subReader(offset.toNumber());
value = coder.decode(offsetReader);
dynamicLength += offsetReader.consumed;
}
else {
value = coder.decode(reader);
}
if (value != undefined) {
values.push(value);
}
});
// @TODO: get rid of this an see if it still works?
// Consume the dynamic components in the main reader
reader.readBytes(dynamicLength);
// Add any named parameters (i.e. tuples)
coders.forEach(function (coder, index) {
var name = coder.localName;
if (!name) {
return;
}
if (name === "length") {
name = "_length";
}
if (values[name] != null) {
return;
}
values[name] = values[index];
});
return values;
}
exports.unpack = unpack;
var ArrayCoder = /** @class */ (function (_super) {
__extends(ArrayCoder, _super);
function ArrayCoder(coder, length, localName) {
var _this = this;
var type = (coder.type + "[" + (length >= 0 ? length : "") + "]");
var dynamic = (length === -1 || coder.dynamic);
_this = _super.call(this, "array", type, localName, dynamic) || this;
_this.coder = coder;
_this.length = length;
return _this;
}
ArrayCoder.prototype.encode = function (writer, value) {
if (!Array.isArray(value)) {
this._throwError("expected array value", value);
}
var count = this.length;
//let result = new Uint8Array(0);
if (count === -1) {
count = value.length;
writer.writeValue(value.length);
}
errors.checkArgumentCount(count, value.length, " in coder array" + (this.localName ? (" " + this.localName) : ""));
var coders = [];
for (var i = 0; i < value.length; i++) {
coders.push(this.coder);
}
return pack(writer, coders, value);
};
ArrayCoder.prototype.decode = function (reader) {
var count = this.length;
if (count === -1) {
count = reader.readValue().toNumber();
}
var coders = [];
for (var i = 0; i < count; i++) {
coders.push(new anonymous_1.AnonymousCoder(this.coder));
}
return reader.coerce(this.name, unpack(reader, coders));
};
return ArrayCoder;
}(abstract_coder_1.Coder));
exports.ArrayCoder = ArrayCoder;

6
packages/abi/coders/boolean.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
import { Coder, Reader, Writer } from "./abstract-coder";
export declare class BooleanCoder extends Coder {
constructor(localName: string);
encode(writer: Writer, value: boolean): number;
decode(reader: Reader): any;
}

View File

@ -0,0 +1,30 @@
"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 abstract_coder_1 = require("./abstract-coder");
var BooleanCoder = /** @class */ (function (_super) {
__extends(BooleanCoder, _super);
function BooleanCoder(localName) {
return _super.call(this, "bool", "bool", localName, false) || this;
}
BooleanCoder.prototype.encode = function (writer, value) {
return writer.writeValue(value ? 1 : 0);
};
BooleanCoder.prototype.decode = function (reader) {
return reader.coerce(this.type, !reader.readValue().isZero());
};
return BooleanCoder;
}(abstract_coder_1.Coder));
exports.BooleanCoder = BooleanCoder;

10
packages/abi/coders/bytes.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
import { Coder, Reader, Writer } from "./abstract-coder";
export declare class DynamicBytesCoder extends Coder {
constructor(type: string, localName: string);
encode(writer: Writer, value: any): number;
decode(reader: Reader): any;
}
export declare class BytesCoder extends DynamicBytesCoder {
constructor(localName: string);
decode(reader: Reader): any;
}

View File

@ -0,0 +1,45 @@
"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 bytes_1 = require("@ethersproject/bytes");
var abstract_coder_1 = require("./abstract-coder");
var DynamicBytesCoder = /** @class */ (function (_super) {
__extends(DynamicBytesCoder, _super);
function DynamicBytesCoder(type, localName) {
return _super.call(this, type, type, localName, true) || this;
}
DynamicBytesCoder.prototype.encode = function (writer, value) {
value = bytes_1.arrayify(value);
var length = writer.writeValue(value.length);
length += writer.writeBytes(value);
return length;
};
DynamicBytesCoder.prototype.decode = function (reader) {
return reader.readBytes(reader.readValue().toNumber());
};
return DynamicBytesCoder;
}(abstract_coder_1.Coder));
exports.DynamicBytesCoder = DynamicBytesCoder;
var BytesCoder = /** @class */ (function (_super) {
__extends(BytesCoder, _super);
function BytesCoder(localName) {
return _super.call(this, "bytes", localName) || this;
}
BytesCoder.prototype.decode = function (reader) {
return reader.coerce(this.name, bytes_1.hexlify(_super.prototype.decode.call(this, reader)));
};
return BytesCoder;
}(DynamicBytesCoder));
exports.BytesCoder = BytesCoder;

8
packages/abi/coders/fixed-bytes.d.ts vendored Normal file
View File

@ -0,0 +1,8 @@
import { BytesLike } from "@ethersproject/bytes";
import { Coder, Reader, Writer } from "./abstract-coder";
export declare class FixedBytesCoder extends Coder {
readonly size: number;
constructor(size: number, localName: string);
encode(writer: Writer, value: BytesLike): number;
decode(reader: Reader): any;
}

View File

@ -0,0 +1,40 @@
"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 bytes_1 = require("@ethersproject/bytes");
var abstract_coder_1 = require("./abstract-coder");
// @TODO: Merge this with bytes
var FixedBytesCoder = /** @class */ (function (_super) {
__extends(FixedBytesCoder, _super);
function FixedBytesCoder(size, localName) {
var _this = this;
var name = "bytes" + String(size);
_this = _super.call(this, name, name, localName, false) || this;
_this.size = size;
return _this;
}
FixedBytesCoder.prototype.encode = function (writer, value) {
var data = bytes_1.arrayify(value);
if (data.length !== this.size) {
this._throwError("incorrect data length", value);
}
return writer.writeBytes(data);
};
FixedBytesCoder.prototype.decode = function (reader) {
return reader.coerce(this.name, bytes_1.hexlify(reader.readBytes(this.size)));
};
return FixedBytesCoder;
}(abstract_coder_1.Coder));
exports.FixedBytesCoder = FixedBytesCoder;

6
packages/abi/coders/null.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
import { Coder, Reader, Writer } from "./abstract-coder";
export declare class NullCoder extends Coder {
constructor(localName: string);
encode(writer: Writer, value: any): number;
decode(reader: Reader): any;
}

View File

@ -0,0 +1,34 @@
"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 abstract_coder_1 = require("./abstract-coder");
var NullCoder = /** @class */ (function (_super) {
__extends(NullCoder, _super);
function NullCoder(localName) {
return _super.call(this, "null", "", localName, false) || this;
}
NullCoder.prototype.encode = function (writer, value) {
if (value != null) {
this._throwError("not null", value);
}
return writer.writeBytes([]);
};
NullCoder.prototype.decode = function (reader) {
reader.readBytes(0);
return reader.coerce(this.name, null);
};
return NullCoder;
}(abstract_coder_1.Coder));
exports.NullCoder = NullCoder;

9
packages/abi/coders/number.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
import { BigNumberish } from "@ethersproject/bignumber";
import { Coder, Reader, Writer } from "./abstract-coder";
export declare class NumberCoder extends Coder {
readonly size: number;
readonly signed: boolean;
constructor(size: number, signed: boolean, localName: string);
encode(writer: Writer, value: BigNumberish): number;
decode(reader: Reader): any;
}

View File

@ -0,0 +1,57 @@
"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 bignumber_1 = require("@ethersproject/bignumber");
var constants_1 = require("@ethersproject/constants");
var abstract_coder_1 = require("./abstract-coder");
var NumberCoder = /** @class */ (function (_super) {
__extends(NumberCoder, _super);
function NumberCoder(size, signed, localName) {
var _this = this;
var name = ((signed ? "int" : "uint") + (size * 8));
_this = _super.call(this, name, name, localName, false) || this;
_this.size = size;
_this.signed = signed;
return _this;
}
NumberCoder.prototype.encode = function (writer, value) {
var v = bignumber_1.BigNumber.from(value);
// Check bounds are safe for encoding
var maxUintValue = constants_1.MaxUint256.maskn(writer.wordSize * 8);
if (this.signed) {
var bounds = maxUintValue.maskn(this.size * 8 - 1);
if (v.gt(bounds) || v.lt(bounds.add(constants_1.One).mul(constants_1.NegativeOne))) {
this._throwError("value out-of-bounds", value);
}
}
else if (v.lt(constants_1.Zero) || v.gt(maxUintValue.maskn(this.size * 8))) {
this._throwError("value out-of-bounds", value);
}
v = v.toTwos(this.size * 8).maskn(this.size * 8);
if (this.signed) {
v = v.fromTwos(this.size * 8).toTwos(8 * writer.wordSize);
}
return writer.writeValue(v);
};
NumberCoder.prototype.decode = function (reader) {
var value = reader.readValue().maskn(this.size * 8);
if (this.signed) {
value = value.fromTwos(this.size * 8);
}
return reader.coerce(this.name, value);
};
return NumberCoder;
}(abstract_coder_1.Coder));
exports.NumberCoder = NumberCoder;

7
packages/abi/coders/string.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
import { Reader, Writer } from "./abstract-coder";
import { DynamicBytesCoder } from "./bytes";
export declare class StringCoder extends DynamicBytesCoder {
constructor(localName: string);
encode(writer: Writer, value: any): number;
decode(reader: Reader): any;
}

View File

@ -0,0 +1,31 @@
"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 strings_1 = require("@ethersproject/strings");
var bytes_1 = require("./bytes");
var StringCoder = /** @class */ (function (_super) {
__extends(StringCoder, _super);
function StringCoder(localName) {
return _super.call(this, "string", localName) || this;
}
StringCoder.prototype.encode = function (writer, value) {
return _super.prototype.encode.call(this, writer, strings_1.toUtf8Bytes(value));
};
StringCoder.prototype.decode = function (reader) {
return strings_1.toUtf8String(_super.prototype.decode.call(this, reader));
};
return StringCoder;
}(bytes_1.DynamicBytesCoder));
exports.StringCoder = StringCoder;

7
packages/abi/coders/tuple.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
import { Coder, Reader, Writer } from "./abstract-coder";
export declare class TupleCoder extends Coder {
readonly coders: Array<Coder>;
constructor(coders: Array<Coder>, localName: string);
encode(writer: Writer, value: Array<any>): number;
decode(reader: Reader): any;
}

View File

@ -0,0 +1,43 @@
"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 abstract_coder_1 = require("./abstract-coder");
var array_1 = require("./array");
var TupleCoder = /** @class */ (function (_super) {
__extends(TupleCoder, _super);
function TupleCoder(coders, localName) {
var _this = this;
var dynamic = false;
var types = [];
coders.forEach(function (coder) {
if (coder.dynamic) {
dynamic = true;
}
types.push(coder.type);
});
var type = ("tuple(" + types.join(",") + ")");
_this = _super.call(this, "tuple", type, localName, dynamic) || this;
_this.coders = coders;
return _this;
}
TupleCoder.prototype.encode = function (writer, value) {
return array_1.pack(writer, this.coders, value);
};
TupleCoder.prototype.decode = function (reader) {
return reader.coerce(this.name, array_1.unpack(reader, this.coders));
};
return TupleCoder;
}(abstract_coder_1.Coder));
exports.TupleCoder = TupleCoder;

63
packages/abi/fragments.d.ts vendored Normal file
View File

@ -0,0 +1,63 @@
import { BigNumber } from "@ethersproject/bignumber";
export interface JsonFragmentType {
name?: string;
indexed?: boolean;
type?: string;
components?: Array<JsonFragmentType>;
}
export interface JsonFragment {
name?: string;
type?: string;
anonymous?: boolean;
payable?: boolean;
constant?: boolean;
stateMutability?: string;
inputs?: Array<JsonFragmentType>;
outputs?: Array<JsonFragmentType>;
gas?: string;
}
export declare class ParamType {
readonly name: string;
readonly type: string;
readonly baseType: string;
readonly indexed: boolean;
readonly components: Array<ParamType>;
readonly arrayLength: number;
readonly arrayChildren: ParamType;
constructor(constructorGuard: any, params: any);
format(expanded?: boolean): string;
static from(value: string | JsonFragmentType | ParamType, allowIndexed?: boolean): ParamType;
static fromObject(value: JsonFragmentType | ParamType): ParamType;
static fromString(value: string, allowIndexed?: boolean): ParamType;
}
export declare abstract class Fragment {
readonly type: string;
readonly name: string;
readonly inputs: Array<ParamType>;
constructor(constructorGuard: any, params: any);
format(expanded?: boolean): string;
static from(value: Fragment | JsonFragment | string): Fragment;
static fromObject(value: Fragment | JsonFragment): Fragment;
static fromString(value: string): Fragment;
}
export declare class EventFragment extends Fragment {
readonly anonymous: boolean;
static from(value: EventFragment | JsonFragment | string): EventFragment;
static fromObject(value: JsonFragment | EventFragment): EventFragment;
static fromString(value: string): EventFragment;
}
export declare class ConstructorFragment extends Fragment {
stateMutability: string;
payable: boolean;
gas?: BigNumber;
static from(value: ConstructorFragment | JsonFragment | string): ConstructorFragment;
static fromObject(value: ConstructorFragment | JsonFragment): ConstructorFragment;
static fromString(value: string): ConstructorFragment;
}
export declare class FunctionFragment extends ConstructorFragment {
constant: boolean;
outputs?: Array<ParamType>;
static from(value: FunctionFragment | JsonFragment | string): FunctionFragment;
static fromObject(value: FunctionFragment | JsonFragment): FunctionFragment;
static fromString(value: string): FunctionFragment;
}

609
packages/abi/fragments.js Normal file
View File

@ -0,0 +1,609 @@
"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 __());
};
})();
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var bignumber_1 = require("@ethersproject/bignumber");
var errors = __importStar(require("@ethersproject/errors"));
var properties_1 = require("@ethersproject/properties");
;
var _constructorGuard = {};
// @TODO: Make sure that children of an indexed tuple are marked with a null indexed
function parseParamType(param, allowIndexed) {
var originalParam = param;
function throwError(i) {
throw new Error("unexpected character '" + originalParam[i] + "' at position " + i + " in '" + originalParam + "'");
}
param = param.replace(/\s/g, " ");
function newNode(parent) {
var node = { type: "", name: "", parent: parent, state: { allowType: true } };
if (allowIndexed) {
node.indexed = false;
}
return node;
}
var parent = { type: "", name: "", state: { allowType: true } };
var node = parent;
for (var i = 0; i < param.length; i++) {
var c = param[i];
switch (c) {
case "(":
if (!node.state.allowParams) {
throwError(i);
}
node.state.allowType = false;
node.type = verifyType(node.type);
node.components = [newNode(node)];
node = node.components[0];
break;
case ")":
delete node.state;
if (allowIndexed) {
if (node.name === "indexed") {
node.indexed = true;
node.name = "";
}
}
node.type = verifyType(node.type);
var child = node;
node = node.parent;
if (!node) {
throwError(i);
}
delete child.parent;
node.state.allowParams = false;
node.state.allowName = true;
node.state.allowArray = true;
break;
case ",":
delete node.state;
if (allowIndexed) {
if (node.name === "indexed") {
node.indexed = true;
node.name = "";
}
}
node.type = verifyType(node.type);
var sibling = newNode(node.parent);
//{ type: "", name: "", parent: node.parent, state: { allowType: true } };
node.parent.components.push(sibling);
delete node.parent;
node = sibling;
break;
// Hit a space...
case " ":
// If reading type, the type is done and may read a param or name
if (node.state.allowType) {
if (node.type !== "") {
node.type = verifyType(node.type);
delete node.state.allowType;
node.state.allowName = true;
node.state.allowParams = true;
}
}
// If reading name, the name is done
if (node.state.allowName) {
if (node.name !== "") {
if (allowIndexed) {
if (node.name === "indexed") {
if (node.indexed) {
throwError(i);
}
node.indexed = true;
node.name = "";
}
}
else {
node.state.allowName = false;
}
}
}
break;
case "[":
if (!node.state.allowArray) {
throwError(i);
}
node.type += c;
node.state.allowArray = false;
node.state.allowName = false;
node.state.readArray = true;
break;
case "]":
if (!node.state.readArray) {
throwError(i);
}
node.type += c;
node.state.readArray = false;
node.state.allowArray = true;
node.state.allowName = true;
break;
default:
if (node.state.allowType) {
node.type += c;
node.state.allowParams = true;
node.state.allowArray = true;
}
else if (node.state.allowName) {
node.name += c;
delete node.state.allowArray;
}
else if (node.state.readArray) {
node.type += c;
}
else {
throwError(i);
}
}
}
if (node.parent) {
throw new Error("unexpected eof");
}
delete parent.state;
if (allowIndexed) {
if (node.name === "indexed") {
if (node.indexed) {
throwError(originalParam.length - 7);
}
node.indexed = true;
node.name = "";
}
}
parent.type = verifyType(parent.type);
return parent;
}
function populate(object, params) {
for (var key in params) {
properties_1.defineReadOnly(object, key, params[key]);
}
}
var paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/);
var ParamType = /** @class */ (function () {
function ParamType(constructorGuard, params) {
if (constructorGuard !== _constructorGuard) {
throw new Error("use fromString");
}
populate(this, params);
var match = this.type.match(paramTypeArray);
if (match) {
populate(this, {
arrayLength: parseInt(match[2] || "-1"),
arrayChildren: ParamType.fromObject({
type: match[1],
components: this.components
}),
baseType: "array"
});
}
else {
populate(this, {
arrayLength: null,
arrayChildren: null,
baseType: ((this.components != null) ? "tuple" : this.type)
});
}
}
// Format the parameter fragment
// - non-expanded: "(uint256,address)"
// - expanded: "tuple(uint256 foo, addres bar) indexed baz"
ParamType.prototype.format = function (expanded) {
var result = "";
// Array
if (this.baseType === "array") {
result += this.arrayChildren.format(expanded);
result += "[" + (this.arrayLength < 0 ? "" : String(this.arrayLength)) + "]";
}
else {
if (this.baseType === "tuple") {
if (expanded) {
result += this.type;
}
result += "(" + this.components.map(function (c) { return c.format(expanded); }).join(expanded ? ", " : ",") + ")";
}
else {
result += this.type;
}
}
if (expanded) {
if (this.indexed === true) {
result += " indexed";
}
if (this.name) {
result += " " + this.name;
}
}
return result;
};
ParamType.from = function (value, allowIndexed) {
if (typeof (value) === "string") {
return ParamType.fromString(value, allowIndexed);
}
return ParamType.fromObject(value);
};
ParamType.fromObject = function (value) {
if (properties_1.isNamedInstance(ParamType, value)) {
return value;
}
return new ParamType(_constructorGuard, {
name: (value.name || null),
type: verifyType(value.type),
indexed: ((value.indexed == null) ? null : !!value.indexed),
components: (value.components ? value.components.map(ParamType.fromObject) : null)
});
};
ParamType.fromString = function (value, allowIndexed) {
function ParamTypify(node) {
return ParamType.fromObject({
name: node.name,
type: node.type,
indexed: node.indexed,
components: node.components
});
}
return ParamTypify(parseParamType(value, !!allowIndexed));
};
return ParamType;
}());
exports.ParamType = ParamType;
;
function parseParams(value, allowIndex) {
return splitNesting(value).map(function (param) { return ParamType.fromString(param, allowIndex); });
}
var Fragment = /** @class */ (function () {
function Fragment(constructorGuard, params) {
if (constructorGuard !== _constructorGuard) {
throw new Error("use a static from method");
}
populate(this, params);
}
// @TOOD: move logic to sub-classes; make this abstract
Fragment.prototype.format = function (expanded) {
var result = "";
if (this.type === "constructor") {
result += "constructor";
}
else {
if (expanded) {
result += this.type + " ";
}
result += this.name;
}
result += "(" + this.inputs.map(function (i) { return i.format(expanded); }).join(expanded ? ", " : ",") + ") ";
// @TODO: Handle returns, modifiers, etc.
if (expanded) {
result += "public ";
if (this.mutabilityState) {
result += this.mutabilityState + " ";
}
else if (this.constant) {
result += "view ";
}
if (this.outputs && this.outputs.length) {
result += "(" + this.outputs.map(function (i) { return i.format(expanded); }).join(", ") + ") ";
}
}
return result.trim();
};
Fragment.from = function (value) {
if (typeof (value) === "string") {
return Fragment.fromString(value);
}
return Fragment.fromObject(value);
};
Fragment.fromObject = function (value) {
if (properties_1.isNamedInstance(Fragment, value)) {
return value;
}
if (value.type === "function") {
return FunctionFragment.fromObject(value);
}
else if (value.type === "event") {
return EventFragment.fromObject(value);
}
else if (value.type === "constructor") {
return ConstructorFragment.fromObject(value);
}
else if (value.type === "fallback") {
// @TODO:
return null;
}
return errors.throwError("invalid fragment object", errors.INVALID_ARGUMENT, {
argument: "value",
value: value
});
};
Fragment.fromString = function (value) {
// Make sure the "returns" is surrounded by a space and all whitespace is exactly one space
value = value.replace(/\s/g, " ");
value = value.replace(/\(/g, " (").replace(/\)/g, ") ").replace(/\s+/g, " ");
value = value.trim();
if (value.split(" ")[0] === "event") {
return EventFragment.fromString(value.substring(5).trim());
}
else if (value.split(" ")[0] === "function") {
return FunctionFragment.fromString(value.substring(8).trim());
}
else if (value.split("(")[0].trim() === "constructor") {
return ConstructorFragment.fromString(value.trim());
}
throw new Error("unknown fragment");
};
return Fragment;
}());
exports.Fragment = Fragment;
var EventFragment = /** @class */ (function (_super) {
__extends(EventFragment, _super);
function EventFragment() {
return _super !== null && _super.apply(this, arguments) || this;
}
EventFragment.from = function (value) {
if (typeof (value) === "string") {
return EventFragment.fromString(value);
}
return EventFragment.fromObject(value);
};
EventFragment.fromObject = function (value) {
if (properties_1.isNamedInstance(EventFragment, value)) {
return value;
}
if (value.type !== "event") {
throw new Error("invalid event object - " + value.type);
}
return new EventFragment(_constructorGuard, {
name: verifyIdentifier(value.name),
anonymous: value.anonymous,
inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : []),
type: "event"
});
};
EventFragment.fromString = function (value) {
var match = value.match(regexParen);
if (!match) {
throw new Error("invalid event: " + value);
}
var anonymous = false;
match[3].split(" ").forEach(function (modifier) {
switch (modifier.trim()) {
case "anonymous":
anonymous = true;
break;
case "":
break;
default:
errors.warn("unknown modifier: " + modifier);
}
});
return EventFragment.fromObject({
name: match[1].trim(),
anonymous: anonymous,
inputs: parseParams(match[2], true),
type: "event"
});
};
return EventFragment;
}(Fragment));
exports.EventFragment = EventFragment;
function parseGas(value, params) {
params.gas = null;
var comps = value.split("@");
if (comps.length !== 1) {
if (comps.length > 2) {
throw new Error("invalid signature");
}
if (!comps[1].match(/^[0-9]+$/)) {
throw new Error("invalid signature gas");
}
params.gas = bignumber_1.BigNumber.from(comps[1]);
return comps[0];
}
return value;
}
function parseModifiers(value, params) {
params.constant = false;
params.payable = false;
// @TODO: Should this be initialized to "nonpayable"?
params.stateMutability = null;
value.split(" ").forEach(function (modifier) {
switch (modifier.trim()) {
case "constant":
params.constant = true;
break;
case "payable":
params.payable = true;
params.stateMutability = "payable";
break;
case "pure":
params.constant = true;
params.stateMutability = "pure";
break;
case "view":
params.constant = true;
params.stateMutability = "view";
break;
case "external":
case "public":
case "":
break;
default:
console.log("unknown modifier: " + modifier);
}
});
}
var ConstructorFragment = /** @class */ (function (_super) {
__extends(ConstructorFragment, _super);
function ConstructorFragment() {
return _super !== null && _super.apply(this, arguments) || this;
}
ConstructorFragment.from = function (value) {
if (typeof (value) === "string") {
return ConstructorFragment.fromString(value);
}
return ConstructorFragment.fromObject(value);
};
ConstructorFragment.fromObject = function (value) {
if (properties_1.isNamedInstance(ConstructorFragment, value)) {
return value;
}
if (value.type !== "constructor") {
throw new Error("invalid constructor object - " + value.type);
}
return new ConstructorFragment(_constructorGuard, {
type: value.type,
inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : []),
payable: ((value.payable == null) ? true : !!value.payable),
gas: (value.gas ? bignumber_1.BigNumber.from(value.gas) : null)
});
};
ConstructorFragment.fromString = function (value) {
var params = { type: "constructor" };
value = parseGas(value, params);
var parens = value.match(regexParen);
if (!parens) {
throw new Error("invalid constructor: " + value);
}
if (parens[1].trim() !== "constructor") {
throw new Error("invalid constructor");
}
params.inputs = parseParams(parens[2].trim(), false);
parseModifiers(parens[3].trim(), params);
return ConstructorFragment.fromObject(params);
};
return ConstructorFragment;
}(Fragment));
exports.ConstructorFragment = ConstructorFragment;
var FunctionFragment = /** @class */ (function (_super) {
__extends(FunctionFragment, _super);
function FunctionFragment() {
return _super !== null && _super.apply(this, arguments) || this;
}
FunctionFragment.from = function (value) {
if (typeof (value) === "string") {
return FunctionFragment.fromString(value);
}
return FunctionFragment.fromObject(value);
};
FunctionFragment.fromObject = function (value) {
if (properties_1.isNamedInstance(FunctionFragment, value)) {
return value;
}
if (value.type !== "function") {
throw new Error("invalid function object - " + value.type);
}
return new FunctionFragment(_constructorGuard, {
type: value.type,
name: verifyIdentifier(value.name),
constant: !!value.constant,
inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : []),
outputs: (value.outputs ? value.outputs.map(ParamType.fromObject) : []),
payable: ((value.payable == null) ? true : !!value.payable),
stateMutability: ((value.stateMutability != null) ? verifyString(value.stateMutability) : null),
gas: (value.gas ? bignumber_1.BigNumber.from(value.gas) : null)
});
};
FunctionFragment.fromString = function (value) {
var params = { type: "function" };
value = parseGas(value, params);
var comps = value.split(" returns ");
if (comps.length > 2) {
throw new Error("invalid function");
}
var parens = comps[0].match(regexParen);
if (!parens) {
throw new Error("invalid signature");
}
params.name = parens[1].trim();
if (!params.name.match(regexIdentifier)) {
throw new Error("invalid identifier: '" + params.name + "'");
}
params.inputs = parseParams(parens[2], false);
parseModifiers(parens[3].trim(), params);
// We have outputs
if (comps.length > 1) {
var returns = comps[1].match(regexParen);
if (returns[1].trim() != "" || returns[3].trim() != "") {
throw new Error("unexpected tokens");
}
params.outputs = parseParams(returns[2], false);
}
else {
params.outputs = [];
}
return FunctionFragment.fromObject(params);
};
return FunctionFragment;
}(ConstructorFragment));
exports.FunctionFragment = FunctionFragment;
//export class ErrorFragment extends Fragment {
//}
//export class StructFragment extends Fragment {
//}
function verifyString(value) {
if (typeof (value) !== "string") {
throw new Error("requires a string");
}
return value;
}
function verifyType(type) {
// These need to be transformed to their full description
if (type.match(/^uint($|[^1-9])/)) {
type = "uint256" + type.substring(4);
}
else if (type.match(/^int($|[^1-9])/)) {
type = "int256" + type.substring(3);
}
// @TODO: more verification
return type;
}
var regexIdentifier = new RegExp("^[A-Za-z_][A-Za-z0-9_]*$");
function verifyIdentifier(value) {
if (!value || !value.match(regexIdentifier)) {
throw new Error("invalid identifier: '" + value + "'");
}
return value;
}
var regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$");
function splitNesting(value) {
value = value.trim();
var result = [];
var accum = "";
var depth = 0;
for (var offset = 0; offset < value.length; offset++) {
var c = value[offset];
if (c === "," && depth === 0) {
result.push(accum);
accum = "";
}
else {
accum += c;
if (c === "(") {
depth++;
}
else if (c === ")") {
depth--;
if (depth === -1) {
throw new Error("unbalanced parenthsis");
}
}
}
}
if (accum) {
result.push(accum);
}
return result;
}

4
packages/abi/index.d.ts vendored Normal file
View File

@ -0,0 +1,4 @@
import { ConstructorFragment, EventFragment, Fragment, FunctionFragment, JsonFragment, JsonFragmentType, ParamType } from "./fragments";
import { AbiCoder, CoerceFunc, defaultAbiCoder } from "./abi-coder";
import { Indexed, Interface } from "./interface";
export { ConstructorFragment, EventFragment, Fragment, FunctionFragment, ParamType, AbiCoder, defaultAbiCoder, Interface, Indexed, CoerceFunc, JsonFragment, JsonFragmentType };

14
packages/abi/index.js Normal file
View File

@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fragments_1 = require("./fragments");
exports.ConstructorFragment = fragments_1.ConstructorFragment;
exports.EventFragment = fragments_1.EventFragment;
exports.Fragment = fragments_1.Fragment;
exports.FunctionFragment = fragments_1.FunctionFragment;
exports.ParamType = fragments_1.ParamType;
var abi_coder_1 = require("./abi-coder");
exports.AbiCoder = abi_coder_1.AbiCoder;
exports.defaultAbiCoder = abi_coder_1.defaultAbiCoder;
var interface_1 = require("./interface");
exports.Indexed = interface_1.Indexed;
exports.Interface = interface_1.Interface;

67
packages/abi/interface.d.ts vendored Normal file
View File

@ -0,0 +1,67 @@
import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
import { BytesLike } from "@ethersproject/bytes";
import { Description } from "@ethersproject/properties";
import { AbiCoder } from "./abi-coder";
import { ConstructorFragment, EventFragment, Fragment, FunctionFragment, JsonFragment, ParamType } from "./fragments";
export declare class LogDescription extends Description {
readonly eventFragment: EventFragment;
readonly name: string;
readonly signature: string;
readonly topic: string;
readonly values: any;
}
export declare class TransactionDescription extends Description {
readonly functionFragment: FunctionFragment;
readonly name: string;
readonly args: Array<any>;
readonly signature: string;
readonly sighash: string;
readonly value: BigNumber;
}
export declare class Indexed extends Description {
readonly hash: string;
}
export declare class Result {
[key: string]: any;
[key: number]: any;
}
export declare 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;
constructor(fragments: string | Array<Fragment | JsonFragment | string>);
static getAbiCoder(): AbiCoder;
static getAddress(address: string): string;
_sighashify(functionFragment: FunctionFragment): string;
_topicify(eventFragment: EventFragment): string;
getFunction(nameOrSignatureOrSighash: string): FunctionFragment;
getEvent(nameOrSignatureOrTopic: string): EventFragment;
getSighash(functionFragment: FunctionFragment | string): string;
getEventTopic(eventFragment: EventFragment | string): string;
_encodeParams(params: Array<ParamType>, values: Array<any>): string;
encodeDeploy(values?: Array<any>): string;
encodeFunctionData(functionFragment: FunctionFragment | string, values?: Array<any>): string;
decodeFunctionResult(functionFragment: FunctionFragment | string, data: BytesLike): Array<any>;
encodeFilterTopics(eventFragment: EventFragment, values: Array<any>): Array<string | Array<string>>;
decodeEventLog(eventFragment: EventFragment | string, data: BytesLike, topics?: Array<string>): Array<any>;
parseTransaction(tx: {
data: string;
value?: BigNumberish;
}): TransactionDescription;
parseLog(log: {
topics: Array<string>;
data: string;
}): LogDescription;
}

369
packages/abi/interface.js Normal file
View File

@ -0,0 +1,369 @@
"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 __());
};
})();
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
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 errors = __importStar(require("@ethersproject/errors"));
var properties_1 = require("@ethersproject/properties");
var abi_coder_1 = require("./abi-coder");
var fragments_1 = require("./fragments");
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;
}
return Indexed;
}(properties_1.Description));
exports.Indexed = Indexed;
var Result = /** @class */ (function () {
function Result() {
}
return Result;
}());
exports.Result = Result;
var Interface = /** @class */ (function () {
function Interface(fragments) {
var _newTarget = this.constructor;
var _this = this;
errors.checkNew(_newTarget, Interface);
var abi = [];
if (typeof (fragments) === "string") {
abi = JSON.parse(fragments);
}
else {
abi = fragments;
}
properties_1.defineReadOnly(this, "fragments", abi.map(function (fragment) {
if (properties_1.isNamedInstance(fragments_1.Fragment, fragment)) {
return fragment;
}
return fragments_1.Fragment.from(fragment);
}).filter(function (fragment) { return (fragment != null); }));
properties_1.defineReadOnly(this, "_abiCoder", _newTarget.getAbiCoder());
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) {
errors.warn("duplicate definition - constructor");
return;
}
properties_1.defineReadOnly(_this, "deploy", fragment);
return;
case "function":
bucket = _this.functions;
break;
case "event":
bucket = _this.events;
break;
default:
return;
}
var signature = fragment.format();
if (bucket[signature]) {
errors.warn("duplicate definition - " + signature);
return;
}
bucket[signature] = fragment;
});
// Add any fragments with a unique name by its name (sans signature parameters)
[this.events, this.functions].forEach(function (bucket) {
var count = getNameCount(bucket);
Object.keys(bucket).forEach(function (signature) {
var fragment = bucket[signature];
if (count[fragment.name] !== 1) {
errors.warn("duplicate definition - " + fragment.name);
return;
}
bucket[fragment.name] = fragment;
});
});
// If we do not have a constructor use the default "constructor() payable"
if (!this.deploy) {
properties_1.defineReadOnly(this, "deploy", fragments_1.ConstructorFragment.from({ type: "constructor" }));
}
}
Interface.getAbiCoder = function () {
return abi_coder_1.defaultAbiCoder;
};
Interface.getAddress = function (address) {
return address_1.getAddress(address);
};
Interface.prototype._sighashify = function (functionFragment) {
return bytes_1.hexDataSlice(hash_1.id(functionFragment.format()), 0, 4);
};
Interface.prototype._topicify = function (eventFragment) {
return hash_1.id(eventFragment.format());
};
Interface.prototype.getFunction = function (nameOrSignatureOrSighash) {
if (bytes_1.isHexString(nameOrSignatureOrSighash)) {
return getFragment(nameOrSignatureOrSighash, this.getSighash.bind(this), this.functions);
}
// It is a bare name, look up the function (will return null if ambiguous)
if (nameOrSignatureOrSighash.indexOf("(") === -1) {
return (this.functions[nameOrSignatureOrSighash.trim()] || null);
}
// Normlize the signature and lookup the function
return this.functions[fragments_1.FunctionFragment.fromString(nameOrSignatureOrSighash).format()];
};
Interface.prototype.getEvent = function (nameOrSignatureOrTopic) {
if (bytes_1.isHexString(nameOrSignatureOrTopic)) {
return getFragment(nameOrSignatureOrTopic, this.getEventTopic.bind(this), this.events);
}
// It is a bare name, look up the function (will return null if ambiguous)
if (nameOrSignatureOrTopic.indexOf("(") === -1) {
return this.events[nameOrSignatureOrTopic];
}
return this.events[fragments_1.EventFragment.fromString(nameOrSignatureOrTopic).format()];
};
Interface.prototype.getSighash = function (functionFragment) {
if (typeof (functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
return this._sighashify(functionFragment);
};
Interface.prototype.getEventTopic = function (eventFragment) {
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
return this._topicify(eventFragment);
};
Interface.prototype._encodeParams = function (params, values) {
return this._abiCoder.encode(params, values);
};
Interface.prototype.encodeDeploy = function (values) {
return this._encodeParams(this.deploy.inputs, values || []);
};
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 || [])
]));
};
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)";
reason = this._abiCoder.decode(["string"], bytes.slice(4));
}
break;
}
return errors.throwError("call revert exception", errors.CALL_EXCEPTION, {
method: functionFragment.format(),
errorSignature: errorSignature,
errorArgs: [reason],
reason: reason
});
};
Interface.prototype.encodeFilterTopics = function (eventFragment, values) {
var _this = this;
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
if (values.length > eventFragment.inputs.length) {
errors.throwError("too many arguments for " + eventFragment.format(), errors.UNEXPECTED_ARGUMENT, {
argument: "values",
value: values
});
}
var topics = [];
if (!eventFragment.anonymous) {
topics.push(this.getEventTopic(eventFragment));
}
values.forEach(function (value, index) {
var param = eventFragment.inputs[index];
if (!param.indexed) {
if (value != null) {
errors.throwArgumentError("cannot filter non-indexed parameters; must be null", ("contract." + param.name), value);
}
return;
}
if (value == null) {
topics.push(null);
}
else if (param.type === "string") {
topics.push(hash_1.id(value));
}
else if (param.type === "bytes") {
topics.push(keccak256_1.keccak256(bytes_1.hexlify(value)));
}
else if (param.type.indexOf("[") !== -1 || param.type.substring(0, 5) === "tuple") {
errors.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value);
}
else {
// Check addresses are valid
if (param.type === "address") {
_this._abiCoder.encode(["address"], [value]);
}
topics.push(bytes_1.hexZeroPad(bytes_1.hexlify(value), 32));
}
});
// Trim off trailing nulls
while (topics.length && topics[topics.length - 1] === null) {
topics.pop();
}
return topics;
};
Interface.prototype.decodeEventLog = function (eventFragment, data, topics) {
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
if (topics != null && !eventFragment.anonymous) {
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;
var resultNonIndexed = this._abiCoder.decode(nonIndexed, data);
var result = [];
var nonIndexedIndex = 0, indexedIndex = 0;
eventFragment.inputs.forEach(function (param, index) {
if (param.indexed) {
if (resultIndexed == null) {
result[index] = new Indexed({ hash: null });
}
else if (dynamic[index]) {
result[index] = new Indexed({ hash: resultIndexed[indexedIndex++] });
}
else {
result[index] = resultIndexed[indexedIndex++];
}
}
else {
result[index] = resultNonIndexed[nonIndexedIndex++];
}
//if (param.name && result[param.name] == null) { result[param.name] = result[index]; }
});
return result;
};
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"),
});
};
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?
return new LogDescription({
eventFragment: fragment,
name: fragment.name,
signature: fragment.format(),
topic: this.getEventTopic(fragment),
values: this.decodeEventLog(fragment, log.data, log.topics)
});
};
return Interface;
}());
exports.Interface = Interface;
function getFragment(hash, calcFunc, items) {
for (var signature in items) {
if (signature.indexOf("(") === -1) {
continue;
}
var fragment = items[signature];
if (calcFunc(fragment) === hash) {
return fragment;
}
}
return null;
}
function getNameCount(fragments) {
var unique = {};
// Count each name
for (var signature in fragments) {
var name_1 = fragments[signature].name;
if (!unique[name_1]) {
unique[name_1] = 0;
}
unique[name_1]++;
}
return unique;
}

View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.126";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.126";

133
packages/abstract-provider/index.d.ts vendored Normal file
View File

@ -0,0 +1,133 @@
import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
import { BytesLike } from "@ethersproject/bytes";
import { Network } from "@ethersproject/networks";
import { Transaction } from "@ethersproject/transactions";
import { OnceBlockable } from "@ethersproject/web";
export declare type TransactionRequest = {
to?: string | Promise<string>;
from?: string | Promise<string>;
nonce?: BigNumberish | Promise<BigNumberish>;
gasLimit?: BigNumberish | Promise<BigNumberish>;
gasPrice?: BigNumberish | Promise<BigNumberish>;
data?: BytesLike | Promise<BytesLike>;
value?: BigNumberish | Promise<BigNumberish>;
chainId?: number | Promise<number>;
};
export interface TransactionResponse extends Transaction {
blockNumber?: number;
blockHash?: string;
timestamp?: number;
confirmations: number;
from: string;
raw?: string;
wait: (confirmations?: number) => Promise<TransactionReceipt>;
}
export declare type BlockTag = string | number;
interface _Block {
hash: string;
parentHash: string;
number: number;
timestamp: number;
nonce: string;
difficulty: number;
gasLimit: BigNumber;
gasUsed: BigNumber;
miner: string;
extraData: string;
}
export interface Block extends _Block {
transactions: Array<string>;
}
export interface BlockWithTransactions extends _Block {
transactions: Array<TransactionResponse>;
}
export interface Log {
blockNumber?: number;
blockHash?: string;
transactionIndex?: number;
removed?: boolean;
transactionLogIndex?: number;
address: string;
data: string;
topics: Array<string>;
transactionHash?: string;
logIndex?: number;
}
export interface TransactionReceipt {
to?: string;
from?: string;
contractAddress?: string;
transactionIndex?: number;
root?: string;
gasUsed?: BigNumber;
logsBloom?: string;
blockHash?: string;
transactionHash?: string;
logs?: Array<Log>;
blockNumber?: number;
confirmations?: number;
cumulativeGasUsed?: BigNumber;
byzantium: boolean;
status?: number;
}
export interface EventFilter {
address?: string;
topics?: Array<string | Array<string>>;
}
export interface Filter extends EventFilter {
fromBlock?: BlockTag;
toBlock?: BlockTag;
}
export interface FilterByBlockHash extends EventFilter {
blockhash?: string;
}
export declare class ForkEvent {
readonly expiry: number;
constructor(expiry?: number);
}
export declare class BlockForkEvent extends ForkEvent {
readonly blockhash: string;
constructor(blockhash: string, expiry?: number);
}
export declare class TransactionForkEvent extends ForkEvent {
readonly hash: string;
constructor(hash: string, expiry?: number);
}
export declare class TransactionOrderForkEvent extends ForkEvent {
readonly beforeHash: string;
readonly afterHash: string;
constructor(beforeHash: string, afterHash: string, expiry?: number);
}
export declare type EventType = string | Array<string | Array<string>> | EventFilter | ForkEvent;
export declare type Listener = (...args: Array<any>) => void;
export declare abstract class Provider implements OnceBlockable {
abstract getNetwork(): Promise<Network>;
abstract getBlockNumber(): Promise<number>;
abstract getGasPrice(): Promise<BigNumber>;
abstract getBalance(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<BigNumber>;
abstract getTransactionCount(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<number>;
abstract getCode(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>;
abstract getStorageAt(addressOrName: string | Promise<string>, position: BigNumberish | Promise<BigNumberish>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>;
abstract sendTransaction(signedTransaction: string | Promise<string>): Promise<TransactionResponse>;
abstract call(transaction: TransactionRequest, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>;
abstract estimateGas(transaction: TransactionRequest): Promise<BigNumber>;
abstract getBlock(blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>): Promise<Block>;
abstract getBlockWithTransactions(blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>): Promise<BlockWithTransactions>;
abstract getTransaction(transactionHash: string): Promise<TransactionResponse>;
abstract getTransactionReceipt(transactionHash: string): Promise<TransactionReceipt>;
abstract getLogs(filter: Filter): Promise<Array<Log>>;
abstract resolveName(name: string | Promise<string>): Promise<string>;
abstract lookupAddress(address: string | Promise<string>): Promise<string>;
abstract on(eventName: EventType, listener: Listener): Provider;
abstract once(eventName: EventType, listener: Listener): Provider;
abstract emit(eventName: EventType, ...args: Array<any>): boolean;
abstract listenerCount(eventName?: EventType): number;
abstract listeners(eventName?: EventType): Array<Listener>;
abstract off(eventName: EventType, listener?: Listener): Provider;
abstract removeAllListeners(eventName?: EventType): Provider;
addListener(eventName: EventType, listener: Listener): Provider;
removeListener(eventName: EventType, listener: Listener): Provider;
abstract waitForTransaction(transactionHash: string, timeout?: number): Promise<TransactionReceipt>;
constructor();
}
export {};

View File

@ -0,0 +1,102 @@
"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 __());
};
})();
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var bytes_1 = require("@ethersproject/bytes");
var errors = __importStar(require("@ethersproject/errors"));
var errors_1 = require("@ethersproject/errors");
var properties_1 = require("@ethersproject/properties");
;
;
//export type CallTransactionable = {
// call(transaction: TransactionRequest): Promise<TransactionResponse>;
//};
var ForkEvent = /** @class */ (function () {
function ForkEvent(expiry) {
properties_1.defineReadOnly(this, "expiry", expiry || 0);
}
return ForkEvent;
}());
exports.ForkEvent = ForkEvent;
var BlockForkEvent = /** @class */ (function (_super) {
__extends(BlockForkEvent, _super);
function BlockForkEvent(blockhash, expiry) {
var _this = this;
if (!bytes_1.isHexString(blockhash, 32)) {
errors.throwArgumentError("invalid blockhash", "blockhash", blockhash);
}
_this = _super.call(this, expiry) || this;
properties_1.defineReadOnly(_this, "blockhash", blockhash);
return _this;
}
return BlockForkEvent;
}(ForkEvent));
exports.BlockForkEvent = BlockForkEvent;
var TransactionForkEvent = /** @class */ (function (_super) {
__extends(TransactionForkEvent, _super);
function TransactionForkEvent(hash, expiry) {
var _this = this;
if (!bytes_1.isHexString(hash, 32)) {
errors.throwArgumentError("invalid transaction hash", "hash", hash);
}
_this = _super.call(this, expiry) || this;
properties_1.defineReadOnly(_this, "hash", hash);
return _this;
}
return TransactionForkEvent;
}(ForkEvent));
exports.TransactionForkEvent = TransactionForkEvent;
var TransactionOrderForkEvent = /** @class */ (function (_super) {
__extends(TransactionOrderForkEvent, _super);
function TransactionOrderForkEvent(beforeHash, afterHash, expiry) {
var _this = this;
if (!bytes_1.isHexString(beforeHash, 32)) {
errors.throwArgumentError("invalid transaction hash", "beforeHash", beforeHash);
}
if (!bytes_1.isHexString(afterHash, 32)) {
errors.throwArgumentError("invalid transaction hash", "afterHash", afterHash);
}
_this = _super.call(this, expiry) || this;
properties_1.defineReadOnly(_this, "beforeHash", beforeHash);
properties_1.defineReadOnly(_this, "afterHash", afterHash);
return _this;
}
return TransactionOrderForkEvent;
}(ForkEvent));
exports.TransactionOrderForkEvent = TransactionOrderForkEvent;
///////////////////////////////
// Exported Abstracts
var Provider = /** @class */ (function () {
function Provider() {
var _newTarget = this.constructor;
errors_1.checkAbstract(_newTarget, Provider);
}
// Alias for "on"
Provider.prototype.addListener = function (eventName, listener) {
return this.on(eventName, listener);
};
// Alias for "off"
Provider.prototype.removeListener = function (eventName, listener) {
return this.off(eventName, listener);
};
return Provider;
}());
exports.Provider = Provider;

View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.126";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.126";

37
packages/abstract-signer/index.d.ts vendored Normal file
View File

@ -0,0 +1,37 @@
import { BlockTag, Provider, TransactionRequest, TransactionResponse } from "@ethersproject/abstract-provider";
import { BigNumber } from "@ethersproject/bignumber";
import { Bytes } from "@ethersproject/bytes";
export interface ExternallyOwnedAccount {
readonly address: string;
readonly privateKey: string;
readonly mnemonic?: string;
readonly path?: string;
}
export declare abstract class Signer {
readonly provider?: Provider;
abstract getAddress(): Promise<string>;
abstract signMessage(message: Bytes | string): Promise<string>;
abstract signTransaction(transaction: TransactionRequest): Promise<string>;
abstract connect(provider: Provider): Signer;
constructor();
getBalance(blockTag?: BlockTag): Promise<BigNumber>;
getTransactionCount(blockTag?: BlockTag): Promise<number>;
estimateGas(transaction: TransactionRequest): Promise<BigNumber>;
call(transaction: TransactionRequest, blockTag?: BlockTag): Promise<string>;
sendTransaction(transaction: TransactionRequest): Promise<TransactionResponse>;
getChainId(): Promise<number>;
getGasPrice(): Promise<BigNumber>;
resolveName(name: string): Promise<string>;
checkTransaction(transaction: TransactionRequest): TransactionRequest;
populateTransaction(transaction: TransactionRequest): Promise<TransactionRequest>;
_checkProvider(operation?: string): void;
}
export declare class VoidSigner extends Signer {
readonly address: string;
constructor(address: string, provider?: Provider);
getAddress(): Promise<string>;
_fail(message: string, operation: string): Promise<any>;
signMessage(message: Bytes | string): Promise<string>;
signTransaction(transaction: TransactionRequest): Promise<string>;
connect(provider: Provider): VoidSigner;
}

View File

@ -0,0 +1,192 @@
"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 __());
};
})();
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var errors = __importStar(require("@ethersproject/errors"));
var properties_1 = require("@ethersproject/properties");
var allowedTransactionKeys = [
"chainId", "data", "from", "gasLimit", "gasPrice", "nonce", "to", "value"
];
// Sub-Class Notes:
// - A Signer MUST always make sure, that if present, the "from" field
// matches the Signer, before sending or signing a transaction
// - A Signer SHOULD always wrap private information (such as a private
// key or mnemonic) in a function, so that console.log does not leak
// the data
var Signer = /** @class */ (function () {
///////////////////
// Sub-classes MUST call super
function Signer() {
var _newTarget = this.constructor;
errors.checkAbstract(_newTarget, Signer);
}
///////////////////
// Sub-classes MAY override these
Signer.prototype.getBalance = function (blockTag) {
this._checkProvider("getBalance");
return this.provider.getBalance(this.getAddress(), blockTag);
};
Signer.prototype.getTransactionCount = function (blockTag) {
this._checkProvider("getTransactionCount");
return this.provider.getTransactionCount(this.getAddress(), blockTag);
};
// Populates "from" if unspecified, and estimates the gas for the transation
Signer.prototype.estimateGas = function (transaction) {
var _this = this;
this._checkProvider("estimateGas");
return properties_1.resolveProperties(this.checkTransaction(transaction)).then(function (tx) {
return _this.provider.estimateGas(tx);
});
};
// Populates "from" if unspecified, and calls with the transation
Signer.prototype.call = function (transaction, blockTag) {
var _this = this;
this._checkProvider("call");
return properties_1.resolveProperties(this.checkTransaction(transaction)).then(function (tx) {
return _this.provider.call(tx);
});
};
// Populates all fields in a transaction, signs it and sends it to the network
Signer.prototype.sendTransaction = function (transaction) {
var _this = this;
this._checkProvider("sendTransaction");
return this.populateTransaction(transaction).then(function (tx) {
return _this.signTransaction(tx).then(function (signedTx) {
return _this.provider.sendTransaction(signedTx);
});
});
};
Signer.prototype.getChainId = function () {
this._checkProvider("getChainId");
return this.provider.getNetwork().then(function (network) { return network.chainId; });
};
Signer.prototype.getGasPrice = function () {
this._checkProvider("getGasPrice");
return this.provider.getGasPrice();
};
Signer.prototype.resolveName = function (name) {
this._checkProvider("resolveName");
return this.provider.resolveName(name);
};
// Checks a transaction does not contain invalid keys and if
// no "from" is provided, populates it.
// - does NOT require a provider
// - adds "from" is not present
// - returns a COPY (safe to mutate the result)
// By default called from: (overriding these prevents it)
// - call
// - estimateGas
// - populateTransaction (and therefor sendTransaction)
Signer.prototype.checkTransaction = function (transaction) {
for (var key in transaction) {
if (allowedTransactionKeys.indexOf(key) === -1) {
errors.throwArgumentError("invalid transaction key: " + key, "transaction", transaction);
}
}
var tx = properties_1.shallowCopy(transaction);
if (tx.from == null) {
tx.from = this.getAddress();
}
return tx;
};
// Populates ALL keys for a transaction and checks that "from" matches
// this Signer. Should be used by sendTransaction but NOT by signTransaction.
// By default called from: (overriding these prevents it)
// - sendTransaction
Signer.prototype.populateTransaction = function (transaction) {
var _this = this;
return properties_1.resolveProperties(this.checkTransaction(transaction)).then(function (tx) {
if (tx.to != null) {
tx.to = Promise.resolve(tx.to).then(function (to) { return _this.resolveName(to); });
}
if (tx.gasPrice == null) {
tx.gasPrice = _this.getGasPrice();
}
if (tx.nonce == null) {
tx.nonce = _this.getTransactionCount("pending");
}
// Make sure any provided address matches this signer
if (tx.from == null) {
tx.from = _this.getAddress();
}
else {
tx.from = Promise.all([
_this.getAddress(),
_this.provider.resolveName(tx.from)
]).then(function (results) {
if (results[0] !== results[1]) {
errors.throwArgumentError("from address mismatch", "transaction", transaction);
}
return results[0];
});
}
if (tx.gasLimit == null) {
tx.gasLimit = _this.estimateGas(tx);
}
if (tx.chainId == null) {
tx.chainId = _this.getChainId();
}
return properties_1.resolveProperties(tx);
});
};
///////////////////
// Sub-classes SHOULD leave these alone
Signer.prototype._checkProvider = function (operation) {
if (!this.provider) {
errors.throwError("missing provider", errors.UNSUPPORTED_OPERATION, {
operation: (operation || "_checkProvider")
});
}
};
return Signer;
}());
exports.Signer = Signer;
var VoidSigner = /** @class */ (function (_super) {
__extends(VoidSigner, _super);
function VoidSigner(address, provider) {
var _newTarget = this.constructor;
var _this = this;
errors.checkNew(_newTarget, VoidSigner);
_this = _super.call(this) || this;
properties_1.defineReadOnly(_this, "address", address);
properties_1.defineReadOnly(_this, "provider", provider || null);
return _this;
}
VoidSigner.prototype.getAddress = function () {
return Promise.resolve(this.address);
};
VoidSigner.prototype._fail = function (message, operation) {
return Promise.resolve().then(function () {
errors.throwError(message, errors.UNSUPPORTED_OPERATION, { operation: operation });
});
};
VoidSigner.prototype.signMessage = function (message) {
return this._fail("VoidSigner cannot sign messages", "signMessage");
};
VoidSigner.prototype.signTransaction = function (transaction) {
return this._fail("VoidSigner cannot sign transactions", "signTransaction");
};
VoidSigner.prototype.connect = function (provider) {
return new VoidSigner(this.address, provider);
};
return VoidSigner;
}(Signer));
exports.VoidSigner = VoidSigner;

1
packages/address/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.125";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.125";

8
packages/address/index.d.ts vendored Normal file
View File

@ -0,0 +1,8 @@
import { BigNumberish } from "@ethersproject/bignumber";
export declare function getAddress(address: string): string;
export declare function isAddress(address: string): boolean;
export declare function getIcapAddress(address: string): string;
export declare function getContractAddress(transaction: {
from: string;
nonce: BigNumberish;
}): string;

138
packages/address/index.js Normal file
View File

@ -0,0 +1,138 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
// We use this for base 36 maths
var BN = __importStar(require("bn.js"));
var errors = __importStar(require("@ethersproject/errors"));
var bytes_1 = require("@ethersproject/bytes");
var keccak256_1 = require("@ethersproject/keccak256");
var rlp_1 = require("@ethersproject/rlp");
function getChecksumAddress(address) {
if (!bytes_1.isHexString(address, 20)) {
errors.throwError("invalid address", errors.INVALID_ARGUMENT, { arg: "address", value: address });
}
address = address.toLowerCase();
var chars = address.substring(2).split("");
var hashed = new Uint8Array(40);
for (var i = 0; i < 40; i++) {
hashed[i] = chars[i].charCodeAt(0);
}
hashed = bytes_1.arrayify(keccak256_1.keccak256(hashed));
for (var i = 0; i < 40; i += 2) {
if ((hashed[i >> 1] >> 4) >= 8) {
chars[i] = chars[i].toUpperCase();
}
if ((hashed[i >> 1] & 0x0f) >= 8) {
chars[i + 1] = chars[i + 1].toUpperCase();
}
}
return "0x" + chars.join("");
}
// Shims for environments that are missing some required constants and functions
var MAX_SAFE_INTEGER = 0x1fffffffffffff;
function log10(x) {
if (Math.log10) {
return Math.log10(x);
}
return Math.log(x) / Math.LN10;
}
// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number
// Create lookup table
var ibanLookup = {};
for (var i = 0; i < 10; i++) {
ibanLookup[String(i)] = String(i);
}
for (var i = 0; i < 26; i++) {
ibanLookup[String.fromCharCode(65 + i)] = String(10 + i);
}
// How many decimal digits can we process? (for 64-bit float, this is 15)
var safeDigits = Math.floor(log10(MAX_SAFE_INTEGER));
function ibanChecksum(address) {
address = address.toUpperCase();
address = address.substring(4) + address.substring(0, 2) + "00";
var expanded = "";
address.split("").forEach(function (c) {
expanded += ibanLookup[c];
});
// Javascript can handle integers safely up to 15 (decimal) digits
while (expanded.length >= safeDigits) {
var block = expanded.substring(0, safeDigits);
expanded = parseInt(block, 10) % 97 + expanded.substring(block.length);
}
var checksum = String(98 - (parseInt(expanded, 10) % 97));
while (checksum.length < 2) {
checksum = "0" + checksum;
}
return checksum;
}
;
function getAddress(address) {
var result = null;
if (typeof (address) !== "string") {
errors.throwArgumentError("invalid address", "address", address);
}
if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
// Missing the 0x prefix
if (address.substring(0, 2) !== "0x") {
address = "0x" + address;
}
result = getChecksumAddress(address);
// It is a checksummed address with a bad checksum
if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) {
errors.throwArgumentError("bad address checksum", "address", address);
}
// Maybe ICAP? (we only support direct mode)
}
else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
// It is an ICAP address with a bad checksum
if (address.substring(2, 4) !== ibanChecksum(address)) {
errors.throwArgumentError("bad icap checksum", "address", address);
}
result = (new BN.BN(address.substring(4), 36)).toString(16);
while (result.length < 40) {
result = "0" + result;
}
result = getChecksumAddress("0x" + result);
}
else {
errors.throwArgumentError("invalid address", "address", address);
}
return result;
}
exports.getAddress = getAddress;
function isAddress(address) {
try {
getAddress(address);
return true;
}
catch (error) { }
return false;
}
exports.isAddress = isAddress;
function getIcapAddress(address) {
var base36 = (new BN.BN(getAddress(address).substring(2), 16)).toString(36).toUpperCase();
while (base36.length < 30) {
base36 = "0" + base36;
}
return "XE" + ibanChecksum("XE00" + base36) + base36;
}
exports.getIcapAddress = getIcapAddress;
// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
function getContractAddress(transaction) {
var from = null;
try {
from = getAddress(transaction.from);
}
catch (error) {
errors.throwArgumentError("missing from address", "transaction", transaction);
}
var nonce = bytes_1.stripZeros(bytes_1.arrayify(transaction.nonce));
return getAddress(bytes_1.hexDataSlice(keccak256_1.keccak256(rlp_1.encode([from, nonce])), 12));
}
exports.getContractAddress = getContractAddress;

1
packages/base64/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.124";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.124";

View File

@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bytes_1 = require("@ethersproject/bytes");
function decode(textData) {
textData = atob(textData);
var data = [];
for (var i = 0; i < textData.length; i++) {
data.push(textData.charCodeAt(i));
}
return bytes_1.arrayify(data);
}
exports.decode = decode;
function encode(data) {
data = bytes_1.arrayify(data);
var textData = "";
for (var i = 0; i < data.length; i++) {
textData += String.fromCharCode(data[i]);
}
return btoa(textData);
}
exports.encode = encode;

3
packages/base64/index.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
import { BytesLike } from "@ethersproject/bytes";
export declare function decode(textData: string): Uint8Array;
export declare function encode(data: BytesLike): string;

12
packages/base64/index.js Normal file
View File

@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bytes_1 = require("@ethersproject/bytes");
function decode(textData) {
return bytes_1.arrayify(new Uint8Array(Buffer.from(textData, "base64")));
}
exports.decode = decode;
;
function encode(data) {
return Buffer.from(bytes_1.arrayify(data)).toString("base64");
}
exports.encode = encode;

1
packages/basex/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.124";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.124";

52
packages/basex/index.d.ts vendored Normal file
View File

@ -0,0 +1,52 @@
/**
* var basex = require("base-x");
*
* This implementation is heavily based on base-x. The main reason to
* deviate was to prevent the dependency of Buffer.
*
* Contributors:
*
* base-x encoding
* Forked from https://github.com/cryptocoinjs/bs58
* Originally written by Mike Hearn for BitcoinJ
* Copyright (c) 2011 Google Inc
* Ported to JavaScript by Stefan Thomas
* Merged Buffer refactorings from base58-native by Stephen Pair
* Copyright (c) 2013 BitPay Inc
*
* The MIT License (MIT)
*
* Copyright base-x contributors (c) 2016
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
import { BytesLike } from "@ethersproject/bytes";
export declare class BaseX {
readonly alphabet: string;
readonly base: number;
private _alphabetMap;
private _leader;
constructor(alphabet: string);
encode(value: BytesLike): string;
decode(value: string): Uint8Array;
}
declare const Base32: BaseX;
declare const Base58: BaseX;
export { Base32, Base58 };

123
packages/basex/index.js Normal file
View File

@ -0,0 +1,123 @@
"use strict";
/**
* var basex = require("base-x");
*
* This implementation is heavily based on base-x. The main reason to
* deviate was to prevent the dependency of Buffer.
*
* Contributors:
*
* base-x encoding
* Forked from https://github.com/cryptocoinjs/bs58
* Originally written by Mike Hearn for BitcoinJ
* Copyright (c) 2011 Google Inc
* Ported to JavaScript by Stefan Thomas
* Merged Buffer refactorings from base58-native by Stephen Pair
* Copyright (c) 2013 BitPay Inc
*
* The MIT License (MIT)
*
* Copyright base-x contributors (c) 2016
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
var bytes_1 = require("@ethersproject/bytes");
var properties_1 = require("@ethersproject/properties");
var BaseX = /** @class */ (function () {
function BaseX(alphabet) {
properties_1.defineReadOnly(this, "alphabet", alphabet);
properties_1.defineReadOnly(this, "base", alphabet.length);
properties_1.defineReadOnly(this, "_alphabetMap", {});
properties_1.defineReadOnly(this, "_leader", alphabet.charAt(0));
// pre-compute lookup table
for (var i = 0; i < alphabet.length; i++) {
this._alphabetMap[alphabet.charAt(i)] = i;
}
}
BaseX.prototype.encode = function (value) {
var source = bytes_1.arrayify(value);
if (source.length === 0) {
return "";
}
var digits = [0];
for (var i = 0; i < source.length; ++i) {
var carry = source[i];
for (var j = 0; j < digits.length; ++j) {
carry += digits[j] << 8;
digits[j] = carry % this.base;
carry = (carry / this.base) | 0;
}
while (carry > 0) {
digits.push(carry % this.base);
carry = (carry / this.base) | 0;
}
}
var string = "";
// deal with leading zeros
for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) {
string += this._leader;
}
// convert digits to a string
for (var q = digits.length - 1; q >= 0; --q) {
string += this.alphabet[digits[q]];
}
return string;
};
BaseX.prototype.decode = function (value) {
if (typeof (value) !== "string") {
throw new TypeError("Expected String");
}
var bytes = [];
if (value.length === 0) {
return new Uint8Array(bytes);
}
bytes.push(0);
for (var i = 0; i < value.length; i++) {
var byte = this._alphabetMap[value[i]];
if (byte === undefined) {
throw new Error("Non-base" + this.base + " character");
}
var carry = byte;
for (var j = 0; j < bytes.length; ++j) {
carry += bytes[j] * this.base;
bytes[j] = carry & 0xff;
carry >>= 8;
}
while (carry > 0) {
bytes.push(carry & 0xff);
carry >>= 8;
}
}
// deal with leading zeros
for (var k = 0; value[k] === this._leader && k < value.length - 1; ++k) {
bytes.push(0);
}
return bytes_1.arrayify(new Uint8Array(bytes.reverse()));
};
return BaseX;
}());
exports.BaseX = BaseX;
var Base32 = new BaseX("abcdefghijklmnopqrstuvwxyz234567");
exports.Base32 = Base32;
var Base58 = new BaseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
exports.Base58 = Base58;
//console.log(Base58.decode("Qmd2V777o5XvJbYMeMb8k2nU5f8d3ciUQ5YpYuWhzv8iDj"))
//console.log(Base58.encode(Base58.decode("Qmd2V777o5XvJbYMeMb8k2nU5f8d3ciUQ5YpYuWhzv8iDj")))

1
packages/bignumber/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.126";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.126";

27
packages/bignumber/bignumber.d.ts vendored Normal file
View File

@ -0,0 +1,27 @@
import { Bytes, Hexable } from "@ethersproject/bytes";
export declare type BigNumberish = BigNumber | Bytes | string | number;
export declare class BigNumber implements Hexable {
readonly _hex: string;
constructor(constructorGuard: any, hex: string);
fromTwos(value: number): BigNumber;
toTwos(value: number): BigNumber;
abs(): BigNumber;
add(other: BigNumberish): BigNumber;
sub(other: BigNumberish): BigNumber;
div(other: BigNumberish): BigNumber;
mul(other: BigNumberish): BigNumber;
mod(other: BigNumberish): BigNumber;
pow(other: BigNumberish): BigNumber;
maskn(value: number): BigNumber;
eq(other: BigNumberish): boolean;
lt(other: BigNumberish): boolean;
lte(other: BigNumberish): boolean;
gt(other: BigNumberish): boolean;
gte(other: BigNumberish): boolean;
isZero(): boolean;
toNumber(): number;
toString(): string;
toHexString(): string;
static from(value: any): BigNumber;
static isBigNumber(value: any): value is BigNumber;
}

View File

@ -0,0 +1,309 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* BigNumber
*
* A wrapper around the BN.js object. We use the BN.js library
* because it is used by elliptic, so it is required regardles.
*
*/
var BN = __importStar(require("bn.js"));
var bytes_1 = require("@ethersproject/bytes");
var properties_1 = require("@ethersproject/properties");
var errors = __importStar(require("@ethersproject/errors"));
var _constructorGuard = {};
var MAX_SAFE = 0x1fffffffffffff;
/*
export function isBigNumberLike(value: any): value is BigNumberish {
return (BigNumber.isBigNumber(value) ||
(!!((<any>value).toHexString)) ||
isBytes(value) ||
value.match(/^-?([0-9]+|0x[0-9a-f]+)$/i) ||
typeof(value) === "number");
}
*/
var BigNumber = /** @class */ (function () {
function BigNumber(constructorGuard, hex) {
var _newTarget = this.constructor;
errors.checkNew(_newTarget, BigNumber);
if (constructorGuard !== _constructorGuard) {
errors.throwError("cannot call consturtor directly; use BigNumber.from", errors.UNSUPPORTED_OPERATION, {
operation: "new (BigNumber)"
});
}
properties_1.defineReadOnly(this, "_hex", hex);
}
BigNumber.prototype.fromTwos = function (value) {
return toBigNumber(toBN(this).fromTwos(value));
};
BigNumber.prototype.toTwos = function (value) {
return toBigNumber(toBN(this).toTwos(value));
};
BigNumber.prototype.abs = function () {
if (this._hex[0] === "-") {
return BigNumber.from(this._hex.substring(1));
}
return this;
};
BigNumber.prototype.add = function (other) {
return toBigNumber(toBN(this).add(toBN(other)));
};
BigNumber.prototype.sub = function (other) {
return toBigNumber(toBN(this).sub(toBN(other)));
};
BigNumber.prototype.div = function (other) {
var o = BigNumber.from(other);
if (o.isZero()) {
throwFault("division by zero", "div");
}
return toBigNumber(toBN(this).div(toBN(other)));
};
BigNumber.prototype.mul = function (other) {
return toBigNumber(toBN(this).mul(toBN(other)));
};
BigNumber.prototype.mod = function (other) {
return toBigNumber(toBN(this).mod(toBN(other)));
};
BigNumber.prototype.pow = function (other) {
return toBigNumber(toBN(this).pow(toBN(other)));
};
BigNumber.prototype.maskn = function (value) {
return toBigNumber(toBN(this).maskn(value));
};
BigNumber.prototype.eq = function (other) {
return toBN(this).eq(toBN(other));
};
BigNumber.prototype.lt = function (other) {
return toBN(this).lt(toBN(other));
};
BigNumber.prototype.lte = function (other) {
return toBN(this).lte(toBN(other));
};
BigNumber.prototype.gt = function (other) {
return toBN(this).gt(toBN(other));
};
BigNumber.prototype.gte = function (other) {
return toBN(this).gte(toBN(other));
};
BigNumber.prototype.isZero = function () {
return toBN(this).isZero();
};
BigNumber.prototype.toNumber = function () {
try {
return toBN(this).toNumber();
}
catch (error) {
throwFault("overflow", "toNumber", this.toString());
}
return null;
};
BigNumber.prototype.toString = function () {
// Lots of people expect this, which we do not support, so check
if (arguments.length !== 0) {
errors.throwError("bigNumber.toString does not accept parameters", errors.UNEXPECTED_ARGUMENT, {});
}
return toBN(this).toString(10);
};
BigNumber.prototype.toHexString = function () {
return this._hex;
};
BigNumber.from = function (value) {
if (value instanceof BigNumber) {
return value;
}
if (typeof (value) === "string") {
if (value.match(/-?0x[0-9a-f]+/i)) {
return new BigNumber(_constructorGuard, toHex(value));
}
if (value.match(/^-?[0-9]+$/)) {
return new BigNumber(_constructorGuard, toHex(new BN.BN(value)));
}
return errors.throwArgumentError("invalid BigNumber string", "value", value);
}
if (typeof (value) === "number") {
if (value % 1) {
throwFault("underflow", "BigNumber.from", value);
}
if (value >= MAX_SAFE || value <= -MAX_SAFE) {
throwFault("overflow", "BigNumber.from", value);
}
return BigNumber.from(String(value));
}
if (typeof (value) === "bigint") {
return BigNumber.from(value.toString());
}
if (bytes_1.isBytes(value)) {
return BigNumber.from(bytes_1.hexlify(value));
}
if (value._hex && bytes_1.isHexString(value._hex)) {
return BigNumber.from(value._hex);
}
if (value.toHexString) {
value = value.toHexString();
if (typeof (value) === "string") {
return BigNumber.from(value);
}
}
return errors.throwArgumentError("invalid BigNumber value", "value", value);
};
BigNumber.isBigNumber = function (value) {
return properties_1.isNamedInstance(this, value);
};
return BigNumber;
}());
exports.BigNumber = BigNumber;
/*
export function bigNumberify(value: BigNumberish): BigNumber {
if (BigNumber.isBigNumber(value)) { return value; }
return new BigNumber(value);
}
*/
/*
function zeros(length) {
let result = "";
while (result.length < length) { tens += "0"; }
return result;
}
export class FixedNumber {
readonly value: BigNumber;
readonly decimalPlaces: number;
constructor(value: BigNumberish, decimalPlaces: number) {
defineReadOnly(this, "value", bigNumberify(value));
defineReadOnly(this, "decimalPlaces", decimalPlaces);
}
toString(): string {
return formatUnits(this.value, this.decimalPlaces);
}
static fromString(value: string): FixedNumber {
let comps = value.split(".");
let decimalPlaces = 0;
if (comps.length === 2) { decimalPlaces = comps[1].length; }
return new FixedNumber(parseUnits(value, decimalPlaces), decimalPlaces);
}
*/
/*
readonly negative: boolean;
readonly whole: BigNumber;
readonly fraction: BigNumber;
constructor(whole: BigNumberish, fraction: BigNumberish, negative?: boolean) {
if (whole.lt(constants.Zero)) {
errors.throwError("whole component must be positive", errors.INVALID_ARGUMENT, {
argument: whole,
value: whole
});
}
defineReadOnly(this, "whole", bigNumberify(whole));
defineReadOnly(this, "fraction", bigNumberify(fraction));
defineReadOnly(this, "negative", !!boolean);
}
*/
/*
toHexString(bitWidth?: number, decimalPlaces?: number, signed?: boolean): string {
if (bitWidth == null) { bitWidth = 128; }
if (decimalPlaces == null) { decimalPlaces = 18; }
if (signed == null) { signed = true; }
return null;
}
static fromValue(value: BigNumberish, decimalPlaces: number): FixedNumber {
let negative = false;
if (value.lt(constants.Zero)) {
negative = true;
value = value.abs();
}
let tens = bigNumberify("1" + zeros(decimalPlaces));
return new FixedNumber(value.divide(tens), value.mod(tens), negative);
}
let negative = false;
if (value.substring(0, 1) === "-") {
negative = true;
value = value.substring(1);
}
if (value !== "." && value !== "") {
let comps = value.split(".");
if (comps.length === 1) {
return new FixedNumber(comps[0], 0, negative);
} else if (comps.length === 2) {
if (comps[0] === "") { comps[0] = "0"; }
if (comps[1] === "") { comps[1] = "0"; }
return new FixedNumber(comps[0], comps[1], negative);
}
}
errors.throwError("invalid fixed-point value", errors.INVALID_ARGUMENT, {
argument: "value",
value: value
});
return null;
*/
//}
// Normalize the hex string
function toHex(value) {
// For BN, call on the hex string
if (typeof (value) !== "string") {
return toHex(value.toString(16));
}
// If negative, prepend the negative sign to the normalized positive value
if (value[0] === "-") {
// Strip off the negative sign
value = value.substring(1);
// Cannot have mulitple negative signs (e.g. "--0x04")
if (value[0] === "-") {
errors.throwArgumentError("invalid hex", "value", value);
}
// Call toHex on the positive component
value = toHex(value);
// Do not allow "-0x00"
if (value === "0x00") {
return value;
}
// Negate the value
return "-" + value;
}
// Add a "0x" prefix if missing
if (value.substring(0, 2) !== "0x") {
value = "0x" + value;
}
// Normalize zero
if (value === "0x") {
return "0x00";
}
// Make the string even length
if (value.length % 2) {
value = "0x0" + value.substring(2);
}
// Trim to smallest even-length string
while (value.length > 4 && value.substring(0, 4) === "0x00") {
value = "0x" + value.substring(4);
}
return value;
}
function toBigNumber(value) {
return BigNumber.from(toHex(value));
}
function toBN(value) {
var hex = BigNumber.from(value).toHexString();
if (hex[0] === "-") {
return (new BN.BN("-" + hex.substring(3), 16));
}
return new BN.BN(hex.substring(2), 16);
}
function throwFault(fault, operation, value) {
var params = { fault: fault, operation: operation };
if (value != null) {
params.value = value;
}
return errors.throwError(fault, errors.NUMERIC_FAULT, params);
}

35
packages/bignumber/fixednumber.d.ts vendored Normal file
View File

@ -0,0 +1,35 @@
import { BytesLike } from "@ethersproject/bytes";
import { BigNumber, BigNumberish } from "./bignumber";
export declare function formatFixed(value: BigNumberish, decimals?: string | BigNumberish): string;
export declare function parseFixed(value: string, decimals?: BigNumberish): BigNumber;
export declare class FixedFormat {
readonly signed: boolean;
readonly width: number;
readonly decimals: number;
readonly name: string;
readonly _multiplier: BigNumber;
constructor(constructorGuard: any, signed: boolean, width: number, decimals: number);
static from(value: any): FixedFormat;
static isInstance(value: any): value is FixedFormat;
}
export declare class FixedNumber {
readonly format: FixedFormat;
readonly _hex: string;
readonly _value: string;
constructor(constructorGuard: any, hex: string, value: string, format?: FixedFormat);
_checkFormat(other: FixedNumber): void;
addUnsafe(other: FixedNumber): FixedNumber;
subUnsafe(other: FixedNumber): FixedNumber;
mulUnsafe(other: FixedNumber): FixedNumber;
divUnsafe(other: FixedNumber): FixedNumber;
round(decimals?: number): FixedNumber;
toString(): string;
toHexString(width?: number): string;
toUnsafeFloat(): number;
toFormat(format: FixedFormat | string): FixedNumber;
static fromValue(value: BigNumber, decimals?: BigNumberish, format?: FixedFormat | string): FixedNumber;
static fromString(value: string, format?: FixedFormat | string): FixedNumber;
static fromBytes(value: BytesLike, format?: FixedFormat | string): FixedNumber;
static from(value: any, format?: FixedFormat | string): FixedNumber;
static isFixedNumber(value: any): value is FixedNumber;
}

View File

@ -0,0 +1,321 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var bytes_1 = require("@ethersproject/bytes");
var errors = __importStar(require("@ethersproject/errors"));
var properties_1 = require("@ethersproject/properties");
var bignumber_1 = require("./bignumber");
var _constructorGuard = {};
var Zero = bignumber_1.BigNumber.from(0);
var NegativeOne = bignumber_1.BigNumber.from(-1);
function throwFault(message, fault, operation, value) {
var params = { fault: fault, operation: operation };
if (value !== undefined) {
params.value = value;
}
return errors.throwError(message, errors.NUMERIC_FAULT, params);
}
// Constant to pull zeros from for multipliers
var zeros = "0";
while (zeros.length < 256) {
zeros += zeros;
}
// Returns a string "1" followed by decimal "0"s
function getMultiplier(decimals) {
if (typeof (decimals) !== "number") {
try {
decimals = bignumber_1.BigNumber.from(decimals).toNumber();
}
catch (e) { }
}
if (typeof (decimals) === "number" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) {
return ("1" + zeros.substring(0, decimals));
}
return errors.throwArgumentError("invalid decimal size", "decimals", decimals);
}
function formatFixed(value, decimals) {
if (decimals == null) {
decimals = 0;
}
var multiplier = getMultiplier(decimals);
// Make sure wei is a big number (convert as necessary)
value = bignumber_1.BigNumber.from(value);
var negative = value.lt(Zero);
if (negative) {
value = value.mul(NegativeOne);
}
var fraction = value.mod(multiplier).toString();
while (fraction.length < multiplier.length - 1) {
fraction = "0" + fraction;
}
// Strip training 0
fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
var whole = value.div(multiplier).toString();
value = whole + "." + fraction;
if (negative) {
value = "-" + value;
}
return value;
}
exports.formatFixed = formatFixed;
function parseFixed(value, decimals) {
if (decimals == null) {
decimals = 0;
}
var multiplier = getMultiplier(decimals);
if (typeof (value) !== "string" || !value.match(/^-?[0-9.,]+$/)) {
errors.throwArgumentError("invalid decimal value", "value", value);
}
if (multiplier.length - 1 === 0) {
return bignumber_1.BigNumber.from(value);
}
// Is it negative?
var negative = (value.substring(0, 1) === "-");
if (negative) {
value = value.substring(1);
}
if (value === ".") {
errors.throwArgumentError("missing value", "value", value);
}
// Split it into a whole and fractional part
var comps = value.split(".");
if (comps.length > 2) {
errors.throwArgumentError("too many decimal points", "value", value);
}
var whole = comps[0], fraction = comps[1];
if (!whole) {
whole = "0";
}
if (!fraction) {
fraction = "0";
}
// Prevent underflow
if (fraction.length > multiplier.length - 1) {
throwFault("fractional component exceeds decimals", "underflow", "parseFixed");
}
// Fully pad the string with zeros to get to wei
while (fraction.length < multiplier.length - 1) {
fraction += "0";
}
var wholeValue = bignumber_1.BigNumber.from(whole);
var fractionValue = bignumber_1.BigNumber.from(fraction);
var wei = (wholeValue.mul(multiplier)).add(fractionValue);
if (negative) {
wei = wei.mul(NegativeOne);
}
return wei;
}
exports.parseFixed = parseFixed;
var FixedFormat = /** @class */ (function () {
function FixedFormat(constructorGuard, signed, width, decimals) {
properties_1.defineReadOnly(this, "signed", signed);
properties_1.defineReadOnly(this, "width", width);
properties_1.defineReadOnly(this, "decimals", decimals);
var name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals);
properties_1.defineReadOnly(this, "name", name);
properties_1.defineReadOnly(this, "_multiplier", getMultiplier(decimals));
}
FixedFormat.from = function (value) {
if (value instanceof FixedFormat) {
return value;
}
var signed = true;
var width = 128;
var decimals = 18;
if (typeof (value) === "string") {
if (value === "fixed") {
// defaults...
}
else if (value === "ufixed") {
signed = false;
}
else if (value != null) {
var match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
if (!match) {
errors.throwArgumentError("invalid fixed format", "format", value);
}
signed = (match[1] !== "u");
width = parseInt(match[2]);
decimals = parseInt(match[3]);
}
}
else if (value) {
var check = function (key, type, defaultValue) {
if (value[key] == null) {
return defaultValue;
}
if (typeof (value[key]) !== type) {
errors.throwArgumentError("invalid fixed format (" + key + " not " + type + ")", "format." + key, value[key]);
}
return value[key];
};
signed = check("signed", "boolean", signed);
width = check("width", "number", width);
decimals = check("decimals", "number", decimals);
}
if (width % 8) {
errors.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width);
}
if (decimals > 80) {
errors.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals);
}
return new FixedFormat(_constructorGuard, signed, width, decimals);
};
FixedFormat.isInstance = function (value) {
return properties_1.isNamedInstance(this, value);
};
return FixedFormat;
}());
exports.FixedFormat = FixedFormat;
var FixedNumber = /** @class */ (function () {
function FixedNumber(constructorGuard, hex, value, format) {
var _newTarget = this.constructor;
errors.checkNew(_newTarget, FixedNumber);
properties_1.defineReadOnly(this, 'format', format);
properties_1.defineReadOnly(this, '_hex', hex);
properties_1.defineReadOnly(this, '_value', value);
}
FixedNumber.prototype._checkFormat = function (other) {
if (this.format.name !== other.format.name) {
errors.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other);
}
};
FixedNumber.prototype.addUnsafe = function (other) {
this._checkFormat(other);
var a = parseFixed(this._value, this.format.decimals);
var b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.add(b), this.format.decimals, this.format);
};
FixedNumber.prototype.subUnsafe = function (other) {
this._checkFormat(other);
var a = parseFixed(this._value, this.format.decimals);
var b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.sub(b), this.format.decimals, this.format);
};
FixedNumber.prototype.mulUnsafe = function (other) {
this._checkFormat(other);
var a = parseFixed(this._value, this.format.decimals);
var b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.mul(b).div(this.format._multiplier), this.format.decimals, this.format);
};
FixedNumber.prototype.divUnsafe = function (other) {
this._checkFormat(other);
var a = parseFixed(this._value, this.format.decimals);
var b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.mul(this.format._multiplier).div(b), this.format.decimals, this.format);
};
// @TODO: Support other rounding algorithms
FixedNumber.prototype.round = function (decimals) {
if (decimals == null) {
decimals = 0;
}
if (decimals < 0 || decimals > 80 || (decimals % 1)) {
errors.throwArgumentError("invalid decimal cound", "decimals", decimals);
}
// If we are already in range, we're done
var comps = this.toString().split(".");
if (comps[1].length <= decimals) {
return this;
}
// Bump the value up by the 0.00...0005
var bump = "0." + zeros.substring(0, decimals) + "5";
comps = this.addUnsafe(FixedNumber.fromString(bump, this.format))._value.split(".");
// Now it is safe to truncate
return FixedNumber.fromString(comps[0] + "." + comps[1].substring(0, decimals));
};
FixedNumber.prototype.toString = function () { return this._value; };
FixedNumber.prototype.toHexString = function (width) {
if (width == null) {
return this._hex;
}
if (width % 8) {
errors.throwArgumentError("invalid byte width", "width", width);
}
var hex = bignumber_1.BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString();
return bytes_1.hexZeroPad(hex, width / 8);
};
FixedNumber.prototype.toUnsafeFloat = function () { return parseFloat(this.toString()); };
FixedNumber.prototype.toFormat = function (format) {
return FixedNumber.fromString(this._value, format);
};
FixedNumber.fromValue = function (value, decimals, format) {
// If decimals looks more like a format, and there is no format, shift the parameters
if (format == null && decimals != null && (FixedFormat.isInstance(decimals) || typeof (decimals) === "string")) {
format = decimals;
decimals = null;
}
if (decimals == null) {
decimals = 0;
}
if (format == null) {
format = "fixed";
}
var fixedFormat = (FixedFormat.isInstance(format) ? format : FixedFormat.from(format));
return FixedNumber.fromString(formatFixed(value, decimals), fixedFormat);
};
FixedNumber.fromString = function (value, format) {
if (format == null) {
format = "fixed";
}
var fixedFormat = (FixedFormat.isInstance(format) ? format : FixedFormat.from(format));
var numeric = parseFixed(value, fixedFormat.decimals);
if (!fixedFormat.signed && numeric.lt(Zero)) {
throwFault("unsigned value cannot be negative", "overflow", "value", value);
}
var hex = null;
if (fixedFormat.signed) {
hex = numeric.toTwos(fixedFormat.width).toHexString();
}
else {
hex = numeric.toHexString();
hex = bytes_1.hexZeroPad(hex, fixedFormat.width / 8);
}
var decimal = formatFixed(numeric, fixedFormat.decimals);
return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);
};
FixedNumber.fromBytes = function (value, format) {
if (format == null) {
format = "fixed";
}
var fixedFormat = (FixedFormat.isInstance(format) ? format : FixedFormat.from(format));
if (bytes_1.arrayify(value).length > fixedFormat.width / 8) {
throw new Error("overflow");
}
var numeric = bignumber_1.BigNumber.from(value);
if (fixedFormat.signed) {
numeric = numeric.fromTwos(fixedFormat.width);
}
var hex = numeric.toTwos((fixedFormat.signed ? 0 : 1) + fixedFormat.width).toHexString();
var decimal = formatFixed(numeric, fixedFormat.decimals);
return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);
};
FixedNumber.from = function (value, format) {
if (typeof (value) === "string") {
return FixedNumber.fromString(value, format);
}
if (bytes_1.isBytes(value)) {
return FixedNumber.fromBytes(value, format);
}
try {
return FixedNumber.fromValue(value, 0, format);
}
catch (error) {
// Allow NUMERIC_FAULT to bubble up
if (error.code !== errors.INVALID_ARGUMENT) {
throw error;
}
}
return errors.throwArgumentError("invalid FixedNumber value", "value", value);
};
FixedNumber.isFixedNumber = function (value) {
return properties_1.isNamedInstance(this, value);
};
return FixedNumber;
}());
exports.FixedNumber = FixedNumber;

2
packages/bignumber/index.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
export { BigNumber, BigNumberish } from "./bignumber";
export { FixedNumber } from "./fixednumber";

View File

@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bignumber_1 = require("./bignumber");
exports.BigNumber = bignumber_1.BigNumber;
var fixednumber_1 = require("./fixednumber");
exports.FixedNumber = fixednumber_1.FixedNumber;

1
packages/bytes/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.126";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.126";

39
packages/bytes/index.d.ts vendored Normal file
View File

@ -0,0 +1,39 @@
export declare type Bytes = ArrayLike<number>;
export declare type BytesLike = Bytes | string;
export declare type DataOptions = {
allowMissingPrefix?: boolean;
allowOddLength?: boolean;
};
export interface Hexable {
toHexString(): string;
}
export declare type SignatureLike = {
r: string;
s?: string;
_vs?: string;
recoveryParam?: number;
v?: number;
} | BytesLike;
export interface Signature {
r: string;
s: string;
_vs: string;
recoveryParam: number;
v: number;
}
export declare function isBytesLike(value: any): value is BytesLike;
export declare function isBytes(value: any): value is Bytes;
export declare function arrayify(value: BytesLike | Hexable | number, options?: DataOptions): Uint8Array;
export declare function concat(items: Array<BytesLike>): Uint8Array;
export declare function stripZeros(value: BytesLike): Uint8Array;
export declare function zeroPad(value: BytesLike, length: number): Uint8Array;
export declare function isHexString(value: any, length?: number): boolean;
export declare function hexlify(value: BytesLike | Hexable | number, options?: DataOptions): string;
export declare function hexDataLength(data: BytesLike): number;
export declare function hexDataSlice(data: BytesLike, offset: number, endOffset?: number): string;
export declare function hexConcat(items: Array<BytesLike>): string;
export declare function hexValue(value: BytesLike | Hexable | number): string;
export declare function hexStripZeros(value: BytesLike): string;
export declare function hexZeroPad(value: BytesLike, length: number): string;
export declare function splitSignature(signature: SignatureLike): Signature;
export declare function joinSignature(signature: Signature): string;

385
packages/bytes/index.js Normal file
View File

@ -0,0 +1,385 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var errors = __importStar(require("@ethersproject/errors"));
///////////////////////////////
function isHexable(value) {
return !!(value.toHexString);
}
function addSlice(array) {
if (array.slice) {
return array;
}
array.slice = function () {
var args = Array.prototype.slice.call(arguments);
return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));
};
return array;
}
function isBytesLike(value) {
return ((isHexString(value) && !(value.length % 2)) || isBytes(value));
}
exports.isBytesLike = isBytesLike;
function isBytes(value) {
if (value == null) {
return false;
}
if (value.constructor === Uint8Array) {
return true;
}
if (typeof (value) === "string") {
return false;
}
if (value.length == null) {
return false;
}
for (var i = 0; i < value.length; i++) {
var v = value[i];
if (v < 0 || v >= 256 || (v % 1)) {
return false;
}
}
return true;
}
exports.isBytes = isBytes;
function arrayify(value, options) {
if (!options) {
options = {};
}
if (typeof (value) === "number") {
errors.checkSafeUint53(value, "invalid arrayify value");
var result = [];
while (value) {
result.unshift(value & 0xff);
value /= 256;
}
if (result.length === 0) {
result.push(0);
}
return addSlice(new Uint8Array(result));
}
if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
value = "0x" + value;
}
if (isHexable(value)) {
value = value.toHexString();
}
if (isHexString(value)) {
var hex = value.substring(2);
if (!options.allowOddLength && hex.length % 2) {
errors.throwArgumentError("hex data is odd-length", "value", value);
}
var result = [];
for (var i = 0; i < hex.length; i += 2) {
result.push(parseInt(hex.substring(i, i + 2), 16));
}
return addSlice(new Uint8Array(result));
}
if (isBytes(value)) {
return addSlice(new Uint8Array(value));
}
return errors.throwArgumentError("invalid arrayify value", "value", value);
}
exports.arrayify = arrayify;
function concat(items) {
var objects = items.map(function (item) { return arrayify(item); });
var length = objects.reduce(function (accum, item) { return (accum + item.length); }, 0);
var result = new Uint8Array(length);
objects.reduce(function (offset, object) {
result.set(object, offset);
return offset + object.length;
}, 0);
return addSlice(result);
}
exports.concat = concat;
function stripZeros(value) {
var result = arrayify(value);
if (result.length === 0) {
return result;
}
// Find the first non-zero entry
var start = 0;
while (start < result.length && result[start] === 0) {
start++;
}
// If we started with zeros, strip them
if (start) {
result = result.slice(start);
}
return result;
}
exports.stripZeros = stripZeros;
function zeroPad(value, length) {
value = arrayify(value);
if (value.length > length) {
errors.throwArgumentError("value out of range", "value", arguments[0]);
}
var result = new Uint8Array(length);
result.set(value, length - value.length);
return addSlice(result);
}
exports.zeroPad = zeroPad;
function isHexString(value, length) {
if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
return false;
}
if (length && value.length !== 2 + 2 * length) {
return false;
}
return true;
}
exports.isHexString = isHexString;
var HexCharacters = "0123456789abcdef";
function hexlify(value, options) {
if (!options) {
options = {};
}
if (typeof (value) === "number") {
errors.checkSafeUint53(value, "invalid hexlify value");
var hex = "";
while (value) {
hex = HexCharacters[value & 0x0f] + hex;
value = Math.floor(value / 16);
}
if (hex.length) {
if (hex.length % 2) {
hex = "0" + hex;
}
return "0x" + hex;
}
return "0x00";
}
if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
value = "0x" + value;
}
if (isHexable(value)) {
return value.toHexString();
}
if (isHexString(value)) {
if (!options.allowOddLength && value.length % 2) {
errors.throwArgumentError("hex data is odd-length", "value", value);
}
return value.toLowerCase();
}
if (isBytes(value)) {
var result = "0x";
for (var i = 0; i < value.length; i++) {
var v = value[i];
result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];
}
return result;
}
return errors.throwArgumentError("invalid hexlify value", "value", value);
}
exports.hexlify = hexlify;
/*
function unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number {
if (typeof(value) === "string" && value.length % 2 && value.substring(0, 2) === "0x") {
return "0x0" + value.substring(2);
}
return value;
}
*/
function hexDataLength(data) {
if (typeof (data) !== "string") {
data = hexlify(data);
}
else if (!isHexString(data) || (data.length % 2)) {
return null;
}
return (data.length - 2) / 2;
}
exports.hexDataLength = hexDataLength;
function hexDataSlice(data, offset, endOffset) {
if (typeof (data) !== "string") {
data = hexlify(data);
}
else if (!isHexString(data) || (data.length % 2)) {
errors.throwArgumentError("invalid hexData", "value", data);
}
offset = 2 + 2 * offset;
if (endOffset != null) {
return "0x" + data.substring(offset, 2 + 2 * endOffset);
}
return "0x" + data.substring(offset);
}
exports.hexDataSlice = hexDataSlice;
function hexConcat(items) {
var result = "0x";
items.forEach(function (item) {
result += hexlify(item).substring(2);
});
return result;
}
exports.hexConcat = hexConcat;
function hexValue(value) {
var trimmed = hexStripZeros(hexlify(value, { allowOddLength: true }));
if (trimmed === "0x") {
return "0x0";
}
return trimmed;
}
exports.hexValue = hexValue;
function hexStripZeros(value) {
if (typeof (value) !== "string") {
value = hexlify(value);
}
if (!isHexString(value)) {
errors.throwArgumentError("invalid hex string", "value", value);
}
value = value.substring(2);
var offset = 0;
while (offset < value.length && value[offset] === "0") {
offset++;
}
return "0x" + value.substring(offset);
}
exports.hexStripZeros = hexStripZeros;
function hexZeroPad(value, length) {
if (typeof (value) !== "string") {
value = hexlify(value);
}
else if (!isHexString(value)) {
errors.throwArgumentError("invalid hex string", "value", value);
}
if (value.length > 2 * length + 2) {
errors.throwArgumentError("value out of range", "value", arguments[1]);
}
while (value.length < 2 * length + 2) {
value = "0x0" + value.substring(2);
}
return value;
}
exports.hexZeroPad = hexZeroPad;
function splitSignature(signature) {
var result = {
r: "0x",
s: "0x",
_vs: "0x",
recoveryParam: 0,
v: 0
};
if (isBytesLike(signature)) {
var bytes = arrayify(signature);
if (bytes.length !== 65) {
errors.throwArgumentError("invalid signature string; must be 65 bytes", "signature", signature);
}
// Get the r and s
result.r = hexlify(bytes.slice(0, 32));
result.s = hexlify(bytes.slice(32, 64));
// Reduce v to the canonical 27 or 28
result.v = bytes[64];
if (result.v !== 27 && result.v !== 28) {
result.v = 27 + (result.v % 2);
}
// Compute recoveryParam from v
result.recoveryParam = (result.v - 27);
// Compute _vs from recoveryParam and s
if (result.recoveryParam) {
bytes[32] |= 0x80;
}
result._vs = hexlify(bytes.slice(32, 64));
}
else {
result.r = signature.r;
result.s = signature.s;
result.v = signature.v;
result.recoveryParam = signature.recoveryParam;
result._vs = signature._vs;
// Normalize v into a canonical 27 or 28
if (result.v != null && !(result.v == 27 || result.v == 28)) {
result.v = 27 + (result.v % 2);
}
// Populate a missing v or recoveryParam if possible
if (result.recoveryParam == null && result.v != null) {
result.recoveryParam = 1 - (result.v % 2);
}
else if (result.recoveryParam != null && result.v == null) {
result.v = 27 + result.recoveryParam;
}
else if (result.recoveryParam != null && result.v != null) {
if (result.v !== 27 + result.recoveryParam) {
errors.throwArgumentError("signature v mismatch recoveryParam", "signature", signature);
}
}
// Make sure r and s are padded properly
if (result.r != null) {
result.r = hexZeroPad(result.r, 32);
}
if (result.s != null) {
result.s = hexZeroPad(result.s, 32);
}
// If the _vs is available, use it to populate missing s, v and recoveryParam
// and verify non-missing s, v and recoveryParam
if (result._vs != null) {
result._vs = hexZeroPad(result._vs, 32);
if (result._vs.length > 66) {
errors.throwArgumentError("signature _vs overflow", "signature", signature);
}
var vs = arrayify(result._vs);
var recoveryParam = ((vs[0] >= 128) ? 1 : 0);
var v = 27 + result.recoveryParam;
// Use _vs to compute s
vs[0] &= 0x7f;
var s = hexlify(vs);
// Check _vs aggress with other parameters
if (result.s == null) {
result.s = s;
}
else if (result.s !== s) {
errors.throwArgumentError("signature v mismatch _vs", "signature", signature);
}
if (result.v == null) {
result.v = v;
}
else if (result.v !== v) {
errors.throwArgumentError("signature v mismatch _vs", "signature", signature);
}
if (recoveryParam == null) {
result.recoveryParam = recoveryParam;
}
else if (result.recoveryParam !== recoveryParam) {
errors.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature);
}
}
// After all populating, both v and recoveryParam are still missing...
if (result.v == null && result.recoveryParam == null) {
errors.throwArgumentError("signature requires at least one of recoveryParam, v or _vs", "signature", signature);
}
// Check for canonical v
if (result.v !== 27 && result.v !== 28) {
errors.throwArgumentError("signature v not canonical", "signature", signature);
}
// Check that r and s are in range
if (result.r.length > 66 || result.s.length > 66) {
errors.throwArgumentError("signature overflow r or s", "signature", signature);
}
if (result._vs == null) {
var vs = arrayify(result.s);
if (vs[0] >= 128) {
errors.throwArgumentError("signature s out of range", "signature", signature);
}
if (result.recoveryParam) {
vs[0] |= 0x80;
}
result._vs = hexlify(vs);
}
}
return result;
}
exports.splitSignature = splitSignature;
function joinSignature(signature) {
signature = splitSignature(signature);
return hexlify(concat([
signature.r,
signature.s,
(signature.recoveryParam ? "0x1c" : "0x1b")
]));
}
exports.joinSignature = joinSignature;

1
packages/cli/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.129";

3
packages/cli/_version.js Normal file
View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.129";

View File

@ -0,0 +1,182 @@
#!/usr/bin/env node
'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 __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = __importDefault(require("fs"));
var path_1 = require("path");
var ethers_1 = require("ethers");
var cli_1 = require("../cli");
var typescript_1 = require("../typescript");
var solc_1 = require("../solc");
function computeHash(content) {
var bareContent = content.replace(/\/\*\* Content Hash: 0x[0-9A-F]{64} \*\//i, '/** Content Hash: */');
return ethers_1.ethers.utils.id(bareContent);
}
function checkHash(content) {
var match = content.match(/\/\*\* Content Hash: (0x[0-9A-F]{64}) \*\//i);
return (match && match[1] === computeHash(content));
}
function addContentHash(content) {
var contentHash = computeHash("/** Content Hash: */\n" + content);
return "/** Content Hash: " + contentHash + " */\n" + content;
}
function save(path, content, force) {
if (fs_1.default.existsSync(path) && !force) {
var oldContent = fs_1.default.readFileSync(path).toString();
if (!checkHash(oldContent)) {
return false;
}
}
fs_1.default.writeFileSync(path, content);
return true;
}
function walkFilenames(filenames) {
var result = [];
filenames.forEach(function (filename) {
var stat = fs_1.default.statSync(filename);
if (stat.isDirectory()) {
walkFilenames(fs_1.default.readdirSync(filename).map(function (x) { return path_1.join(filename, x); })).forEach(function (filename) {
result.push(filename);
});
}
else if (stat.isFile()) {
result.push(filename);
}
});
return result;
}
var cli = new cli_1.CLI("generate");
var GeneratePlugin = /** @class */ (function (_super) {
__extends(GeneratePlugin, _super);
function GeneratePlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
GeneratePlugin.prototype.prepareOptions = function (argParser) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareOptions.call(this, argParser)];
case 1:
_a.sent();
this.output = argParser.consumeOption("output");
this.force = argParser.consumeFlag("force");
this.optimize = argParser.consumeFlag("no-optimize");
this.noBytecode = argParser.consumeFlag("no-bytecode");
return [2 /*return*/];
}
});
});
};
GeneratePlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_a.sent();
if (args.length === 0) {
this.throwError("generate requires at least one FILENAME");
}
this.filenames = args;
return [2 /*return*/];
}
});
});
};
GeneratePlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
var output, success;
var _this = this;
return __generator(this, function (_a) {
output = typescript_1.header;
walkFilenames(this.filenames).forEach(function (filename) {
if (!filename.match(/\.sol$/)) {
return;
}
var contracts = null;
var content = fs_1.default.readFileSync(filename).toString();
try {
contracts = solc_1.compile(content, { filename: filename, optimize: _this.optimize });
}
catch (error) {
console.log(error);
if (error.errors) {
error.errors.forEach(function (error) {
console.log(error);
});
}
throw new Error("errors during compilation");
}
contracts.forEach(function (contract) {
output += typescript_1.generate(contract, (_this.noBytecode ? null : contract.bytecode));
output += "\n";
});
});
output = addContentHash(output.trim());
if (this.output) {
success = save(this.output, output, this.force);
if (!success) {
return [2 /*return*/, Promise.reject(new Error("File has been modified; use --force"))];
}
}
else {
console.log(output);
}
return [2 /*return*/, Promise.resolve(null)];
});
});
};
return GeneratePlugin;
}(cli_1.Plugin));
cli.addPlugin("generate", GeneratePlugin);
cli.run(process.argv.slice(2));

982
packages/cli/bin/ethers.js Normal file
View File

@ -0,0 +1,982 @@
#!/usr/bin/env node
"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 __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = __importDefault(require("fs"));
var repl_1 = __importDefault(require("repl"));
var util_1 = __importDefault(require("util"));
var vm_1 = __importDefault(require("vm"));
var ethers_1 = require("ethers");
var cli_1 = require("../cli");
var prompt_1 = require("../prompt");
var solc_1 = require("../solc");
function setupContext(context, plugin) {
context.provider = plugin.provider;
context.accounts = plugin.accounts;
if (!context.console) {
context.console = console;
}
if (!context.require) {
context.require = require;
}
if (!context.process) {
context.process = process;
}
context.ethers = ethers_1.ethers;
context.version = ethers_1.ethers.version;
context.Contract = ethers_1.ethers.Contract;
context.ContractFactory = ethers_1.ethers.ContractFactory;
context.Wallet = ethers_1.ethers.Wallet;
context.providers = ethers_1.ethers.providers;
context.utils = ethers_1.ethers.utils;
context.abiCoder = ethers_1.ethers.utils.defaultAbiCoder;
context.BN = ethers_1.ethers.BigNumber;
context.BigNumber = ethers_1.ethers.BigNumber;
context.FixedNumber = ethers_1.ethers.FixedNumber;
context.getAddress = ethers_1.ethers.utils.getAddress;
context.getContractAddress = ethers_1.ethers.utils.getContractAddress;
context.getIcapAddress = ethers_1.ethers.utils.getIcapAddress;
context.arrayify = ethers_1.ethers.utils.arrayify;
context.hexlify = ethers_1.ethers.utils.hexlify;
context.joinSignature = ethers_1.ethers.utils.joinSignature;
context.splitSignature = ethers_1.ethers.utils.splitSignature;
context.id = ethers_1.ethers.utils.id;
context.keccak256 = ethers_1.ethers.utils.keccak256;
context.namehash = ethers_1.ethers.utils.namehash;
context.sha256 = ethers_1.ethers.utils.sha256;
context.parseEther = ethers_1.ethers.utils.parseEther;
context.parseUnits = ethers_1.ethers.utils.parseUnits;
context.formatEther = ethers_1.ethers.utils.formatEther;
context.formatUnits = ethers_1.ethers.utils.formatUnits;
context.randomBytes = ethers_1.ethers.utils.randomBytes;
context.constants = ethers_1.ethers.constants;
context.parseTransaction = ethers_1.ethers.utils.parseTransaction;
context.serializeTransaction = ethers_1.ethers.utils.serializeTransaction;
context.toUtf8Bytes = ethers_1.ethers.utils.toUtf8Bytes;
context.toUtf8String = ethers_1.ethers.utils.toUtf8String;
}
var cli = new cli_1.CLI("sandbox");
var SandboxPlugin = /** @class */ (function (_super) {
__extends(SandboxPlugin, _super);
function SandboxPlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
SandboxPlugin.getHelp = function () {
return {
name: "sandbox",
help: "Run a REPL VM environment with ethers"
};
};
SandboxPlugin.prototype.prepareOptions = function (argParser) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareOptions.call(this, argParser)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
SandboxPlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
var i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_a.sent();
if (args.length !== 0) {
this.throwUsageError("Unexpected argument - " + JSON.stringify(args[0]));
}
i = 0;
_a.label = 2;
case 2:
if (!(i < this.accounts.length)) return [3 /*break*/, 5];
return [4 /*yield*/, this.accounts[i].unlock()];
case 3:
_a.sent();
_a.label = 4;
case 4:
i++;
return [3 /*break*/, 2];
case 5: return [2 /*return*/];
}
});
});
};
SandboxPlugin.prototype.run = function () {
console.log("network: " + this.network.name + " (chainId: " + this.network.chainId + ")");
var nextPromiseId = 0;
function promiseWriter(output) {
if (output instanceof Promise) {
repl.context._p = output;
var promiseId_1 = nextPromiseId++;
output.then(function (result) {
console.log("\n<Promise id=" + promiseId_1 + " resolved>");
console.log(util_1.default.inspect(result));
repl.context._r = result;
repl.displayPrompt(true);
}, function (error) {
console.log("\n<Promise id=" + promiseId_1 + " rejected>");
console.log(util_1.default.inspect(error));
repl.displayPrompt(true);
});
return "<Promise id=" + promiseId_1 + " pending>";
}
return util_1.default.inspect(output);
}
var repl = repl_1.default.start({
input: process.stdin,
output: process.stdout,
prompt: (this.provider ? this.network.name : "no-network") + "> ",
writer: promiseWriter
});
setupContext(repl.context, this);
return new Promise(function (resolve) {
repl.on("exit", function () {
console.log("");
resolve(null);
});
});
};
return SandboxPlugin;
}(cli_1.Plugin));
cli.addPlugin("sandbox", SandboxPlugin);
var InitPlugin = /** @class */ (function (_super) {
__extends(InitPlugin, _super);
function InitPlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
InitPlugin.getHelp = function () {
return {
name: "init FILENAME",
help: "Create a new JSON wallet"
};
};
InitPlugin.getOptionHelp = function () {
return [
{
name: "[ --force ]",
help: "Overwrite any existing files"
}
];
};
InitPlugin.prototype.prepareOptions = function (argParser) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareOptions.call(this, argParser)];
case 1:
_a.sent();
this.force = argParser.consumeFlag("force");
return [2 /*return*/];
}
});
});
};
InitPlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_a.sent();
if (args.length !== 1) {
this.throwUsageError("init requires FILENAME");
}
this.filename = args[0];
return [2 /*return*/];
}
});
});
};
InitPlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
var password, confirm, wallet, progressBar, json;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.force && fs_1.default.existsSync(this.filename)) {
this.throwError('File already exists (use --force to overwrite)');
}
console.log("Creating a new JSON Wallet - " + this.filename);
console.log('Keep this password and file SAFE!! If lost or forgotten');
console.log('it CANNOT be recovered, by ANYone, EVER.');
return [4 /*yield*/, prompt_1.getPassword("Choose a password: ")];
case 1:
password = _a.sent();
return [4 /*yield*/, prompt_1.getPassword("Confirm password: ")];
case 2:
confirm = _a.sent();
if (password !== confirm) {
this.throwError("Passwords do not match");
}
wallet = ethers_1.ethers.Wallet.createRandom();
return [4 /*yield*/, prompt_1.getProgressBar("Encrypting")];
case 3:
progressBar = _a.sent();
return [4 /*yield*/, wallet.encrypt(password, {}, progressBar)];
case 4:
json = _a.sent();
try {
if (this.force) {
fs_1.default.writeFileSync(this.filename, json);
}
else {
fs_1.default.writeFileSync(this.filename, json, { flag: 'wx' });
}
console.log('New account address: ' + wallet.address);
console.log('Saved: ' + this.filename);
}
catch (error) {
if (error.code === 'EEXIST') {
this.throwError('File already exists (use --force to overwrite)');
}
this.throwError('Unknown Error: ' + error.message);
}
return [2 /*return*/];
}
});
});
};
return InitPlugin;
}(cli_1.Plugin));
cli.addPlugin("init", InitPlugin);
var FundPlugin = /** @class */ (function (_super) {
__extends(FundPlugin, _super);
function FundPlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
FundPlugin.getHelp = function () {
return {
name: "fund TARGET",
help: "Fund TARGET with testnet ether"
};
};
FundPlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_b.sent();
if (this.network.name !== "ropsten") {
this.throwError("Funding requires --network ropsten");
}
if (args.length !== 1) {
this.throwUsageError("fund requires ADDRESS");
}
_a = this;
return [4 /*yield*/, this.getAddress(args[0], "Cannot fund ZERO address", false)];
case 2:
_a.toAddress = _b.sent();
return [2 /*return*/];
}
});
});
};
FundPlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
var url;
return __generator(this, function (_a) {
url = "https:/" + "/api.ethers.io/api/v1/?action=fundAccount&address=" + this.toAddress.toLowerCase();
return [2 /*return*/, ethers_1.ethers.utils.fetchJson(url).then(function (data) {
console.log("Transaction Hash: " + data.hash);
})];
});
});
};
return FundPlugin;
}(cli_1.Plugin));
cli.addPlugin("fund", FundPlugin);
var InfoPlugin = /** @class */ (function (_super) {
__extends(InfoPlugin, _super);
function InfoPlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
InfoPlugin.getHelp = function () {
return {
name: "info [ TARGET ... ]",
help: "Dump info for accounts, addresses and ENS names"
};
};
InfoPlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
var runners, _a;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_b.sent();
this.queries = [];
runners = [];
this.accounts.forEach(function (account, index) {
_this.queries.push("Account #" + index);
runners.push(account.getAddress());
});
args.forEach(function (arg) {
if (ethers_1.ethers.utils.isAddress(arg)) {
_this.queries.push("Address: " + arg);
}
else {
_this.queries.push("ENS Name: " + arg);
}
runners.push(_this.provider.resolveName(arg));
});
_a = this;
return [4 /*yield*/, Promise.all(runners)];
case 2:
_a.addresses = _b.sent();
return [2 /*return*/];
}
});
});
};
InfoPlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
var i, address, _a, balance, nonce, code, reverse, info;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
i = 0;
_b.label = 1;
case 1:
if (!(i < this.addresses.length)) return [3 /*break*/, 4];
address = this.addresses[i];
return [4 /*yield*/, ethers_1.ethers.utils.resolveProperties({
balance: this.provider.getBalance(address),
nonce: this.provider.getTransactionCount(address),
code: this.provider.getCode(address),
reverse: this.provider.lookupAddress(address)
})];
case 2:
_a = _b.sent(), balance = _a.balance, nonce = _a.nonce, code = _a.code, reverse = _a.reverse;
info = {
"Address": address,
"Balance": (ethers_1.ethers.utils.formatEther(balance) + " ether"),
"Transaction Count": nonce
};
if (code != "0x") {
info["Code"] = code;
}
if (reverse) {
info["Reverse Lookup"] = reverse;
}
cli_1.dump(this.queries[i], info);
_b.label = 3;
case 3:
i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/];
}
});
});
};
return InfoPlugin;
}(cli_1.Plugin));
cli.addPlugin("info", InfoPlugin);
var SendPlugin = /** @class */ (function (_super) {
__extends(SendPlugin, _super);
function SendPlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
SendPlugin.getHelp = function () {
return {
name: "send TARGET ETHER",
help: "Send ETHER ether to TARGET form accounts[0]"
};
};
SendPlugin.getOptionHelp = function () {
return [
{
name: "[ --allow-zero ]",
help: "Allow sending to the address zero"
}
];
};
SendPlugin.prototype.prepareOptions = function (argParser) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareOptions.call(this, argParser)];
case 1:
_a.sent();
if (this.accounts.length !== 1) {
this.throwUsageError("send requires exacly one account");
}
this.allowZero = argParser.consumeFlag("allow-zero");
return [2 /*return*/];
}
});
});
};
SendPlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_b.sent();
if (args.length !== 2) {
this.throwUsageError("send requires exactly ADDRESS and AMOUNT");
}
_a = this;
return [4 /*yield*/, this.getAddress(args[0], "Cannot send to the zero address (use --allow-zero to override)", this.allowZero)];
case 2:
_a.toAddress = _b.sent();
this.value = ethers_1.ethers.utils.parseEther(args[1]);
return [2 /*return*/];
}
});
});
};
SendPlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.accounts[0].sendTransaction({
to: this.toAddress,
value: this.value
})];
case 1:
_a.sent();
;
return [2 /*return*/];
}
});
});
};
return SendPlugin;
}(cli_1.Plugin));
cli.addPlugin("send", SendPlugin);
var SweepPlugin = /** @class */ (function (_super) {
__extends(SweepPlugin, _super);
function SweepPlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
SweepPlugin.getHelp = function () {
return {
name: "sweep TARGET",
help: "Send all ether from accounts[0] to TARGET"
};
};
SweepPlugin.prototype.prepareOptions = function (argParser) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareOptions.call(this, argParser)];
case 1:
_a.sent();
if (this.accounts.length !== 1) {
this.throwUsageError("sweep requires exacly one account");
}
return [2 /*return*/];
}
});
});
};
SweepPlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_b.sent();
if (args.length !== 1) {
this.throwUsageError("sweep requires exactly ADDRESS");
}
_a = this;
return [4 /*yield*/, this.getAddress(args[0])];
case 2:
_a.toAddress = _b.sent();
;
return [2 /*return*/];
}
});
});
};
SweepPlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
var _a, balance, gasPrice, code, maxSpendable;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, ethers_1.ethers.utils.resolveProperties({
balance: this.provider.getBalance(this.accounts[0].getAddress()),
gasPrice: (this.gasPrice || this.provider.getGasPrice()),
code: this.provider.getCode(this.toAddress)
})];
case 1:
_a = _b.sent(), balance = _a.balance, gasPrice = _a.gasPrice, code = _a.code;
if (code !== "0x") {
this.throwError("Cannot sweep to a contract address");
}
maxSpendable = balance.sub(gasPrice.mul(21000));
if (maxSpendable.lte(0)) {
this.throwError("Insufficient funds to sweep");
}
return [4 /*yield*/, this.accounts[0].sendTransaction({
to: this.toAddress,
gasLimit: 21000,
gasPrice: gasPrice,
value: maxSpendable
})];
case 2:
_b.sent();
return [2 /*return*/];
}
});
});
};
return SweepPlugin;
}(cli_1.Plugin));
cli.addPlugin("sweep", SweepPlugin);
var SignMessagePlugin = /** @class */ (function (_super) {
__extends(SignMessagePlugin, _super);
function SignMessagePlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
SignMessagePlugin.getHelp = function () {
return {
name: "sign-message MESSAGE",
help: "Sign a MESSAGE with accounts[0]"
};
};
SignMessagePlugin.getOptionHelp = function () {
return [
{
name: "[ --hex ]",
help: "The message content is hex encoded"
}
];
};
SignMessagePlugin.prototype.prepareOptions = function (argParser) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareOptions.call(this, argParser)];
case 1:
_a.sent();
if (this.accounts.length !== 1) {
this.throwError("sign-message requires exacly one account");
}
this.hex = argParser.consumeFlag("hex");
return [2 /*return*/];
}
});
});
};
SignMessagePlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_a.sent();
if (args.length !== 1) {
this.throwError("send requires exactly MESSAGE");
}
this.message = args[0];
return [2 /*return*/];
}
});
});
};
SignMessagePlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.accounts[0].signMessage(this.message)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
return SignMessagePlugin;
}(cli_1.Plugin));
cli.addPlugin("sign-message", SignMessagePlugin);
var EvalPlugin = /** @class */ (function (_super) {
__extends(EvalPlugin, _super);
function EvalPlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
EvalPlugin.getHelp = function () {
return {
name: "eval CODE",
help: "Run CODE in a VM with ethers"
};
};
EvalPlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_a.sent();
if (args.length !== 1) {
this.throwError("eval requires exactly CODE");
}
this.code = args[0];
return [2 /*return*/];
}
});
});
};
EvalPlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
var contextObject, context, script, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
contextObject = {};
setupContext(contextObject, this);
context = vm_1.default.createContext(contextObject);
script = new vm_1.default.Script(this.code, { filename: "-" });
result = script.runInContext(context);
if (!(result instanceof Promise)) return [3 /*break*/, 2];
return [4 /*yield*/, result];
case 1:
result = _a.sent();
_a.label = 2;
case 2:
console.log(result);
return [2 /*return*/];
}
});
});
};
return EvalPlugin;
}(cli_1.Plugin));
cli.addPlugin("eval", EvalPlugin);
var RunPlugin = /** @class */ (function (_super) {
__extends(RunPlugin, _super);
function RunPlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
RunPlugin.getHelp = function () {
return {
name: "run FILENAME",
help: "Run FILENAME in a VM with ethers"
};
};
RunPlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_a.sent();
if (args.length !== 1) {
this.throwError("run requires exactly FILENAME");
}
this.filename = args[0];
return [2 /*return*/];
}
});
});
};
RunPlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
var contextObject, context, script, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
contextObject = {};
setupContext(contextObject, this);
context = vm_1.default.createContext(contextObject);
script = new vm_1.default.Script(fs_1.default.readFileSync(this.filename).toString(), { filename: this.filename });
result = script.runInContext(context);
if (!(result instanceof Promise)) return [3 /*break*/, 2];
return [4 /*yield*/, result];
case 1:
result = _a.sent();
_a.label = 2;
case 2:
console.log(result);
return [2 /*return*/];
}
});
});
};
return RunPlugin;
}(cli_1.Plugin));
cli.addPlugin("run", RunPlugin);
var WaitPlugin = /** @class */ (function (_super) {
__extends(WaitPlugin, _super);
function WaitPlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
WaitPlugin.getHelp = function () {
return {
name: "wait HASH",
help: "Wait for a transaction HASH to be mined"
};
};
WaitPlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_a.sent();
if (args.length !== 1) {
this.throwError("wait requires exactly HASH");
}
this.hash = args[0];
return [2 /*return*/];
}
});
});
};
WaitPlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
var receipt;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
console.log("Waiting for Transaction:", this.hash);
return [4 /*yield*/, this.provider.waitForTransaction(this.hash)];
case 1:
receipt = _a.sent();
cli_1.dump("Response:", {
"Block": receipt.blockNumber,
"Block Hash": receipt.blockHash,
"Status": (receipt.status ? "ok" : "failed")
});
return [2 /*return*/];
}
});
});
};
return WaitPlugin;
}(cli_1.Plugin));
cli.addPlugin("wait", WaitPlugin);
var CompilePlugin = /** @class */ (function (_super) {
__extends(CompilePlugin, _super);
function CompilePlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
CompilePlugin.getHelp = function () {
return {
name: "compile FILENAME",
help: "Compiles a Solidity contract"
};
};
CompilePlugin.getOptionHelp = function () {
return [
{
name: "[ --no-optimize ]",
help: "Do not optimize the compiled output"
},
{
name: "[ --warnings ]",
help: "Error on any warning"
}
];
};
CompilePlugin.prototype.prepareOptions = function (argParser) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareOptions.call(this, argParser)];
case 1:
_a.sent();
this.noOptimize = argParser.consumeFlag("no-optimize");
this.warnings = argParser.consumeFlag("warnings");
return [2 /*return*/];
}
});
});
};
CompilePlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_a.sent();
if (args.length !== 1) {
this.throwError("compile requires exactly FILENAME");
}
this.filename = args[0];
return [2 /*return*/];
}
});
});
};
CompilePlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
var source, result, output;
return __generator(this, function (_a) {
source = fs_1.default.readFileSync(this.filename).toString();
result = solc_1.compile(source, {
filename: this.filename,
optimize: (!this.noOptimize)
});
output = {};
result.forEach(function (contract, index) {
output[contract.name] = {
bytecode: contract.bytecode,
runtime: contract.runtime,
interface: contract.interface.fragments.map(function (f) { return f.format(true); })
};
});
console.log(JSON.stringify(output, null, 4));
return [2 /*return*/];
});
});
};
return CompilePlugin;
}(cli_1.Plugin));
cli.addPlugin("compile", CompilePlugin);
var DeployPlugin = /** @class */ (function (_super) {
__extends(DeployPlugin, _super);
function DeployPlugin() {
return _super !== null && _super.apply(this, arguments) || this;
}
DeployPlugin.getHelp = function () {
return {
name: "deploy FILENAME",
help: "Compile and deploy a Solidity contract"
};
};
DeployPlugin.getOptionHelp = function () {
return [
{
name: "[ --no-optimize ]",
help: "Do not optimize the compiled output"
},
{
name: "[ --contract NAME ]",
help: "Specify the contract to deploy"
}
];
};
DeployPlugin.prototype.prepareOptions = function (argParser) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareOptions.call(this, argParser)];
case 1:
_a.sent();
if (this.accounts.length !== 1) {
this.throwError("deploy requires exactly one account");
}
this.noOptimize = argParser.consumeFlag("no-optimize");
this.contractName = argParser.consumeOption("contract");
return [2 /*return*/];
}
});
});
};
DeployPlugin.prototype.prepareArgs = function (args) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.prepareArgs.call(this, args)];
case 1:
_a.sent();
if (args.length !== 1) {
this.throwError("deploy requires exactly FILENAME");
}
this.filename = args[0];
return [2 /*return*/];
}
});
});
};
DeployPlugin.prototype.run = function () {
return __awaiter(this, void 0, void 0, function () {
var source, result, codes, factory, contract;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
source = fs_1.default.readFileSync(this.filename).toString();
result = solc_1.compile(source, {
filename: this.filename,
optimize: (!this.noOptimize)
});
codes = result.filter(function (c) { return (c.bytecode !== "0x" && (_this.contractName == null || _this.contractName == c.name)); });
if (codes.length > 1) {
this.throwError("Please specify a contract with --contract NAME");
}
if (codes.length === 0) {
this.throwError("No contract found");
}
factory = new ethers_1.ethers.ContractFactory(codes[0].interface, codes[0].bytecode, this.accounts[0]);
return [4 /*yield*/, factory.deploy()];
case 1:
contract = _a.sent();
cli_1.dump("Deployed:", {
Contract: codes[0].name,
Address: contract.address,
Bytecode: codes[0].bytecode,
Interface: codes[0].interface.fragments.map(function (f) { return f.format(true); })
});
return [2 /*return*/];
}
});
});
};
return DeployPlugin;
}(cli_1.Plugin));
cli.addPlugin("deploy", DeployPlugin);
cli.run(process.argv.slice(2));

68
packages/cli/cli.d.ts vendored Normal file
View File

@ -0,0 +1,68 @@
import { ethers } from "ethers";
export declare function dump(header: string, info: any): void;
declare class WrappedSigner extends ethers.Signer {
readonly addressPromise: Promise<string>;
readonly provider: ethers.providers.Provider;
readonly plugin: Plugin;
constructor(addressPromise: Promise<string>, signerFunc: () => Promise<ethers.Signer>, plugin: Plugin);
connect(provider?: ethers.providers.Provider): ethers.Signer;
getAddress(): Promise<string>;
signMessage(message: string | ethers.utils.Bytes): Promise<string>;
signTransaction(transactionRequest: ethers.providers.TransactionRequest): Promise<string>;
sendTransaction(transactionRequest: ethers.providers.TransactionRequest): Promise<ethers.providers.TransactionResponse>;
unlock(): Promise<void>;
}
export declare class ArgParser {
readonly _args: Array<string>;
readonly _consumed: Array<boolean>;
constructor(args: Array<string>);
_finalizeArgs(): Array<string>;
_checkCommandIndex(): number;
consumeFlag(name: string): boolean;
consumeMultiOptions(names: Array<string>): Array<{
name: string;
value: string;
}>;
consumeOptions(name: string): Array<string>;
consumeOption(name: string): string;
}
export interface Help {
name: string;
help: string;
}
export interface PluginType {
new (...args: any[]): Plugin;
getHelp?: () => Help;
getOptionHelp?: () => Array<Help>;
}
export declare class Plugin {
network: ethers.providers.Network;
provider: ethers.providers.Provider;
accounts: Array<WrappedSigner>;
gasLimit: ethers.BigNumber;
gasPrice: ethers.BigNumber;
nonce: number;
data: string;
value: ethers.BigNumber;
yes: boolean;
constructor();
static getHelp(): Help;
static getOptionHelp(): Array<Help>;
prepareOptions(argParser: ArgParser): Promise<void>;
prepareArgs(args: Array<string>): Promise<void>;
run(): Promise<void>;
getAddress(addressOrName: string, message?: string, allowZero?: boolean): Promise<string>;
throwUsageError(message?: string): never;
throwError(message: string): never;
}
export declare class CLI {
readonly defaultCommand: string;
readonly plugins: {
[command: string]: PluginType;
};
constructor(defaultCommand: string);
addPlugin(command: string, plugin: PluginType): void;
showUsage(message?: string, status?: number): never;
run(args: Array<string>): Promise<void>;
}
export {};

849
packages/cli/cli.js Normal file
View File

@ -0,0 +1,849 @@
"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 __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = __importDefault(require("fs"));
var ethers_1 = require("ethers");
var prompt_1 = require("./prompt");
var UsageError = /** @class */ (function (_super) {
__extends(UsageError, _super);
function UsageError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return UsageError;
}(Error));
/////////////////////////////
// Signer
var signerFuncs = new WeakMap();
var signers = new WeakMap();
var alwaysAllow = new WeakMap();
// Gets a signer or lazily request it if needed, possibly asking for a password
// to decrypt a JSON wallet
function getSigner(wrapper) {
return __awaiter(this, void 0, void 0, function () {
var signerFunc, signer;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!!signers.has(wrapper)) return [3 /*break*/, 2];
signerFunc = signerFuncs.get(wrapper);
return [4 /*yield*/, signerFunc()];
case 1:
signer = _a.sent();
signers.set(wrapper, signer);
_a.label = 2;
case 2: return [2 /*return*/, signers.get(wrapper)];
}
});
});
}
// Throws an error if the user does not allow the operation. If "y" is
// selected, all future operations of that type are automatically accepted
function isAllowed(wrapper, message) {
return __awaiter(this, void 0, void 0, function () {
var allowed, allow, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (wrapper.plugin.yes) {
console.log(message + " (--yes => \"y\")");
return [2 /*return*/, true];
}
allowed = alwaysAllow.get(wrapper) || {};
if (allowed[message]) {
console.log(message + " (previous (a)ll => \"y\")");
return [2 /*return*/, true];
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, prompt_1.getChoice(message, "yna", "n")];
case 2:
allow = _a.sent();
if (allow === "a") {
allowed[message] = true;
alwaysAllow.set(wrapper, allowed);
}
else if (allow === "n") {
throw new Error("Cancelled.");
}
return [3 /*break*/, 4];
case 3:
error_1 = _a.sent();
throw new Error("Cancelled.");
case 4: return [2 /*return*/, true];
}
});
});
}
function repeat(chr, length) {
var result = chr;
while (result.length < length) {
result += result;
}
return result.substring(0, length);
}
// @TODO: Make dump recurable for objects
// Dumps key/value pairs in a nice format
function dump(header, info) {
console.log(header);
var maxLength = Object.keys(info).reduce(function (maxLength, i) { return Math.max(maxLength, i.length); }, 0);
for (var key in info) {
var value = info[key];
if (Array.isArray(value)) {
console.log(" " + key + ":");
value.forEach(function (value) {
console.log(" " + value);
});
}
else {
console.log(" " + key + ":" + repeat(" ", maxLength - key.length) + " " + info[key]);
}
}
}
exports.dump = dump;
// This wraps our signers to prevent the private keys and mnemonics from being exposed.
// It is also in charge of user-interaction, requesting permission before signing or
// sending.
var WrappedSigner = /** @class */ (function (_super) {
__extends(WrappedSigner, _super);
function WrappedSigner(addressPromise, signerFunc, plugin) {
var _this = _super.call(this) || this;
signerFuncs.set(_this, signerFunc);
ethers_1.ethers.utils.defineReadOnly(_this, "addressPromise", addressPromise);
ethers_1.ethers.utils.defineReadOnly(_this, "provider", plugin.provider);
ethers_1.ethers.utils.defineReadOnly(_this, "plugin", plugin);
return _this;
}
WrappedSigner.prototype.connect = function (provider) {
throw new Error("unsupported for now...");
//return new WrappedSigner(this.addressPromise, () => getSigner(this).then((s) => s.connect(provider)), provider);
};
WrappedSigner.prototype.getAddress = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.addressPromise];
});
});
};
WrappedSigner.prototype.signMessage = function (message) {
return __awaiter(this, void 0, void 0, function () {
var signer, info, bytes, i, c, result, signature;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, getSigner(this)];
case 1:
signer = _a.sent();
info = {};
if (typeof (message) === "string") {
info["Message"] = JSON.stringify(message);
info["Message (hex)"] = ethers_1.ethers.utils.hexlify(ethers_1.ethers.utils.toUtf8Bytes(message));
}
else {
bytes = ethers_1.ethers.utils.arrayify(message);
for (i = 0; i < bytes.length; i++) {
c = bytes[i];
if (c < 32 || c > 126) {
bytes = null;
break;
}
}
if (bytes) {
info["Message"] = ethers_1.ethers.utils.toUtf8String(bytes);
}
info["Message (hex)"] = ethers_1.ethers.utils.hexlify(message);
}
dump("Message:", info);
return [4 /*yield*/, isAllowed(this, "Sign Message?")];
case 2:
_a.sent();
return [4 /*yield*/, signer.signMessage(message)];
case 3:
result = _a.sent();
signature = ethers_1.ethers.utils.splitSignature(result);
dump("Signature", {
Flat: result,
r: signature.r,
s: signature.s,
vs: signature._vs,
v: signature.v,
recid: signature.recoveryParam,
});
return [2 /*return*/, result];
}
});
});
};
WrappedSigner.prototype.signTransaction = function (transactionRequest) {
return __awaiter(this, void 0, void 0, function () {
var signer, network, tx, info, result, signature;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, getSigner(this)];
case 1:
signer = _a.sent();
return [4 /*yield*/, this.provider.getNetwork()];
case 2:
network = _a.sent();
return [4 /*yield*/, ethers_1.ethers.utils.resolveProperties(transactionRequest)];
case 3:
tx = _a.sent();
info = {};
if (tx.to != null) {
info["To"] = tx.to;
}
if (tx.from != null) {
info["From"] = tx.from;
}
info["Value"] = (ethers_1.ethers.utils.formatEther(tx.value || 0) + " ether");
if (tx.nonce != null) {
info["None"] = tx.nonce;
}
info["Gas Limit"] = ethers_1.ethers.BigNumber.from(tx.gasLimit || 0).toString();
info["Gas Price"] = (ethers_1.ethers.utils.formatUnits(tx.gasPrice || 0, "gwei") + " gwei"),
info["Chain ID"] = (tx.chainId || 0);
info["Data"] = ethers_1.ethers.utils.hexlify(tx.data || "0x");
info["Network"] = network.name;
dump("Transaction:", info);
return [4 /*yield*/, isAllowed(this, "Sign Transaction?")];
case 4:
_a.sent();
return [4 /*yield*/, signer.signTransaction(transactionRequest)];
case 5:
result = _a.sent();
signature = ethers_1.ethers.utils.splitSignature(result);
dump("Signature:", {
Signature: result,
r: signature.r,
s: signature.s,
vs: signature._vs,
v: signature.v,
recid: signature.recoveryParam,
});
return [2 /*return*/, result];
}
});
});
};
WrappedSigner.prototype.sendTransaction = function (transactionRequest) {
return __awaiter(this, void 0, void 0, function () {
var signer, network, tx, info, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, getSigner(this)];
case 1:
signer = _a.sent();
return [4 /*yield*/, this.provider.getNetwork()];
case 2:
network = _a.sent();
return [4 /*yield*/, signer.populateTransaction(transactionRequest)];
case 3:
tx = _a.sent();
return [4 /*yield*/, ethers_1.ethers.utils.resolveProperties(tx)];
case 4:
tx = _a.sent();
info = {};
if (tx.to != null) {
info["To"] = tx.to;
}
if (tx.from != null) {
info["From"] = tx.from;
}
info["Value"] = (ethers_1.ethers.utils.formatEther(tx.value || 0) + " ether");
if (tx.nonce != null) {
info["None"] = tx.nonce;
}
info["Gas Limit"] = ethers_1.ethers.BigNumber.from(tx.gasLimit || 0).toString();
info["Gas Price"] = (ethers_1.ethers.utils.formatUnits(tx.gasPrice || 0, "gwei") + " gwei"),
info["Chain ID"] = (tx.chainId || 0);
info["Data"] = ethers_1.ethers.utils.hexlify(tx.data || "0x");
info["Network"] = network.name;
dump("Transaction:", info);
return [4 /*yield*/, isAllowed(this, "Send Transaction?")];
case 5:
_a.sent();
return [4 /*yield*/, signer.sendTransaction(tx)];
case 6:
response = _a.sent();
dump("Response:", {
"Hash": response.hash
});
return [2 /*return*/, response];
}
});
});
};
WrappedSigner.prototype.unlock = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, getSigner(this)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
return WrappedSigner;
}(ethers_1.ethers.Signer));
/////////////////////////////
// Argument Parser
var ArgParser = /** @class */ (function () {
function ArgParser(args) {
ethers_1.ethers.utils.defineReadOnly(this, "_args", args);
ethers_1.ethers.utils.defineReadOnly(this, "_consumed", args.map(function (a) { return false; }));
}
ArgParser.prototype._finalizeArgs = function () {
var args = [];
for (var i = 0; i < this._args.length; i++) {
if (this._consumed[i]) {
continue;
}
var arg = this._args[i];
// Escaped args, add the rest as args
if (arg === "--") {
for (var j = i + 1; j < this._args.length; j++) {
args.push(this._args[j]);
}
break;
}
if (arg.substring(0, 2) === "--") {
throw new UsageError("unexpected option " + arg);
}
args.push(arg);
}
return args;
};
ArgParser.prototype._checkCommandIndex = function () {
for (var i = 0; i < this._args.length; i++) {
if (this._consumed[i]) {
continue;
}
return i;
}
return -1;
};
ArgParser.prototype.consumeFlag = function (name) {
var count = 0;
for (var i = 0; i < this._args.length; i++) {
var arg = this._args[i];
if (arg === "--") {
break;
}
if (arg === ("--" + name)) {
count++;
this._consumed[i] = true;
}
}
if (count > 1) {
throw new UsageError("expected at most one --${name}");
}
return (count === 1);
};
ArgParser.prototype.consumeMultiOptions = function (names) {
var result = [];
if (typeof (names) === "string") {
names = [names];
}
for (var i = 0; i < this._args.length; i++) {
var arg = this._args[i];
if (arg === "--") {
break;
}
if (arg.substring(0, 2) === "--") {
var name_1 = arg.substring(2);
var index = names.indexOf(name_1);
if (index < 0) {
continue;
}
if (this._args.length === i) {
throw new UsageError("missing argument for --${name}");
}
this._consumed[i] = true;
result.push({ name: name_1, value: this._args[++i] });
this._consumed[i] = true;
}
}
return result;
};
ArgParser.prototype.consumeOptions = function (name) {
return this.consumeMultiOptions([name]).map(function (o) { return o.value; });
};
ArgParser.prototype.consumeOption = function (name) {
var options = this.consumeOptions(name);
if (options.length > 1) {
throw new UsageError("expected at most one --" + name);
}
return (options.length ? options[0] : null);
};
return ArgParser;
}());
exports.ArgParser = ArgParser;
// Accepts:
// - "-" which indicates to read from the terminal using prompt (which can then be any of the below)
// - JSON Wallet filename (which will require a password to unlock)
// - raw private key
// - mnemonic
function loadAccount(arg, plugin) {
return __awaiter(this, void 0, void 0, function () {
var content, signer_1, signer_2, content_1, address;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(arg === "-")) return [3 /*break*/, 2];
return [4 /*yield*/, prompt_1.getPassword("Private Key / Mnemonic:")];
case 1:
content = _a.sent();
return [2 /*return*/, loadAccount(content, plugin)];
case 2:
// Raw private key
if (ethers_1.ethers.utils.isHexString(arg, 32)) {
signer_1 = new ethers_1.ethers.Wallet(arg, plugin.provider);
return [2 /*return*/, Promise.resolve(new WrappedSigner(signer_1.getAddress(), function () { return Promise.resolve(signer_1); }, plugin))];
}
// Mnemonic
if (ethers_1.ethers.utils.isValidMnemonic(arg)) {
signer_2 = ethers_1.ethers.Wallet.fromMnemonic(arg).connect(plugin.provider);
return [2 /*return*/, Promise.resolve(new WrappedSigner(signer_2.getAddress(), function () { return Promise.resolve(signer_2); }, plugin))];
}
// Check for a JSON wallet
try {
content_1 = fs_1.default.readFileSync(arg).toString();
address = ethers_1.ethers.utils.getJsonWalletAddress(content_1);
if (address) {
return [2 /*return*/, Promise.resolve(new WrappedSigner(Promise.resolve(address), function () { return __awaiter(_this, void 0, void 0, function () {
var password, progressBar;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, prompt_1.getPassword("Password (" + arg + "): ")];
case 1:
password = _a.sent();
progressBar = prompt_1.getProgressBar("Decrypting");
return [2 /*return*/, ethers_1.ethers.Wallet.fromEncryptedJson(content_1, password, progressBar).then(function (wallet) {
return wallet.connect(plugin.provider);
})];
}
});
}); }, plugin))];
}
}
catch (error) {
if (error.message === "cancelled") {
throw new Error("Cancelled.");
}
else if (error.message === "wrong password") {
throw new Error("Incorrect password.");
}
}
throw new UsageError("unknown account option - [REDACTED]");
}
});
});
}
var Plugin = /** @class */ (function () {
function Plugin() {
}
Plugin.getHelp = function () {
return null;
};
Plugin.getOptionHelp = function () {
return [];
};
Plugin.prototype.prepareOptions = function (argParser) {
return __awaiter(this, void 0, void 0, function () {
var runners, network, providers, rpc, accounts, accountOptions, _loop_1, this_1, i, gasPrice, gasLimit, nonce, value, data, error_2;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
runners = [];
this.yes = argParser.consumeFlag("yes");
network = (argParser.consumeOption("network") || "homestead");
providers = [];
rpc = [];
argParser.consumeOptions("rpc").forEach(function (url) {
var provider = new ethers_1.ethers.providers.JsonRpcProvider(url);
providers.push(provider);
rpc.push(provider);
});
if (argParser.consumeFlag("alchemy")) {
providers.push(new ethers_1.ethers.providers.AlchemyProvider(network));
}
if (argParser.consumeFlag("etherscan")) {
providers.push(new ethers_1.ethers.providers.EtherscanProvider(network));
}
if (argParser.consumeFlag("infura")) {
providers.push(new ethers_1.ethers.providers.InfuraProvider(network));
}
if (argParser.consumeFlag("nodesmith")) {
providers.push(new ethers_1.ethers.providers.NodesmithProvider(network));
}
if (providers.length === 1) {
this.provider = providers[0];
}
else if (providers.length) {
this.provider = new ethers_1.ethers.providers.FallbackProvider(providers);
}
else {
this.provider = ethers_1.ethers.getDefaultProvider(network);
}
accounts = [];
accountOptions = argParser.consumeMultiOptions(["account", "account-rpc", "account-void"]);
_loop_1 = function (i) {
var account, _a, wrappedSigner, signer_3, addressPromise, signerPromise_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
account = accountOptions[i];
_a = account.name;
switch (_a) {
case "account": return [3 /*break*/, 1];
case "account-rpc": return [3 /*break*/, 3];
case "account-void": return [3 /*break*/, 4];
}
return [3 /*break*/, 5];
case 1: return [4 /*yield*/, loadAccount(account.value, this_1)];
case 2:
wrappedSigner = _b.sent();
accounts.push(wrappedSigner);
return [3 /*break*/, 5];
case 3:
if (rpc.length !== 1) {
this_1.throwUsageError("--account-rpc requires exactly one JSON-RPC provider");
}
try {
signer_3 = null;
if (account.value.match(/^[0-9]+$/)) {
signer_3 = rpc[0].getSigner(parseInt(account.value));
}
else {
signer_3 = rpc[0].getSigner(ethers_1.ethers.utils.getAddress(account.value));
}
accounts.push(new WrappedSigner(signer_3.getAddress(), function () { return Promise.resolve(signer_3); }, this_1));
}
catch (error) {
this_1.throwUsageError("invalid --account-rpc - " + account.value);
}
return [3 /*break*/, 5];
case 4:
{
addressPromise = this_1.provider.resolveName(account.value);
signerPromise_1 = addressPromise.then(function (addr) {
return new ethers_1.ethers.VoidSigner(addr, _this.provider);
});
accounts.push(new WrappedSigner(addressPromise, function () { return signerPromise_1; }, this_1));
return [3 /*break*/, 5];
}
_b.label = 5;
case 5: return [2 /*return*/];
}
});
};
this_1 = this;
i = 0;
_a.label = 1;
case 1:
if (!(i < accountOptions.length)) return [3 /*break*/, 4];
return [5 /*yield**/, _loop_1(i)];
case 2:
_a.sent();
_a.label = 3;
case 3:
i++;
return [3 /*break*/, 1];
case 4:
this.accounts = accounts;
gasPrice = argParser.consumeOption("gas-price");
if (gasPrice) {
this.gasPrice = ethers_1.ethers.utils.parseUnits(gasPrice, "gwei");
}
gasLimit = argParser.consumeOption("gas-limit");
if (gasLimit) {
this.gasLimit = ethers_1.ethers.BigNumber.from(gasLimit);
}
nonce = argParser.consumeOption("nonce");
if (nonce) {
this.nonce = ethers_1.ethers.BigNumber.from(nonce).toNumber();
}
value = argParser.consumeOption("value");
if (value) {
this.value = ethers_1.ethers.utils.parseEther(value);
}
data = argParser.consumeOption("data");
if (data) {
this.data = ethers_1.ethers.utils.hexlify(data);
}
// Now wait for all asynchronous options to load
runners.push(this.provider.getNetwork().then(function (network) {
_this.network = network;
}, function (error) {
_this.network = {
chainId: 0,
name: "no-network"
};
}));
_a.label = 5;
case 5:
_a.trys.push([5, 7, , 8]);
return [4 /*yield*/, Promise.all(runners)];
case 6:
_a.sent();
return [3 /*break*/, 8];
case 7:
error_2 = _a.sent();
this.throwError(error_2);
return [3 /*break*/, 8];
case 8: return [2 /*return*/];
}
});
});
};
Plugin.prototype.prepareArgs = function (args) {
return Promise.resolve(null);
};
Plugin.prototype.run = function () {
return null;
};
Plugin.prototype.getAddress = function (addressOrName, message, allowZero) {
var _this = this;
try {
return Promise.resolve(ethers_1.ethers.utils.getAddress(addressOrName));
}
catch (error) { }
return this.provider.resolveName(addressOrName).then(function (address) {
if (address == null) {
_this.throwError("ENS name not configured - " + addressOrName);
}
if (address === ethers_1.ethers.constants.AddressZero && !allowZero) {
_this.throwError(message);
}
return address;
});
};
Plugin.prototype.throwUsageError = function (message) {
throw new UsageError(message);
};
Plugin.prototype.throwError = function (message) {
throw new Error(message);
};
return Plugin;
}());
exports.Plugin = Plugin;
/////////////////////////////
// Command Line Runner
var CLI = /** @class */ (function () {
function CLI(defaultCommand) {
ethers_1.ethers.utils.defineReadOnly(this, "defaultCommand", defaultCommand || null);
ethers_1.ethers.utils.defineReadOnly(this, "plugins", {});
}
CLI.prototype.addPlugin = function (command, plugin) {
this.plugins[command] = plugin;
};
CLI.prototype.showUsage = function (message, status) {
// Limit: | |
console.log("Usage:");
var lines = [];
for (var cmd in this.plugins) {
var plugin = this.plugins[cmd];
var help = (plugin.getHelp ? plugin.getHelp() : null);
if (help == null) {
continue;
}
var helpLine = " " + help.name;
if (helpLine.length > 28) {
lines.push(helpLine);
lines.push(repeat(" ", 30) + help.help);
}
else {
helpLine += repeat(" ", 30 - helpLine.length);
lines.push(helpLine + help.help);
}
var optionHelp = (plugin.getOptionHelp ? plugin.getOptionHelp() : []);
optionHelp.forEach(function (help) {
lines.push(" " + help.name + repeat(" ", 27 - help.name.length) + help.help);
});
}
if (lines.length) {
if (this.defaultCommand) {
console.log(" ethers [ COMMAND ] [ ARGS ] [ OPTIONS ]");
console.log("");
console.log("COMMANDS (default: " + this.defaultCommand + ")");
}
else {
console.log(" ethers COMMAND [ ARGS ] [ OPTIONS ]");
console.log("");
console.log("COMMANDS");
}
lines.forEach(function (line) {
console.log(line);
});
console.log("");
}
console.log("ACCOUNT OPTIONS");
console.log(" --account FILENAME Load a JSON Wallet (crowdsale or keystore)");
console.log(" --account RAW_KEY Use a private key (insecure *)");
console.log(" --account 'MNEMONIC' Use a mnemonic (insecure *)");
console.log(" --account - Use secure entry for a raw key or mnemonic");
console.log(" --account-void ADDRESS Udd an address as a void signer");
console.log(" --account-void ENS_NAME Add the resolved address as a void signer");
console.log(" --account-rpc ADDRESS Add the address from a JSON-RPC provider");
console.log(" --account-rpc INDEX Add the index from a JSON-RPC provider");
console.log("");
console.log("PROVIDER OPTIONS (default: getDefaultProvider)");
console.log(" --alchemy Include Alchemy");
console.log(" --etherscan Include Etherscan");
console.log(" --infura Include INFURA");
console.log(" --nodesmith Include nodesmith");
console.log(" --rpc URL Include a custom JSON-RPC");
console.log(" --network NETWORK Network to connect to (default: homestead)");
console.log("");
console.log("TRANSACTION OPTIONS (default: query the network)");
console.log(" --gasPrice GWEI Default gas price for transactions(in wei)");
console.log(" --gasLimit GAS Default gas limit for transactions");
console.log(" --nonce NONCE Initial nonce for the first transaction");
console.log(" --value VALUE Default value (in ether) for transactions");
console.log(" --yes Always accept Siging and Sending");
console.log("");
console.log("OTHER OPTIONS");
console.log(" --help Show this usage and quit");
console.log("");
console.log("(*) By including mnemonics or private keys on the command line they are");
console.log(" possibly readable by other users on your system and may get stored in");
console.log(" your bash history file.");
console.log("");
if (message) {
console.log(message);
console.log("");
}
process.exit(status || 0);
throw new Error("never reached");
};
CLI.prototype.run = function (args) {
return __awaiter(this, void 0, void 0, function () {
var command, argParser_1, commandIndex, argParser, debug, plugin, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
args = args.slice();
command = null;
// We run a temporary argument parser to check for a command by processing standard options
{
argParser_1 = new ArgParser(args);
["debug", "help", "yes"].forEach(function (key) {
argParser_1.consumeFlag(key);
});
["alchemy", "etherscan", "infura", "nodesmith"].forEach(function (flag) {
argParser_1.consumeFlag(flag);
});
["network", "rpc", "account", "account-rpc", "account-void", "gas-price", "gas-limit", "nonce", "data"].forEach(function (option) {
argParser_1.consumeOption(option);
});
commandIndex = argParser_1._checkCommandIndex();
if (commandIndex === -1) {
command = this.defaultCommand;
}
else {
command = args[commandIndex];
args.splice(commandIndex, 1);
}
}
argParser = new ArgParser(args);
if (argParser.consumeFlag("help")) {
return [2 /*return*/, this.showUsage()];
}
debug = argParser.consumeFlag("debug");
plugin = null;
try {
plugin = new this.plugins[command]();
}
catch (error) {
if (command) {
this.showUsage("unknown command - " + command);
}
return [2 /*return*/, this.showUsage("no command provided", 1)];
}
_a.label = 1;
case 1:
_a.trys.push([1, 5, , 6]);
return [4 /*yield*/, plugin.prepareOptions(argParser)];
case 2:
_a.sent();
return [4 /*yield*/, plugin.prepareArgs(argParser._finalizeArgs())];
case 3:
_a.sent();
return [4 /*yield*/, plugin.run()];
case 4:
_a.sent();
return [3 /*break*/, 6];
case 5:
error_3 = _a.sent();
if (debug) {
console.log("----- <DEBUG> ------");
console.log(error_3);
console.log("----- </DEBUG> -----");
}
if (error_3 instanceof UsageError) {
return [2 /*return*/, this.showUsage(error_3.message, 1)];
}
console.log("Error: " + error_3.message);
process.exit(2);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
});
};
return CLI;
}());
exports.CLI = CLI;

552
packages/cli/package-lock.json generated Normal file
View File

@ -0,0 +1,552 @@
{
"name": "@ethersproject/cli",
"version": "5.0.0-beta.129",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"solc": {
"version": "0.5.8",
"resolved": "https://registry.npmjs.org/solc/-/solc-0.5.8.tgz",
"integrity": "sha512-RQ2SlwPBOBSV7ktNQJkvbiQks3t+3V9dsqD014EdstxnJzSxBuOvbt3P5QXpNPYW1DsEmF7dhOaT3JL7yEae/A==",
"requires": {
"command-exists": "^1.2.8",
"fs-extra": "^0.30.0",
"keccak": "^1.0.2",
"memorystream": "^0.3.1",
"require-from-string": "^2.0.0",
"semver": "^5.5.0",
"tmp": "0.0.33",
"yargs": "^11.0.0"
},
"dependencies": {
"ansi-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg="
},
"balanced-match": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
"integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c="
},
"bindings": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
"integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
"requires": {
"file-uri-to-path": "1.0.0"
}
},
"brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"requires": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"camelcase": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz",
"integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0="
},
"cliui": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-4.1.0.tgz",
"integrity": "sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ==",
"requires": {
"string-width": "^2.1.1",
"strip-ansi": "^4.0.0",
"wrap-ansi": "^2.0.0"
}
},
"code-point-at": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz",
"integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c="
},
"command-exists": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/command-exists/-/command-exists-1.2.8.tgz",
"integrity": "sha512-PM54PkseWbiiD/mMsbvW351/u+dafwTJ0ye2qB60G1aGQP9j3xK2gmMDc+R34L3nDtx4qMCitXT75mkbkGJDLw=="
},
"concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s="
},
"cross-spawn": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz",
"integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=",
"requires": {
"lru-cache": "^4.0.1",
"shebang-command": "^1.2.0",
"which": "^1.2.9"
}
},
"decamelize": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
"integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA="
},
"execa": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/execa/-/execa-0.7.0.tgz",
"integrity": "sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c=",
"requires": {
"cross-spawn": "^5.0.1",
"get-stream": "^3.0.0",
"is-stream": "^1.1.0",
"npm-run-path": "^2.0.0",
"p-finally": "^1.0.0",
"signal-exit": "^3.0.0",
"strip-eof": "^1.0.0"
}
},
"file-uri-to-path": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
"integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="
},
"find-up": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz",
"integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=",
"requires": {
"locate-path": "^2.0.0"
}
},
"fs-extra": {
"version": "0.30.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-0.30.0.tgz",
"integrity": "sha1-8jP/zAjU2n1DLapEl3aYnbHfk/A=",
"requires": {
"graceful-fs": "^4.1.2",
"jsonfile": "^2.1.0",
"klaw": "^1.0.0",
"path-is-absolute": "^1.0.0",
"rimraf": "^2.2.8"
}
},
"fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8="
},
"get-caller-file": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz",
"integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w=="
},
"get-stream": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz",
"integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ="
},
"glob": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz",
"integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==",
"requires": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.0.4",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
}
},
"graceful-fs": {
"version": "4.1.15",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz",
"integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA=="
},
"inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
"requires": {
"once": "^1.3.0",
"wrappy": "1"
}
},
"inherits": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
},
"invert-kv": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz",
"integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY="
},
"is-fullwidth-code-point": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz",
"integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8="
},
"is-stream": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz",
"integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ="
},
"isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA="
},
"jsonfile": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-2.4.0.tgz",
"integrity": "sha1-NzaitCi4e72gzIO1P6PWM6NcKug=",
"requires": {
"graceful-fs": "^4.1.6"
}
},
"keccak": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/keccak/-/keccak-1.4.0.tgz",
"integrity": "sha512-eZVaCpblK5formjPjeTBik7TAg+pqnDrMHIffSvi9Lh7PQgM1+hSzakUeZFCk9DVVG0dacZJuaz2ntwlzZUIBw==",
"requires": {
"bindings": "^1.2.1",
"inherits": "^2.0.3",
"nan": "^2.2.1",
"safe-buffer": "^5.1.0"
}
},
"klaw": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/klaw/-/klaw-1.3.1.tgz",
"integrity": "sha1-QIhDO0azsbolnXh4XY6W9zugJDk=",
"requires": {
"graceful-fs": "^4.1.9"
}
},
"lcid": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz",
"integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=",
"requires": {
"invert-kv": "^1.0.0"
}
},
"locate-path": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz",
"integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=",
"requires": {
"p-locate": "^2.0.0",
"path-exists": "^3.0.0"
}
},
"lru-cache": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz",
"integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==",
"requires": {
"pseudomap": "^1.0.2",
"yallist": "^2.1.2"
}
},
"mem": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/mem/-/mem-1.1.0.tgz",
"integrity": "sha1-Xt1StIXKHZAP5kiVUFOZoN+kX3Y=",
"requires": {
"mimic-fn": "^1.0.0"
}
},
"memorystream": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz",
"integrity": "sha1-htcJCzDORV1j+64S3aUaR93K+bI="
},
"mimic-fn": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz",
"integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ=="
},
"minimatch": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
"integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
"requires": {
"brace-expansion": "^1.1.7"
}
},
"nan": {
"version": "2.13.2",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.13.2.tgz",
"integrity": "sha512-TghvYc72wlMGMVMluVo9WRJc0mB8KxxF/gZ4YYFy7V2ZQX9l7rgbPg7vjS9mt6U5HXODVFVI2bOduCzwOMv/lw=="
},
"npm-run-path": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz",
"integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=",
"requires": {
"path-key": "^2.0.0"
}
},
"number-is-nan": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz",
"integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0="
},
"once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
"requires": {
"wrappy": "1"
}
},
"os-locale": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/os-locale/-/os-locale-2.1.0.tgz",
"integrity": "sha512-3sslG3zJbEYcaC4YVAvDorjGxc7tv6KVATnLPZONiljsUncvihe9BQoVCEs0RZ1kmf4Hk9OBqlZfJZWI4GanKA==",
"requires": {
"execa": "^0.7.0",
"lcid": "^1.0.0",
"mem": "^1.1.0"
}
},
"os-tmpdir": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz",
"integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ="
},
"p-finally": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
"integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4="
},
"p-limit": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz",
"integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==",
"requires": {
"p-try": "^1.0.0"
}
},
"p-locate": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz",
"integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=",
"requires": {
"p-limit": "^1.1.0"
}
},
"p-try": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz",
"integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M="
},
"path-exists": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz",
"integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU="
},
"path-is-absolute": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18="
},
"path-key": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz",
"integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A="
},
"pseudomap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz",
"integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM="
},
"require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I="
},
"require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="
},
"require-main-filename": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz",
"integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE="
},
"rimraf": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz",
"integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==",
"requires": {
"glob": "^7.1.3"
}
},
"safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"semver": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz",
"integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA=="
},
"set-blocking": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
"integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc="
},
"shebang-command": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz",
"integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=",
"requires": {
"shebang-regex": "^1.0.0"
}
},
"shebang-regex": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz",
"integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM="
},
"signal-exit": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz",
"integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0="
},
"string-width": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
"integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==",
"requires": {
"is-fullwidth-code-point": "^2.0.0",
"strip-ansi": "^4.0.0"
}
},
"strip-ansi": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
"integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
"requires": {
"ansi-regex": "^3.0.0"
}
},
"strip-eof": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz",
"integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8="
},
"tmp": {
"version": "0.0.33",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz",
"integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==",
"requires": {
"os-tmpdir": "~1.0.2"
}
},
"which": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz",
"integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==",
"requires": {
"isexe": "^2.0.0"
}
},
"which-module": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz",
"integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho="
},
"wrap-ansi": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz",
"integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=",
"requires": {
"string-width": "^1.0.1",
"strip-ansi": "^3.0.1"
},
"dependencies": {
"ansi-regex": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz",
"integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8="
},
"is-fullwidth-code-point": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz",
"integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=",
"requires": {
"number-is-nan": "^1.0.0"
}
},
"string-width": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",
"integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=",
"requires": {
"code-point-at": "^1.0.0",
"is-fullwidth-code-point": "^1.0.0",
"strip-ansi": "^3.0.0"
}
},
"strip-ansi": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",
"integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=",
"requires": {
"ansi-regex": "^2.0.0"
}
}
}
},
"wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8="
},
"y18n": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz",
"integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE="
},
"yallist": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz",
"integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI="
},
"yargs": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-11.1.0.tgz",
"integrity": "sha512-NwW69J42EsCSanF8kyn5upxvjp5ds+t3+udGBeTbFnERA+lF541DDpMawzo4z6W/QrzNM18D+BPMiOBibnFV5A==",
"requires": {
"cliui": "^4.0.0",
"decamelize": "^1.1.1",
"find-up": "^2.1.0",
"get-caller-file": "^1.0.1",
"os-locale": "^2.0.0",
"require-directory": "^2.1.1",
"require-main-filename": "^1.0.1",
"set-blocking": "^2.0.0",
"string-width": "^2.0.0",
"which-module": "^2.0.0",
"y18n": "^3.2.1",
"yargs-parser": "^9.0.2"
}
},
"yargs-parser": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-9.0.2.tgz",
"integrity": "sha1-nM9qQ0YP5O1Aqbto9I1DuKaMwHc=",
"requires": {
"camelcase": "^4.1.0"
}
}
}
}
}
}

9
packages/cli/prompt.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
export declare type PromptOptions = {
choice?: Array<string>;
defaultChoice?: string;
mask?: string;
};
export declare function getProgressBar(action: string): (percent: number) => void;
export declare function getPassword(prompt: string): Promise<string>;
export declare function getMessage(prompt: string): Promise<string>;
export declare function getChoice(prompt: string, choices: string, defaultChoice?: string): Promise<string>;

130
packages/cli/prompt.js Normal file
View File

@ -0,0 +1,130 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function repeat(chr, count) {
var result = "";
while (result.length < count) {
result += chr;
}
return result;
}
function _getPrompt(prompt, options, callback) {
process.stdout.write(prompt);
var stdin = process.stdin;
stdin.resume();
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
var message = '';
var respond = function (ctrlC, message) {
process.stdout.write('\n');
stdin.setRawMode(false);
stdin.pause();
stdin.removeListener('data', handler);
callback(ctrlC, message);
};
function handler(chr) {
chr = String(chr);
switch (chr) {
// Enter (ish)
case "\n":
case "\r":
case "\u0004":
if (options.choice) {
if (options.defaultChoice) {
respond(null, options.defaultChoice);
}
}
else {
respond(null, message);
}
break;
// Backspace
case "\u007f":
if (message.length > 0 && options.choice == null) {
message = message.substring(0, message.length - 1);
(process.stdout).clearLine();
(process.stdout).cursorTo(0);
if (options.mask) {
process.stdout.write(prompt + repeat(options.mask, message.length));
}
else {
process.stdout.write(prompt + message);
}
}
break;
// Ctrl-C
case "\u0003":
process.stdout.write('\n[ CTRL-C ]');
respond(true, null);
break;
// Any other character
default:
if (options.choice) {
if (options.choice.indexOf(chr) >= 0) {
process.stdout.write(chr);
respond(null, chr);
}
}
else {
// More passsword characters
if (options.mask) {
process.stdout.write('*');
}
else {
process.stdout.write(chr);
}
message += chr;
}
break;
}
}
stdin.on('data', handler);
}
function getPrompt(prompt, options) {
return new Promise(function (resolve, reject) {
_getPrompt(prompt, options, function (ctrlC, password) {
if (ctrlC) {
return reject(new Error("cancelled"));
}
resolve(password);
});
});
}
function getProgressBar(action) {
var lastProgress = -1;
return function (percent) {
var progress = Math.trunc(percent * 100);
if (progress == lastProgress) {
return;
}
lastProgress = progress;
process.stdin.setRawMode(false);
process.stdin.pause();
(process.stdout).clearLine();
(process.stdout).cursorTo(0);
process.stdout.write(action + "... " + progress + "%");
if (percent === 1) {
process.stdout.write('\n');
}
};
}
exports.getProgressBar = getProgressBar;
function getPassword(prompt) {
return getPrompt(prompt, { mask: "*" });
}
exports.getPassword = getPassword;
function getMessage(prompt) {
return getPrompt(prompt, {});
}
exports.getMessage = getMessage;
// @TODO: Allow choices to be an array, [ "Yes", "No", "All" ] => "(y)es/ (N)o/ (a)ll"
function getChoice(prompt, choices, defaultChoice) {
var choice = choices.toLowerCase().split("");
if (defaultChoice) {
defaultChoice = defaultChoice.toLowerCase();
}
var options = { choice: choice, defaultChoice: defaultChoice };
var hint = choice.map(function (c) { return ((c === defaultChoice) ? c.toUpperCase() : c); }).join("/");
return getPrompt((prompt + " (" + hint + ") "), options);
}
exports.getChoice = getChoice;

14
packages/cli/solc.d.ts vendored Normal file
View File

@ -0,0 +1,14 @@
import { ethers } from "ethers";
export interface ContractCode {
interface: ethers.utils.Interface;
name: string;
bytecode?: string;
runtime?: string;
}
export declare type CompilerOptions = {
filename?: string;
basedir?: string;
optimize?: boolean;
throwWarnings?: boolean;
};
export declare function compile(source: string, options?: CompilerOptions): Array<ContractCode>;

78
packages/cli/solc.js Normal file
View File

@ -0,0 +1,78 @@
'use strict';
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = __importDefault(require("fs"));
var path_1 = require("path");
var ethers_1 = require("ethers");
var _solc = null;
function getSolc() {
if (!_solc) {
_solc = require("solc");
}
return _solc;
}
;
function compile(source, options) {
options = ethers_1.ethers.utils.shallowCopy(options || {});
if (options.filename && !options.basedir) {
options.basedir = path_1.dirname(options.filename);
}
if (!options.filename) {
options.filename = "_contract.sol";
}
if (!options.basedir) {
options.basedir = ".";
}
var sources = {};
sources[options.filename] = { content: source };
var input = {
language: "Solidity",
sources: sources,
settings: {
outputSelection: {
"*": {
"*": ["*"]
}
}
}
};
if (options.optimize) {
input.settings.optimizer = {
enabled: true,
runs: 200
};
}
var findImport = function (filename) {
try {
return {
contents: fs_1.default.readFileSync(path_1.resolve(options.basedir, options.filename)).toString()
};
}
catch (error) {
return { error: error.message };
}
};
var output = JSON.parse(getSolc().compile(JSON.stringify(input), findImport));
var errors = (output.errors || []).filter(function (x) { return (x.severity === "error" || options.throwWarnings); }).map(function (x) { return x.formattedMessage; });
if (errors.length) {
var error = new Error("compilation error");
error.errors = errors;
throw error;
}
var result = [];
for (var filename in output.contracts) {
for (var name_1 in output.contracts[filename]) {
var contract = output.contracts[filename][name_1];
result.push({
name: name_1,
interface: new ethers_1.ethers.utils.Interface(contract.abi),
bytecode: "0x" + contract.evm.bytecode.object,
runtime: "0x" + contract.evm.deployedBytecode.object
});
}
}
return result;
}
exports.compile = compile;

3
packages/cli/typescript.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
import { ContractCode } from "./solc";
export declare const header = "import { ethers } from \"ethers\";\n\n";
export declare function generate(contract: ContractCode, bytecode?: string): string;

116
packages/cli/typescript.js Normal file
View File

@ -0,0 +1,116 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function getType(param, flexible) {
if (param.type === "address" || param.type === "string") {
return "string";
}
if (param.type.substring(0, 5) === "bytes") {
if (flexible) {
return "string | ethers.utils.BytesLike";
}
return "string";
}
var match = param.type.match(/^(u?int)([0-9]+)$/);
if (match) {
if (flexible) {
return "ethers.BigNumberish";
}
if (parseInt(match[2]) < 53) {
return 'number';
}
return 'ethers.BigNumber';
}
if (param.type === "array") {
return "Array<" + getType(param.arrayChildren) + ">";
}
if (param.type === "tuple") {
var struct = param.components.map(function (p, i) { return (p.name || "p_" + i) + ": " + getType(p, flexible); });
return "{ " + struct.join(", ") + " }";
}
throw new Error("unknown type");
return null;
}
exports.header = "import { ethers } from \"ethers\";\n\n";
function generate(contract, bytecode) {
var lines = [];
lines.push("export class " + contract.name + " extends ethers.Contract {");
lines.push("");
lines.push(" constructor(addressOrName: string, providerOrSigner: ethers.Signer | ethers.providers.Provider) {");
lines.push(" super(addressOrName, new.target.ABI(), providerOrSigner)");
lines.push(" }");
lines.push("");
lines.push(" connect(providerOrSigner: ethers.Signer | ethers.providers.Provider): " + contract.name + " {");
lines.push(" return new (<{ new(...args: any[]): " + contract.name + " }>(this.constructor))(this.address, providerOrSigner)");
lines.push(" }");
lines.push("");
lines.push(" attach(addressOrName: string): " + contract.name + " {");
lines.push(" return new (<{ new(...args: any[]): " + contract.name + " }>(this.constructor))(addressOrName, this.signer || this.provider)");
lines.push(" }");
var _loop_1 = function (signature) {
if (signature.indexOf('(') === -1) {
return "continue";
}
var fragment = contract.interface.functions[signature];
console.log(fragment);
var output_1 = "Promise<ethers.providers.TransactionResponse>";
var overrides = "ethers.CallOverrides";
if (fragment.constant == false) {
if (fragment.payable) {
overrides = "ethers.PayableOverrides";
}
else {
overrides = "ethers.Overrides";
}
}
else if (fragment.outputs.length > 0) {
if (fragment.outputs.length === 1) {
output_1 = "Promise<" + getType(fragment.outputs[0]) + ">";
}
else {
throw new Error('not implemented yet');
}
}
var inputs = [];
var passed = [];
fragment.inputs.forEach(function (input, index) {
var name = (input.name || ("p_" + index));
var type = getType(input, true);
inputs.push(name + ": " + type);
passed.push(name);
});
inputs.push("_overrides?: " + overrides);
passed.push("_overrides");
lines.push("");
lines.push(" " + fragment.name + "(" + inputs.join(', ') + "): " + output_1 + " {");
lines.push(" return this.functions[\"" + signature + "\"](" + passed.join(", ") + ");");
lines.push(" }");
};
for (var signature in contract.interface.functions) {
_loop_1(signature);
}
lines.push("");
lines.push(" static factory(signer?: ethers.Signer): ethers.ContractFactory {");
lines.push(" return new ethers.ContractFactory(" + contract.name + ".ABI(), " + contract.name + ".bytecode(), signer);");
lines.push(" }");
lines.push("");
lines.push(" static bytecode(): string {");
if (bytecode == null) {
lines.push(' return ethers.errors.throwError("no bytecode provided during generation", ethers.errors.UNSUPPORTED_OPERATION, { operation: "contract.bytecode" });');
}
else {
lines.push(' return "' + bytecode + '";');
}
lines.push(" }");
lines.push("");
lines.push(" static ABI(): Array<string> {");
lines.push(" return [");
contract.interface.fragments.forEach(function (fragment) {
lines.push(" \"" + fragment.format(true) + "\",");
});
lines.push(" ];");
lines.push(" }");
lines.push("}");
var output = lines.join("\n") + "\n";
return output;
}
exports.generate = generate;

1
packages/constants/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.126";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.126";

11
packages/constants/index.d.ts vendored Normal file
View File

@ -0,0 +1,11 @@
import { BigNumber } from "@ethersproject/bignumber";
declare const AddressZero = "0x0000000000000000000000000000000000000000";
declare const HashZero = "0x0000000000000000000000000000000000000000000000000000000000000000";
declare const EtherSymbol = "\u039E";
declare const NegativeOne: BigNumber;
declare const Zero: BigNumber;
declare const One: BigNumber;
declare const Two: BigNumber;
declare const WeiPerEther: BigNumber;
declare const MaxUint256: BigNumber;
export { AddressZero, HashZero, EtherSymbol, NegativeOne, Zero, One, Two, WeiPerEther, MaxUint256 };

View File

@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bignumber_1 = require("@ethersproject/bignumber");
var AddressZero = "0x0000000000000000000000000000000000000000";
exports.AddressZero = AddressZero;
var HashZero = "0x0000000000000000000000000000000000000000000000000000000000000000";
exports.HashZero = HashZero;
// NFKD (decomposed)
//const EtherSymbol = "\uD835\uDF63";
// NFKC (composed)
var EtherSymbol = "\u039e";
exports.EtherSymbol = EtherSymbol;
var NegativeOne = bignumber_1.BigNumber.from(-1);
exports.NegativeOne = NegativeOne;
var Zero = bignumber_1.BigNumber.from(0);
exports.Zero = Zero;
var One = bignumber_1.BigNumber.from(1);
exports.One = One;
var Two = bignumber_1.BigNumber.from(2);
exports.Two = Two;
var WeiPerEther = bignumber_1.BigNumber.from("1000000000000000000");
exports.WeiPerEther = WeiPerEther;
var MaxUint256 = bignumber_1.BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
exports.MaxUint256 = MaxUint256;

1
packages/contracts/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.127";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.127";

110
packages/contracts/index.d.ts vendored Normal file
View File

@ -0,0 +1,110 @@
import { EventFragment, Fragment, Indexed, Interface, JsonFragment } from "@ethersproject/abi";
import { Block, BlockTag, Listener, Log, Provider, TransactionReceipt, TransactionRequest, TransactionResponse } from "@ethersproject/abstract-provider";
import { Signer } from "@ethersproject/abstract-signer";
import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
import { BytesLike } from "@ethersproject/bytes";
import { UnsignedTransaction } from "@ethersproject/transactions";
export interface Overrides {
gasLimit?: BigNumberish | Promise<BigNumberish>;
gasPrice?: BigNumberish | Promise<BigNumberish>;
nonce?: BigNumberish | Promise<BigNumberish>;
}
export interface PayableOverrides extends Overrides {
value?: BigNumberish | Promise<BigNumberish>;
}
export interface CallOverrides extends PayableOverrides {
blockTag?: BlockTag | Promise<BlockTag>;
from?: string | Promise<string>;
}
export declare type ContractFunction = (...params: Array<any>) => Promise<any>;
export declare type EventFilter = {
address?: string;
topics?: Array<string>;
};
export interface Event extends Log {
event?: string;
eventSignature?: string;
values?: Array<any>;
decode?: (data: string, topics?: Array<string>) => any;
removeListener: () => void;
getBlock: () => Promise<Block>;
getTransaction: () => Promise<TransactionResponse>;
getTransactionReceipt: () => Promise<TransactionReceipt>;
}
export interface ContractReceipt extends TransactionReceipt {
events?: Array<Event>;
}
export interface ContractTransaction extends TransactionResponse {
wait(confirmations?: number): Promise<ContractReceipt>;
}
interface Bucket<T> {
[name: string]: T;
}
declare type _EventFilter = {
prepareEvent: (event: Event) => void;
fragment?: EventFragment;
eventTag: string;
filter: EventFilter;
};
export declare type ContractInterface = string | Array<Fragment | JsonFragment | string> | Interface;
export declare class Contract {
readonly address: string;
readonly interface: Interface;
readonly signer: Signer;
readonly provider: Provider;
readonly functions: Bucket<ContractFunction>;
readonly callStatic: Bucket<ContractFunction>;
readonly estimate: Bucket<(...params: Array<any>) => Promise<BigNumber>>;
readonly populateTransaction: Bucket<(...params: Array<any>) => Promise<UnsignedTransaction>>;
readonly filters: Bucket<(...params: Array<any>) => EventFilter>;
readonly [name: string]: ContractFunction | any;
readonly addressPromise: Promise<string>;
readonly deployTransaction: TransactionResponse;
_deployedPromise: Promise<Contract>;
constructor(addressOrName: string, contractInterface: ContractInterface, signerOrProvider: Signer | Provider);
static getContractAddress(transaction: {
from: string;
nonce: BigNumberish;
}): string;
static getInterface(contractInterface: ContractInterface): Interface;
deployed(): Promise<Contract>;
_deployed(blockTag?: BlockTag): Promise<Contract>;
fallback(overrides?: TransactionRequest): Promise<TransactionResponse>;
connect(signerOrProvider: Signer | Provider | string): Contract;
attach(addressOrName: string): Contract;
static isIndexed(value: any): value is Indexed;
private _events;
private _getEventFilter;
_wrapEvent(eventFilter: _EventFilter, log: Log, listener: Listener): Event;
private _addEventListener;
queryFilter(event: EventFilter, fromBlockOrBlockhash?: BlockTag | string, toBlock?: BlockTag): Promise<Array<Event>>;
on(event: EventFilter | string, listener: Listener): Contract;
once(event: EventFilter | string, listener: Listener): Contract;
addListener(eventName: EventFilter | string, listener: Listener): Contract;
emit(eventName: EventFilter | string, ...args: Array<any>): boolean;
listenerCount(eventName?: EventFilter | string): number;
listeners(eventName?: EventFilter | string): Array<Listener>;
removeAllListeners(eventName: EventFilter | string): Contract;
off(eventName: any, listener: Listener): Contract;
removeListener(eventName: any, listener: Listener): Contract;
}
export declare class ContractFactory {
readonly interface: Interface;
readonly bytecode: string;
readonly signer: Signer;
constructor(contractInterface: ContractInterface, bytecode: BytesLike | {
object: string;
}, signer?: Signer);
getDeployTransaction(...args: Array<any>): UnsignedTransaction;
deploy(...args: Array<any>): Promise<Contract>;
attach(address: string): Contract;
connect(signer: Signer): ContractFactory;
static fromSolidity(compilerOutput: any, signer?: Signer): ContractFactory;
static getInterface(contractInterface: ContractInterface): Interface;
static getContractAddress(tx: {
from: string;
nonce: BytesLike | BigNumber | number;
}): string;
static getContract(address: string, contractInterface: ContractInterface, signer?: Signer): Contract;
}
export {};

686
packages/contracts/index.js Normal file
View File

@ -0,0 +1,686 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var abi_1 = require("@ethersproject/abi");
var abstract_provider_1 = require("@ethersproject/abstract-provider");
var abstract_signer_1 = require("@ethersproject/abstract-signer");
var address_1 = require("@ethersproject/address");
var bignumber_1 = require("@ethersproject/bignumber");
var bytes_1 = require("@ethersproject/bytes");
var constants_1 = require("@ethersproject/constants");
var errors = __importStar(require("@ethersproject/errors"));
var properties_1 = require("@ethersproject/properties");
///////////////////////////////
var allowedTransactionKeys = {
chainId: true, data: true, from: true, gasLimit: true, gasPrice: true, nonce: true, to: true, value: true
};
// Recursively replaces ENS names with promises to resolve the name and
// stalls until all promises have returned
// @TODO: Expand this to resolve any promises too
function resolveAddresses(signerOrProvider, value, paramType) {
if (Array.isArray(paramType)) {
return Promise.all(paramType.map(function (paramType, index) {
return resolveAddresses(signerOrProvider, ((Array.isArray(value)) ? value[index] : value[paramType.name]), paramType);
}));
}
if (paramType.type === "address") {
return signerOrProvider.resolveName(value);
}
if (paramType.type === "tuple") {
return resolveAddresses(signerOrProvider, value, paramType.components);
}
// Strips one level of array indexing off the end to recuse into
//let isArrayMatch = paramType.type.match(/(.*)(\[[0-9]*\]$)/);
if (paramType.baseType === "array") {
if (!Array.isArray(value)) {
throw new Error("invalid value for array");
}
return Promise.all(value.map(function (v) { return resolveAddresses(signerOrProvider, v, paramType.arrayChildren); }));
}
return Promise.resolve(value);
}
function runMethod(contract, functionName, options) {
var method = contract.interface.functions[functionName];
return function () {
var _this = this;
var params = [];
for (var _i = 0; _i < arguments.length; _i++) {
params[_i] = arguments[_i];
}
var tx = {};
var blockTag = null;
// If 1 extra parameter was passed in, it contains overrides
if (params.length === method.inputs.length + 1 && typeof (params[params.length - 1]) === "object") {
tx = properties_1.shallowCopy(params.pop());
if (tx.blockTag != null) {
blockTag = tx.blockTag;
}
delete tx.blockTag;
// Check for unexpected keys (e.g. using "gas" instead of "gasLimit")
for (var key in tx) {
if (!allowedTransactionKeys[key]) {
errors.throwError(("unknown transaxction override - " + key), "overrides", tx);
}
}
}
errors.checkArgumentCount(params.length, method.inputs.length, "passed to contract");
// Check overrides make sense
["data", "to"].forEach(function (key) {
if (tx[key] != null) {
errors.throwError("cannot override " + key, errors.UNSUPPORTED_OPERATION, { operation: key });
}
});
// If the contract was just deployed, wait until it is minded
if (contract.deployTransaction != null) {
tx.to = contract._deployed(blockTag).then(function () {
return contract.addressPromise;
});
}
else {
tx.to = contract.addressPromise;
}
return resolveAddresses(contract.signer || contract.provider, params, method.inputs).then(function (params) {
tx.data = contract.interface.encodeFunctionData(method, params);
if (method.constant || options.callStatic) {
// Call (constant functions) always cost 0 ether
if (options.estimate) {
return Promise.resolve(constants_1.Zero);
}
if (!contract.provider && !contract.signer) {
errors.throwError("call (constant functions) require a provider or signer", errors.UNSUPPORTED_OPERATION, { operation: "call" });
}
// Check overrides make sense
["gasLimit", "gasPrice", "value"].forEach(function (key) {
if (tx[key] != null) {
throw new Error("call cannot override " + key);
}
});
if (options.transaction) {
return properties_1.resolveProperties(tx);
}
return (contract.signer || contract.provider).call(tx, blockTag).then(function (value) {
try {
var result = contract.interface.decodeFunctionResult(method, value);
if (method.outputs.length === 1) {
result = result[0];
}
return result;
}
catch (error) {
if (error.code === errors.CALL_EXCEPTION) {
error.address = contract.address;
error.args = params;
error.transaction = tx;
}
throw error;
}
});
}
// Only computing the transaction estimate
if (options.estimate) {
if (!contract.provider && !contract.signer) {
errors.throwError("estimate require a provider or signer", errors.UNSUPPORTED_OPERATION, { operation: "estimateGas" });
}
return (contract.signer || contract.provider).estimateGas(tx);
}
if (tx.gasLimit == null && method.gas != null) {
tx.gasLimit = bignumber_1.BigNumber.from(method.gas).add(21000);
}
if (tx.value != null && !method.payable) {
errors.throwError("contract method is not payable", errors.INVALID_ARGUMENT, {
argument: "sendTransaction",
value: tx,
method: method.format()
});
}
if (!contract.signer) {
errors.throwError("sending a transaction require a signer", errors.UNSUPPORTED_OPERATION, { operation: "sendTransaction" });
}
if (options.transaction) {
return tx;
}
return contract.signer.sendTransaction(tx).then(function (tx) {
var wait = tx.wait.bind(tx);
tx.wait = function (confirmations) {
return wait(confirmations).then(function (receipt) {
receipt.events = receipt.logs.map(function (log) {
var event = properties_1.deepCopy(log);
var parsed = contract.interface.parseLog(log);
if (parsed) {
event.values = parsed.values;
event.decode = function (data, topics) {
return _this.interface.decodeEventLog(parsed.eventFragment, data, topics);
};
event.event = parsed.name;
event.eventSignature = parsed.signature;
}
event.removeListener = function () { return contract.provider; };
event.getBlock = function () {
return contract.provider.getBlock(receipt.blockHash);
};
event.getTransaction = function () {
return contract.provider.getTransaction(receipt.transactionHash);
};
event.getTransactionReceipt = function () {
return Promise.resolve(receipt);
};
return event;
});
return receipt;
});
};
return tx;
});
});
};
}
function getEventTag(filter) {
if (filter.address && (filter.topics == null || filter.topics.length === 0)) {
return "*";
}
return (filter.address || "*") + "@" + (filter.topics ? filter.topics.join(":") : "");
}
var Contract = /** @class */ (function () {
// https://github.com/Microsoft/TypeScript/issues/5453
// Once this issue is resolved (there are open PR) we can do this nicer
// by making addressOrName default to null for 2 operand calls. :)
function Contract(addressOrName, contractInterface, signerOrProvider) {
var _newTarget = this.constructor;
var _this = this;
errors.checkNew(_newTarget, Contract);
// @TODO: Maybe still check the addressOrName looks like a valid address or name?
//address = getAddress(address);
properties_1.defineReadOnly(this, "interface", _newTarget.getInterface(contractInterface));
if (properties_1.isNamedInstance(abstract_signer_1.Signer, signerOrProvider)) {
properties_1.defineReadOnly(this, "provider", signerOrProvider.provider);
properties_1.defineReadOnly(this, "signer", signerOrProvider);
}
else if (properties_1.isNamedInstance(abstract_provider_1.Provider, signerOrProvider)) {
properties_1.defineReadOnly(this, "provider", signerOrProvider);
properties_1.defineReadOnly(this, "signer", null);
}
else {
errors.throwError("invalid signer or provider", errors.INVALID_ARGUMENT, { arg: "signerOrProvider", value: signerOrProvider });
}
properties_1.defineReadOnly(this, "callStatic", {});
properties_1.defineReadOnly(this, "estimate", {});
properties_1.defineReadOnly(this, "functions", {});
properties_1.defineReadOnly(this, "populateTransaction", {});
properties_1.defineReadOnly(this, "filters", {});
Object.keys(this.interface.events).forEach(function (eventName) {
var event = _this.interface.events[eventName];
properties_1.defineReadOnly(_this.filters, eventName, function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return {
address: _this.address,
topics: _this.interface.encodeFilterTopics(event, args)
};
});
});
this._events = [];
properties_1.defineReadOnly(this, "address", addressOrName);
if (this.provider) {
properties_1.defineReadOnly(this, "addressPromise", this.provider.resolveName(addressOrName).then(function (address) {
if (address == null) {
throw new Error("name not found");
}
return address;
}).catch(function (error) {
console.log("ERROR: Cannot find Contract - " + addressOrName);
throw error;
}));
}
else {
try {
properties_1.defineReadOnly(this, "addressPromise", Promise.resolve((this.interface.constructor).getAddress(addressOrName)));
}
catch (error) {
// Without a provider, we cannot use ENS names
errors.throwError("provider is required to use non-address contract address", errors.INVALID_ARGUMENT, { argument: "addressOrName", value: addressOrName });
}
}
Object.keys(this.interface.functions).forEach(function (name) {
var run = runMethod(_this, name, {});
if (_this[name] == null) {
properties_1.defineReadOnly(_this, name, run);
}
if (_this.functions[name] == null) {
properties_1.defineReadOnly(_this.functions, name, run);
}
if (_this.callStatic[name] == null) {
properties_1.defineReadOnly(_this.callStatic, name, runMethod(_this, name, { callStatic: true }));
}
if (_this.populateTransaction[name] == null) {
properties_1.defineReadOnly(_this.populateTransaction, name, runMethod(_this, name, { transaction: true }));
}
if (_this.estimate[name] == null) {
properties_1.defineReadOnly(_this.estimate, name, runMethod(_this, name, { estimate: true }));
}
});
}
Contract.getContractAddress = function (transaction) {
return address_1.getContractAddress(transaction);
};
Contract.getInterface = function (contractInterface) {
if (properties_1.isNamedInstance(abi_1.Interface, contractInterface)) {
return contractInterface;
}
return new abi_1.Interface(contractInterface);
};
// @TODO: Allow timeout?
Contract.prototype.deployed = function () {
return this._deployed();
};
Contract.prototype._deployed = function (blockTag) {
var _this = this;
if (!this._deployedPromise) {
// If we were just deployed, we know the transaction we should occur in
if (this.deployTransaction) {
this._deployedPromise = this.deployTransaction.wait().then(function () {
return _this;
});
}
else {
// @TODO: Once we allow a timeout to be passed in, we will wait
// up to that many blocks for getCode
// Otherwise, poll for our code to be deployed
this._deployedPromise = this.provider.getCode(this.address, blockTag).then(function (code) {
if (code === "0x") {
errors.throwError("contract not deployed", errors.UNSUPPORTED_OPERATION, {
contractAddress: _this.address,
operation: "getDeployed"
});
}
return _this;
});
}
}
return this._deployedPromise;
};
// @TODO:
// estimateFallback(overrides?: TransactionRequest): Promise<BigNumber>
// @TODO:
// estimateDeploy(bytecode: string, ...args): Promise<BigNumber>
Contract.prototype.fallback = function (overrides) {
var _this = this;
if (!this.signer) {
errors.throwError("sending a transaction require a signer", errors.UNSUPPORTED_OPERATION, { operation: "sendTransaction(fallback)" });
}
var tx = properties_1.shallowCopy(overrides || {});
["from", "to"].forEach(function (key) {
if (tx[key] == null) {
return;
}
errors.throwError("cannot override " + key, errors.UNSUPPORTED_OPERATION, { operation: key });
});
tx.to = this.addressPromise;
return this.deployed().then(function () {
return _this.signer.sendTransaction(tx);
});
};
// Reconnect to a different signer or provider
Contract.prototype.connect = function (signerOrProvider) {
if (typeof (signerOrProvider) === "string") {
signerOrProvider = new abstract_signer_1.VoidSigner(signerOrProvider, this.provider);
}
var contract = new (this.constructor)(this.address, this.interface, signerOrProvider);
if (this.deployTransaction) {
properties_1.defineReadOnly(contract, "deployTransaction", this.deployTransaction);
}
return contract;
};
// Re-attach to a different on-chain instance of this contract
Contract.prototype.attach = function (addressOrName) {
return new (this.constructor)(addressOrName, this.interface, this.signer || this.provider);
};
Contract.isIndexed = function (value) {
return properties_1.isNamedInstance(abi_1.Indexed, value);
};
Contract.prototype._getEventFilter = function (eventName) {
var _this = this;
if (typeof (eventName) === "string") {
// Listen for any event
if (eventName === "*") {
return {
prepareEvent: function (e) {
var parsed = _this.interface.parseLog(e);
if (parsed) {
e.values = parsed.values;
e.decode = function (data, topics) {
return _this.interface.decodeEventLog(parsed.eventFragment, data, topics);
},
e.event = parsed.name;
e.eventSignature = parsed.signature;
}
},
eventTag: "*",
filter: { address: this.address },
};
}
var fragment_1 = this.interface.getEvent(eventName);
if (!fragment_1) {
errors.throwError("unknown event - " + eventName, errors.INVALID_ARGUMENT, { argumnet: "eventName", value: eventName });
}
var filter_1 = {
address: this.address,
topics: [this.interface.getEventTopic(fragment_1)]
};
return {
prepareEvent: function (e) {
e.values = _this.interface.decodeEventLog(fragment_1, e.data, e.topics);
},
fragment: fragment_1,
eventTag: getEventTag(filter_1),
filter: filter_1
};
}
var filter = {
address: this.address
};
// Find the matching event in the ABI; if none, we still allow filtering
// since it may be a filter for an otherwise unknown event
var fragment = null;
if (eventName.topics && eventName.topics[0]) {
filter.topics = eventName.topics;
fragment = this.interface.getEvent(eventName.topics[0]);
}
return {
prepareEvent: function (e) {
if (!fragment) {
return;
}
e.values = _this.interface.decodeEventLog(fragment, e.data, e.topics);
},
fragment: fragment,
eventTag: getEventTag(filter),
filter: filter
};
};
// @TODO: move this to _EventFilter.wrapLog. Maybe into prepareEvent?
Contract.prototype._wrapEvent = function (eventFilter, log, listener) {
var _this = this;
var event = properties_1.deepCopy(log);
// @TODO: Move all the below stuff into prepare
eventFilter.prepareEvent(event);
if (eventFilter.fragment) {
event.decode = function (data, topics) {
return _this.interface.decodeEventLog(eventFilter.fragment, data, topics);
},
event.event = eventFilter.fragment.name;
event.eventSignature = eventFilter.fragment.format();
}
event.removeListener = function () {
if (!listener) {
return;
}
_this.removeListener(eventFilter.filter, listener);
};
event.getBlock = function () { return _this.provider.getBlock(log.blockHash); };
event.getTransaction = function () { return _this.provider.getTransaction(log.transactionHash); };
event.getTransactionReceipt = function () { return _this.provider.getTransactionReceipt(log.transactionHash); };
return event;
};
Contract.prototype._addEventListener = function (eventFilter, listener, once) {
var _this = this;
if (!this.provider) {
errors.throwError("events require a provider or a signer with a provider", errors.UNSUPPORTED_OPERATION, { operation: "once" });
}
var wrappedListener = function (log) {
var event = _this._wrapEvent(eventFilter, log, listener);
var values = (event.values || []);
values.push(event);
_this.emit.apply(_this, [eventFilter.filter].concat(values));
};
this.provider.on(eventFilter.filter, wrappedListener);
this._events.push({ eventFilter: eventFilter, listener: listener, wrappedListener: wrappedListener, once: once });
};
Contract.prototype.queryFilter = function (event, fromBlockOrBlockhash, toBlock) {
var _this = this;
var eventFilter = this._getEventFilter(event);
var filter = properties_1.shallowCopy(eventFilter.filter);
if (typeof (fromBlockOrBlockhash) === "string" && bytes_1.isHexString(fromBlockOrBlockhash, 32)) {
filter.blockhash = fromBlockOrBlockhash;
if (toBlock != null) {
errors.throwArgumentError("cannot specify toBlock with blockhash", "toBlock", toBlock);
}
}
else {
filter.fromBlock = ((fromBlockOrBlockhash != null) ? fromBlockOrBlockhash : 0);
filter.toBlock = ((toBlock != null) ? toBlock : "latest");
}
return this.provider.getLogs(filter).then(function (logs) {
return logs.map(function (log) { return _this._wrapEvent(eventFilter, log, null); });
});
};
Contract.prototype.on = function (event, listener) {
this._addEventListener(this._getEventFilter(event), listener, false);
return this;
};
Contract.prototype.once = function (event, listener) {
this._addEventListener(this._getEventFilter(event), listener, true);
return this;
};
Contract.prototype.addListener = function (eventName, listener) {
return this.on(eventName, listener);
};
Contract.prototype.emit = function (eventName) {
var _this = this;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (!this.provider) {
return false;
}
var result = false;
var eventFilter = this._getEventFilter(eventName);
this._events = this._events.filter(function (event) {
// Not this event (keep it for later)
if (event.eventFilter.eventTag !== eventFilter.eventTag) {
return true;
}
// Call the callback in the next event loop
setTimeout(function () {
event.listener.apply(_this, args);
}, 0);
result = true;
// Reschedule it if it not "once"
return !(event.once);
});
return result;
};
Contract.prototype.listenerCount = function (eventName) {
if (!this.provider) {
return 0;
}
var eventFilter = this._getEventFilter(eventName);
return this._events.filter(function (event) {
return event.eventFilter.eventTag === eventFilter.eventTag;
}).length;
};
Contract.prototype.listeners = function (eventName) {
if (!this.provider) {
return [];
}
if (eventName == null) {
return this._events.map(function (event) { return event.listener; });
}
var eventFilter = this._getEventFilter(eventName);
return this._events
.filter(function (event) { return (event.eventFilter.eventTag === eventFilter.eventTag); })
.map(function (event) { return event.listener; });
};
Contract.prototype.removeAllListeners = function (eventName) {
var _this = this;
if (!this.provider) {
return this;
}
var eventFilter = this._getEventFilter(eventName);
this._events = this._events.filter(function (event) {
// Keep non-matching events
if (event.eventFilter.eventTag !== eventFilter.eventTag) {
return true;
}
// De-register this event from the provider and filter it out
_this.provider.removeListener(event.eventFilter.filter, event.wrappedListener);
return false;
});
return this;
};
Contract.prototype.off = function (eventName, listener) {
var _this = this;
if (!this.provider) {
return this;
}
var found = false;
var eventFilter = this._getEventFilter(eventName);
this._events = this._events.filter(function (event) {
// Make sure this event and listener match
if (event.eventFilter.eventTag !== eventFilter.eventTag) {
return true;
}
if (event.listener !== listener) {
return true;
}
_this.provider.removeListener(event.eventFilter.filter, event.wrappedListener);
// Already found a matching event in a previous loop
if (found) {
return true;
}
// Remove this event (returning false filters us out)
found = true;
return false;
});
return this;
};
Contract.prototype.removeListener = function (eventName, listener) {
return this.off(eventName, listener);
};
return Contract;
}());
exports.Contract = Contract;
var ContractFactory = /** @class */ (function () {
function ContractFactory(contractInterface, bytecode, signer) {
var _newTarget = this.constructor;
var bytecodeHex = null;
if (typeof (bytecode) === "string") {
bytecodeHex = bytecode;
}
else if (bytes_1.isBytes(bytecode)) {
bytecodeHex = bytes_1.hexlify(bytecode);
}
else if (bytecode && typeof (bytecode.object) === "string") {
// Allow the bytecode object from the Solidity compiler
bytecodeHex = bytecode.object;
}
else {
// Crash in the next verification step
bytecodeHex = "!";
}
// Make sure it is 0x prefixed
if (bytecodeHex.substring(0, 2) !== "0x") {
bytecodeHex = "0x" + bytecodeHex;
}
// Make sure the final result is valid bytecode
if (!bytes_1.isHexString(bytecodeHex) || (bytecodeHex.length % 2)) {
errors.throwArgumentError("invalid bytecode", "bytecode", bytecode);
}
// If we have a signer, make sure it is valid
if (signer && !properties_1.isNamedInstance(abstract_signer_1.Signer, signer)) {
errors.throwArgumentError("invalid signer", "signer", signer);
}
properties_1.defineReadOnly(this, "bytecode", bytecodeHex);
properties_1.defineReadOnly(this, "interface", _newTarget.getInterface(contractInterface));
properties_1.defineReadOnly(this, "signer", signer || null);
}
ContractFactory.prototype.getDeployTransaction = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var tx = {};
// If we have 1 additional argument, we allow transaction overrides
if (args.length === this.interface.deploy.inputs.length + 1) {
tx = properties_1.shallowCopy(args.pop());
for (var key in tx) {
if (!allowedTransactionKeys[key]) {
throw new Error("unknown transaction override " + key);
}
}
}
// Do not allow these to be overridden in a deployment transaction
["data", "from", "to"].forEach(function (key) {
if (tx[key] == null) {
return;
}
errors.throwError("cannot override " + key, errors.UNSUPPORTED_OPERATION, { operation: key });
});
// Make sure the call matches the constructor signature
errors.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor");
// Set the data to the bytecode + the encoded constructor arguments
tx.data = bytes_1.hexlify(bytes_1.concat([
this.bytecode,
this.interface.encodeDeploy(args)
]));
return tx;
};
ContractFactory.prototype.deploy = function () {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// Get the deployment transaction (with optional overrides)
var tx = this.getDeployTransaction.apply(this, args);
// Send the deployment transaction
return this.signer.sendTransaction(tx).then(function (tx) {
var address = (_this.constructor).getContractAddress(tx);
var contract = (_this.constructor).getContract(address, _this.interface, _this.signer);
properties_1.defineReadOnly(contract, "deployTransaction", tx);
return contract;
});
};
ContractFactory.prototype.attach = function (address) {
return (this.constructor).getContract(address, this.interface, this.signer);
};
ContractFactory.prototype.connect = function (signer) {
return new (this.constructor)(this.interface, this.bytecode, signer);
};
ContractFactory.fromSolidity = function (compilerOutput, signer) {
if (compilerOutput == null) {
errors.throwError("missing compiler output", errors.MISSING_ARGUMENT, { argument: "compilerOutput" });
}
if (typeof (compilerOutput) === "string") {
compilerOutput = JSON.parse(compilerOutput);
}
var abi = compilerOutput.abi;
var bytecode = null;
if (compilerOutput.bytecode) {
bytecode = compilerOutput.bytecode;
}
else if (compilerOutput.evm && compilerOutput.evm.bytecode) {
bytecode = compilerOutput.evm.bytecode;
}
return new this(abi, bytecode, signer);
};
ContractFactory.getInterface = function (contractInterface) {
return Contract.getInterface(contractInterface);
};
ContractFactory.getContractAddress = function (tx) {
return address_1.getContractAddress(tx);
};
ContractFactory.getContract = function (address, contractInterface, signer) {
return new Contract(address, contractInterface, signer);
};
return ContractFactory;
}());
exports.ContractFactory = ContractFactory;

1
packages/errors/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.125";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.125";

27
packages/errors/index.d.ts vendored Normal file
View File

@ -0,0 +1,27 @@
export declare const UNKNOWN_ERROR = "UNKNOWN_ERROR";
export declare const NOT_IMPLEMENTED = "NOT_IMPLEMENTED";
export declare const UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION";
export declare const NETWORK_ERROR = "NETWORK_ERROR";
export declare const BUFFER_OVERRUN = "BUFFER_OVERRUN";
export declare const NUMERIC_FAULT = "NUMERIC_FAULT";
export declare const MISSING_NEW = "MISSING_NEW";
export declare const INVALID_ARGUMENT = "INVALID_ARGUMENT";
export declare const MISSING_ARGUMENT = "MISSING_ARGUMENT";
export declare const UNEXPECTED_ARGUMENT = "UNEXPECTED_ARGUMENT";
export declare const CALL_EXCEPTION = "CALL_EXCEPTION";
export declare const INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS";
export declare const NONCE_EXPIRED = "NONCE_EXPIRED";
export declare const REPLACEMENT_UNDERPRICED = "REPLACEMENT_UNDERPRICED";
export declare const UNPREDICTABLE_GAS_LIMIT = "UNPREDICTABLE_GAS_LIMIT";
export declare function setCensorship(censorship: boolean, permanent?: boolean): void;
export declare function makeError(message: string, code: string, params: any): Error;
export declare function throwError(message: string, code: string, params: any): never;
export declare function throwArgumentError(message: string, name: string, value: any): never;
export declare function checkArgumentCount(count: number, expectedCount: number, suffix?: string): void;
export declare function checkNew(target: any, kind: any): void;
export declare function checkAbstract(target: any, kind: any): void;
export declare function checkNormalize(): void;
export declare function checkSafeUint53(value: number, message?: string): void;
export declare function setLogLevel(logLevel: string): void;
export declare function warn(...args: Array<any>): void;
export declare function info(...args: Array<any>): void;

262
packages/errors/index.js Normal file
View File

@ -0,0 +1,262 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//import { version } from "./_version";
var version = "@TODO";
///////////////////
// Generic Errors
// Unknown Error
exports.UNKNOWN_ERROR = "UNKNOWN_ERROR";
// Not Implemented
exports.NOT_IMPLEMENTED = "NOT_IMPLEMENTED";
// Unsupported Operation
// - operation
exports.UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION";
// Network Error
exports.NETWORK_ERROR = "NETWORK_ERROR";
///////////////////
// Operational Errors
// Buffer Overrun
exports.BUFFER_OVERRUN = "BUFFER_OVERRUN";
// Numeric Fault
// - operation: the operation being executed
// - fault: the reason this faulted
exports.NUMERIC_FAULT = "NUMERIC_FAULT";
///////////////////
// Argument Errors
// Missing new operator to an object
// - name: The name of the class
exports.MISSING_NEW = "MISSING_NEW";
// Invalid argument (e.g. value is incompatible with type) to a function:
// - argument: The argument name that was invalid
// - value: The value of the argument
exports.INVALID_ARGUMENT = "INVALID_ARGUMENT";
// Missing argument to a function:
// - count: The number of arguments received
// - expectedCount: The number of arguments expected
exports.MISSING_ARGUMENT = "MISSING_ARGUMENT";
// Too many arguments
// - count: The number of arguments received
// - expectedCount: The number of arguments expected
exports.UNEXPECTED_ARGUMENT = "UNEXPECTED_ARGUMENT";
///////////////////
// Blockchain Errors
// Call exception
// - transaction: the transaction
// - address?: the contract address
// - args?: The arguments passed into the function
// - method?: The Solidity method signature
// - errorSignature?: The EIP848 error signature
// - errorArgs?: The EIP848 error parameters
// - reason: The reason (only for EIP848 "Error(string)")
exports.CALL_EXCEPTION = "CALL_EXCEPTION";
// Insufficien funds (< value + gasLimit * gasPrice)
// - transaction: the transaction attempted
exports.INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS";
// Nonce has already been used
// - transaction: the transaction attempted
exports.NONCE_EXPIRED = "NONCE_EXPIRED";
// The replacement fee for the transaction is too low
// - transaction: the transaction attempted
exports.REPLACEMENT_UNDERPRICED = "REPLACEMENT_UNDERPRICED";
// The gas limit could not be estimated
// - transaction: the transaction passed to estimateGas
exports.UNPREDICTABLE_GAS_LIMIT = "UNPREDICTABLE_GAS_LIMIT";
//export const errors: { [ code: string ]: string } = {
//};
///////////////////
// Censorship
var _permanentCensorErrors = false;
var _censorErrors = false;
function setCensorship(censorship, permanent) {
if (_permanentCensorErrors) {
throwError("error censorship permanent", exports.UNSUPPORTED_OPERATION, { operation: "setCensorship" });
}
_censorErrors = !!censorship;
_permanentCensorErrors = !!permanent;
}
exports.setCensorship = setCensorship;
///////////////////
// Errors
function makeError(message, code, params) {
if (_censorErrors) {
return new Error("unknown error");
}
if (!code) {
code = exports.UNKNOWN_ERROR;
}
if (!params) {
params = {};
}
var messageDetails = [];
Object.keys(params).forEach(function (key) {
try {
messageDetails.push(key + "=" + JSON.stringify(params[key]));
}
catch (error) {
messageDetails.push(key + "=" + JSON.stringify(params[key].toString()));
}
});
messageDetails.push("version=" + version);
var reason = message;
if (messageDetails.length) {
message += " (" + messageDetails.join(", ") + ")";
}
// @TODO: Any??
var error = new Error(message);
error.reason = reason;
error.code = code;
Object.keys(params).forEach(function (key) {
error[key] = params[key];
});
return error;
}
exports.makeError = makeError;
// @TODO: Enum
function throwError(message, code, params) {
throw makeError(message, code, params);
}
exports.throwError = throwError;
function throwArgumentError(message, name, value) {
return throwError(message, exports.INVALID_ARGUMENT, {
argument: name,
value: value
});
}
exports.throwArgumentError = throwArgumentError;
///////////////////
// Checking
function checkArgumentCount(count, expectedCount, suffix) {
if (suffix) {
suffix = " " + suffix;
}
else {
suffix = "";
}
if (count < expectedCount) {
throwError("missing argument" + suffix, exports.MISSING_ARGUMENT, { count: count, expectedCount: expectedCount });
}
if (count > expectedCount) {
throwError("too many arguments" + suffix, exports.UNEXPECTED_ARGUMENT, { count: count, expectedCount: expectedCount });
}
}
exports.checkArgumentCount = checkArgumentCount;
function checkNew(target, kind) {
if (target === Object || target == null) {
throwError("missing new", exports.MISSING_NEW, { name: kind.name });
}
}
exports.checkNew = checkNew;
/*
export function check(target: any: void {
if (target === Object || target == null) {
throwError("missing new", MISSING_NEW, { name: kind.name });
}
}
*/
function checkAbstract(target, kind) {
if (target === kind) {
throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", exports.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" });
}
else if (target === Object || target == null) {
throwError("missing new", exports.MISSING_NEW, { name: kind.name });
}
}
exports.checkAbstract = checkAbstract;
/*
export function checkTarget(target: any, kind: any): void {
if (target == null) {
throwError("missing new", MISSING_NEW, { name: kind.name });
}
}
*/
function _checkNormalize() {
try {
var missing_1 = [];
// Make sure all forms of normalization are supported
["NFD", "NFC", "NFKD", "NFKC"].forEach(function (form) {
try {
"test".normalize(form);
}
catch (error) {
missing_1.push(form);
}
});
if (missing_1.length) {
throw new Error("missing " + missing_1.join(", "));
}
if (String.fromCharCode(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) {
throw new Error("broken implementation");
}
}
catch (error) {
return error.message;
}
return null;
}
var _normalizeError = _checkNormalize();
function checkNormalize() {
if (_normalizeError) {
throwError("platform missing String.prototype.normalize", exports.UNSUPPORTED_OPERATION, {
operation: "String.prototype.normalize", form: _normalizeError
});
}
}
exports.checkNormalize = checkNormalize;
function checkSafeUint53(value, message) {
if (typeof (value) !== "number") {
return;
}
if (message == null) {
message = "value not safe";
}
if (value < 0 || value >= 0x1fffffffffffff) {
throwError(message, exports.NUMERIC_FAULT, {
operation: "checkSafeInteger",
fault: "out-of-safe-range",
value: value
});
}
if (value % 1) {
throwError(message, exports.NUMERIC_FAULT, {
operation: "checkSafeInteger",
fault: "non-integer",
value: value
});
}
}
exports.checkSafeUint53 = checkSafeUint53;
///////////////////
// Logging
var LogLevels = { debug: 1, "default": 2, info: 2, warn: 3, error: 4, off: 5 };
var LogLevel = LogLevels["default"];
function setLogLevel(logLevel) {
var level = LogLevels[logLevel];
if (level == null) {
warn("invliad log level - " + logLevel);
return;
}
LogLevel = level;
}
exports.setLogLevel = setLogLevel;
function log(logLevel, args) {
if (LogLevel > LogLevels[logLevel]) {
return;
}
console.log.apply(console, args);
}
function warn() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
log("warn", args);
}
exports.warn = warn;
function info() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
log("info", args);
}
exports.info = info;

1
packages/ethers/_version.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const version = "5.0.0-beta.134";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "5.0.0-beta.134";

1
packages/ethers/browser-platform.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const platform = "browser";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.platform = "browser";

18
packages/ethers/ethers.d.ts vendored Normal file
View File

@ -0,0 +1,18 @@
import { Contract, ContractFactory } from "@ethersproject/contracts";
import { BigNumber, FixedNumber } from "@ethersproject/bignumber";
import { Signer, VoidSigner } from "@ethersproject/abstract-signer";
import { Wallet } from "@ethersproject/wallet";
import * as constants from "@ethersproject/constants";
import * as errors from "@ethersproject/errors";
import * as providers from "@ethersproject/providers";
import * as wordlists from "@ethersproject/wordlists";
import * as utils from "./utils";
import { version } from "./_version";
import { BigNumberish } from "@ethersproject/bignumber";
import { Bytes, BytesLike, Signature } from "@ethersproject/bytes";
import { Transaction, UnsignedTransaction } from "@ethersproject/transactions";
import { Wordlist } from "@ethersproject/wordlists/wordlist";
import { platform } from "./platform";
import { ContractFunction, ContractReceipt, ContractTransaction, Event, EventFilter, Overrides, PayableOverrides, CallOverrides, ContractInterface } from "@ethersproject/contracts";
declare function getDefaultProvider(network?: providers.Network | string, options?: any): providers.BaseProvider;
export { version, Signer, Wallet, VoidSigner, getDefaultProvider, providers, Contract, ContractFactory, BigNumber, FixedNumber, constants, errors, utils, wordlists, platform, ContractFunction, ContractReceipt, ContractTransaction, Event, EventFilter, Overrides, PayableOverrides, CallOverrides, ContractInterface, BigNumberish, Bytes, BytesLike, Signature, Transaction, UnsignedTransaction, Wordlist };

55
packages/ethers/ethers.js Normal file
View File

@ -0,0 +1,55 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var contracts_1 = require("@ethersproject/contracts");
exports.Contract = contracts_1.Contract;
exports.ContractFactory = contracts_1.ContractFactory;
var bignumber_1 = require("@ethersproject/bignumber");
exports.BigNumber = bignumber_1.BigNumber;
exports.FixedNumber = bignumber_1.FixedNumber;
var abstract_signer_1 = require("@ethersproject/abstract-signer");
exports.Signer = abstract_signer_1.Signer;
exports.VoidSigner = abstract_signer_1.VoidSigner;
var wallet_1 = require("@ethersproject/wallet");
exports.Wallet = wallet_1.Wallet;
var constants = __importStar(require("@ethersproject/constants"));
exports.constants = constants;
var errors = __importStar(require("@ethersproject/errors"));
exports.errors = errors;
var providers = __importStar(require("@ethersproject/providers"));
exports.providers = providers;
var wordlists = __importStar(require("@ethersproject/wordlists"));
exports.wordlists = wordlists;
var utils = __importStar(require("./utils"));
exports.utils = utils;
var _version_1 = require("./_version");
exports.version = _version_1.version;
var wordlist_1 = require("@ethersproject/wordlists/wordlist");
exports.Wordlist = wordlist_1.Wordlist;
////////////////////////
// Compile-Time Constants
// This is empty in node, and used by browserify to inject extra goodies
var platform_1 = require("./platform");
exports.platform = platform_1.platform;
////////////////////////
// Helper Functions
function getDefaultProvider(network, options) {
if (network == null) {
network = "homestead";
}
var n = providers.getNetwork(network);
if (!n || !n._defaultProvider) {
errors.throwError("unsupported getDefaultProvider network", errors.NETWORK_ERROR, {
operation: "getDefaultProvider",
network: network
});
}
return n._defaultProvider(providers, options);
}
exports.getDefaultProvider = getDefaultProvider;

3
packages/ethers/index.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
import * as ethers from "./ethers";
export { ethers };
export * from "./ethers";

15
packages/ethers/index.js Normal file
View File

@ -0,0 +1,15 @@
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var ethers = __importStar(require("./ethers"));
exports.ethers = ethers;
__export(require("./ethers"));

1
packages/ethers/platform.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare const platform = "node";

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.platform = "node";

Some files were not shown because too many files have changed in this diff Show More