ethers.js/packages/contracts/src.ts/index.ts

1006 lines
37 KiB
TypeScript
Raw Normal View History

2019-05-15 01:25:46 +03:00
"use strict";
import { EventFragment, Fragment, Indexed, Interface, JsonFragment, LogDescription, ParamType, Result } from "@ethersproject/abi";
2020-02-07 02:21:34 +03:00
import { Block, BlockTag, Filter, FilterByBlockHash, Listener, Log, Provider, TransactionReceipt, TransactionRequest, TransactionResponse } from "@ethersproject/abstract-provider";
2019-05-15 01:25:46 +03:00
import { Signer, VoidSigner } from "@ethersproject/abstract-signer";
import { getContractAddress } from "@ethersproject/address";
import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
import { BytesLike, concat, hexlify, isBytes, isHexString } from "@ethersproject/bytes";
import { Zero } from "@ethersproject/constants";
import { defineReadOnly, deepCopy, getStatic, resolveProperties, shallowCopy } from "@ethersproject/properties";
2019-05-15 01:25:46 +03:00
import { UnsignedTransaction } from "@ethersproject/transactions";
2019-08-02 01:04:06 +03:00
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
2019-08-02 01:04:06 +03:00
const logger = new Logger(version);
2019-05-15 01:25:46 +03:00
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 type ContractFunction = (...params: Array<any>) => Promise<any>;
export type EventFilter = {
address?: string;
topics?: Array<string>;
// @TODO: Support OR-style topcis; backwards compatible to make this change
//topics?: Array<string | Array<string>>
};
// The (n + 1)th parameter passed to contract event callbacks
export interface Event extends Log {
// The event name
event?: string;
// The event signature
eventSignature?: string;
// The parsed arguments to the event
args?: Result;
2019-05-15 01:25:46 +03:00
// A function that can be used to decode event data and topics
decode?: (data: string, topics?: Array<string>) => any;
// A function that will remove the listener responsible for this event (if any)
removeListener: () => void;
// Get blockchain details about this event's block and transaction
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>;
}
///////////////////////////////
const allowedTransactionKeys: { [ key: string ]: boolean } = {
chainId: true, data: true, from: true, gasLimit: true, gasPrice:true, nonce: true, to: true, value: true
}
2019-05-24 01:59:04 +03:00
// Recursively replaces ENS names with promises to resolve the name and resolves all properties
2019-05-15 01:25:46 +03:00
function resolveAddresses(signerOrProvider: Signer | Provider, value: any, paramType: ParamType | Array<ParamType>): Promise<any> {
if (Array.isArray(paramType)) {
return Promise.all(paramType.map((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);
}
if (paramType.baseType === "array") {
if (!Array.isArray(value)) { throw new Error("invalid value for array"); }
return Promise.all(value.map((v) => resolveAddresses(signerOrProvider, v, paramType.arrayChildren)));
}
return Promise.resolve(value);
}
type RunFunction = (...params: Array<any>) => Promise<any>;
type RunOptions = {
estimate?: boolean;
callStatic?: boolean;
payable?: boolean;
transaction?: boolean;
};
/*
export function _populateTransaction(func: FunctionFragment, args: Array<any>, overrides?: any): Promise<Transaction> {
return null;
}
export function _sendTransaction(func: FunctionFragment, args: Array<any>, overrides?: any): Promise<Transaction> {
return null;
}
*/
2019-05-15 01:25:46 +03:00
function runMethod(contract: Contract, functionName: string, options: RunOptions): RunFunction {
const method = contract.interface.functions[functionName];
2019-05-15 01:25:46 +03:00
return function(...params): Promise<any> {
let tx: any = {}
let blockTag: 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 = 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 (let key in tx) {
if (!allowedTransactionKeys[key]) {
2019-08-02 01:04:06 +03:00
logger.throwError(("unknown transaxction override - " + key), "overrides", tx);
2019-05-15 01:25:46 +03:00
}
}
}
2019-08-02 01:04:06 +03:00
logger.checkArgumentCount(params.length, method.inputs.length, "passed to contract");
2019-05-15 01:25:46 +03:00
// Check overrides make sense
["data", "to"].forEach(function(key) {
if (tx[key] != null) {
2019-08-02 01:04:06 +03:00
logger.throwError("cannot override " + key, Logger.errors.UNSUPPORTED_OPERATION, { operation: key });
2019-05-15 01:25:46 +03:00
}
});
// If the contract was just deployed, wait until it is minded
if (contract.deployTransaction != null) {
tx.to = contract._deployed(blockTag).then(() => {
return contract.addressPromise;
});
} else {
tx.to = contract.addressPromise;
}
return resolveAddresses(contract.signer || contract.provider, params, method.inputs).then((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(Zero);
}
if (!contract.provider && !contract.signer) {
2019-08-02 01:04:06 +03:00
logger.throwError("call (constant functions) require a provider or signer", Logger.errors.UNSUPPORTED_OPERATION, { operation: "call" })
2019-05-15 01:25:46 +03:00
}
// 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 resolveProperties(tx); }
return (contract.signer || contract.provider).call(tx, blockTag).then((value) => {
try {
let result = contract.interface.decodeFunctionResult(method, value);
if (method.outputs.length === 1) {
result = result[0];
}
return result;
} catch (error) {
2019-08-02 01:04:06 +03:00
if (error.code === Logger.errors.CALL_EXCEPTION) {
2019-05-15 01:25:46 +03:00
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) {
2019-08-02 01:04:06 +03:00
logger.throwError("estimate require a provider or signer", Logger.errors.UNSUPPORTED_OPERATION, { operation: "estimateGas" })
2019-05-15 01:25:46 +03:00
}
return (contract.signer || contract.provider).estimateGas(tx);
}
if (tx.gasLimit == null && method.gas != null) {
tx.gasLimit = BigNumber.from(method.gas).add(21000);
}
if (tx.value != null && !method.payable) {
2019-08-02 01:04:06 +03:00
logger.throwArgumentError("contract method is not payable", "sendTransaction:" + method.format(), tx);
2019-05-15 01:25:46 +03:00
}
if (options.transaction) { return resolveProperties(tx); }
2019-05-15 01:25:46 +03:00
if (!contract.signer) {
2019-09-07 01:46:34 +03:00
logger.throwError("sending a transaction requires a signer", Logger.errors.UNSUPPORTED_OPERATION, { operation: "sendTransaction" })
2019-05-15 01:25:46 +03:00
}
return contract.signer.sendTransaction(tx).then((tx) => {
const wait = tx.wait.bind(tx);
2019-05-15 01:25:46 +03:00
tx.wait = (confirmations?: number) => {
return wait(confirmations).then((receipt: ContractReceipt) => {
receipt.events = receipt.logs.map((log) => {
let event: Event = (<Event>deepCopy(log));
let parsed: LogDescription = null;
try {
parsed = contract.interface.parseLog(log);
} catch (e){}
2019-05-15 01:25:46 +03:00
if (parsed) {
event.args = parsed.args;
2019-05-15 01:25:46 +03:00
event.decode = (data: BytesLike, topics?: Array<any>) => {
return this.interface.decodeEventLog(parsed.eventFragment, data, topics);
};
event.event = parsed.name;
event.eventSignature = parsed.signature;
}
event.removeListener = () => { return contract.provider; }
event.getBlock = () => {
return contract.provider.getBlock(receipt.blockHash);
}
event.getTransaction = () => {
return contract.provider.getTransaction(receipt.transactionHash);
}
event.getTransactionReceipt = () => {
return Promise.resolve(receipt);
}
return event;
});
return receipt;
});
};
return tx;
});
});
}
}
function getEventTag(filter: EventFilter): string {
if (filter.address && (filter.topics == null || filter.topics.length === 0)) {
return "*";
}
return (filter.address || "*") + "@" + (filter.topics ? filter.topics.join(":"): "");
}
interface Bucket<T> {
[name: string]: T;
}
2019-05-24 01:24:31 +03:00
class RunningEvent {
readonly tag: string;
readonly filter: EventFilter;
private _listeners: Array<{ listener: Listener, once: boolean }>;
constructor(tag: string, filter: EventFilter) {
defineReadOnly(this, "tag", tag);
defineReadOnly(this, "filter", filter);
this._listeners = [ ];
}
addListener(listener: Listener, once: boolean): void {
this._listeners.push({ listener: listener, once: once });
}
removeListener(listener: Listener): void {
let done = false;
this._listeners = this._listeners.filter((item) => {
if (done || item.listener !== listener) { return true; }
done = true;
return false;
});
}
removeAllListeners(): void {
this._listeners = [];
}
listeners(): Array<Listener> {
return this._listeners.map((i) => i.listener);
}
listenerCount(): number {
return this._listeners.length;
}
run(args: Array<any>): number {
const listenerCount = this.listenerCount();
2019-05-24 01:24:31 +03:00
this._listeners = this._listeners.filter((item) => {
const argsCopy = args.slice();
2019-05-24 01:24:31 +03:00
// Call the callback in the next event loop
setTimeout(() => {
item.listener.apply(this, argsCopy);
}, 0);
// Reschedule it if it not "once"
return !(item.once);
});
return listenerCount;
}
prepareEvent(event: Event): void {
}
}
class ErrorRunningEvent extends RunningEvent {
constructor() {
super("error", null);
}
}
class FragmentRunningEvent extends RunningEvent {
readonly address: string;
readonly interface: Interface;
readonly fragment: EventFragment;
constructor(address: string, contractInterface: Interface, fragment: EventFragment, topics?: Array<string>) {
const filter: EventFilter = {
address: address
}
let topic = contractInterface.getEventTopic(fragment);
if (topics) {
2019-08-02 01:04:06 +03:00
if (topic !== topics[0]) { logger.throwArgumentError("topic mismatch", "topics", topics); }
filter.topics = topics.slice();
} else {
filter.topics = [ topic ];
2019-05-24 01:24:31 +03:00
}
super(getEventTag(filter), filter);
defineReadOnly(this, "address", address);
defineReadOnly(this, "interface", contractInterface);
defineReadOnly(this, "fragment", fragment);
}
prepareEvent(event: Event): void {
super.prepareEvent(event);
event.event = this.fragment.name;
event.eventSignature = this.fragment.format();
event.decode = (data: BytesLike, topics?: Array<string>) => {
return this.interface.decodeEventLog(this.fragment, data, topics);
};
event.args = this.interface.decodeEventLog(this.fragment, event.data, event.topics);
2019-05-24 01:24:31 +03:00
}
}
class WildcardRunningEvent extends RunningEvent {
readonly address: string;
readonly interface: Interface;
constructor(address :string, contractInterface: Interface) {
super("*", { address: address });
defineReadOnly(this, "address", address);
defineReadOnly(this, "interface", contractInterface);
}
prepareEvent(event: Event): void {
super.prepareEvent(event);
const parsed = this.interface.parseLog(event);
2019-05-24 01:24:31 +03:00
if (parsed) {
event.event = parsed.name;
event.eventSignature = parsed.signature;
event.decode = (data: BytesLike, topics?: Array<string>) => {
return this.interface.decodeEventLog(parsed.eventFragment, data, topics);
};
event.args = parsed.args;
2019-05-24 01:24:31 +03:00
}
}
}
2019-05-15 01:25:46 +03:00
export type ContractInterface = string | Array<Fragment | JsonFragment | string> | Interface;
type InterfaceFunc = (contractInterface: ContractInterface) => Interface;
2019-05-15 01:25:46 +03:00
export 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>;
// This is only set if the contract was created with a call to deploy
readonly deployTransaction: TransactionResponse;
2019-05-24 01:24:31 +03:00
private _deployedPromise: Promise<Contract>;
2019-05-15 01:25:46 +03:00
2019-05-24 01:59:04 +03:00
// A list of RunningEvents to track listsners for each event tag
2019-05-24 01:24:31 +03:00
private _runningEvents: { [ eventTag: string ]: RunningEvent };
2019-05-24 01:59:04 +03:00
// Wrapped functions to call emit and allow deregistration from the provider
2019-05-24 01:24:31 +03:00
private _wrappedEmits: { [ eventTag: string ]: (...args: Array<any>) => void };
2019-05-15 01:25:46 +03:00
constructor(addressOrName: string, contractInterface: ContractInterface, signerOrProvider: Signer | Provider) {
2019-08-02 01:04:06 +03:00
logger.checkNew(new.target, Contract);
2019-05-15 01:25:46 +03:00
// @TODO: Maybe still check the addressOrName looks like a valid address or name?
//address = getAddress(address);
defineReadOnly(this, "interface", getStatic<InterfaceFunc>(new.target, "getInterface")(contractInterface));
2019-05-15 01:25:46 +03:00
if (Signer.isSigner(signerOrProvider)) {
defineReadOnly(this, "provider", signerOrProvider.provider || null);
2019-05-15 01:25:46 +03:00
defineReadOnly(this, "signer", signerOrProvider);
} else if (Provider.isProvider(signerOrProvider)) {
2019-05-15 01:25:46 +03:00
defineReadOnly(this, "provider", signerOrProvider);
defineReadOnly(this, "signer", null);
} else {
2019-08-02 01:04:06 +03:00
logger.throwArgumentError("invalid signer or provider", "signerOrProvider", signerOrProvider);
2019-05-15 01:25:46 +03:00
}
defineReadOnly(this, "callStatic", { });
defineReadOnly(this, "estimate", { });
defineReadOnly(this, "functions", { });
defineReadOnly(this, "populateTransaction", { });
defineReadOnly(this, "filters", { });
{
const uniqueFilters: { [ name: string ]: Array<string> } = { };
Object.keys(this.interface.events).forEach((eventSignature) => {
const event = this.interface.events[eventSignature];
2020-02-04 16:01:26 +03:00
defineReadOnly<any, any>(this.filters, eventSignature, (...args: Array<any>) => {
return {
address: this.address,
topics: this.interface.encodeFilterTopics(event, args)
}
});
if (!uniqueFilters[event.name]) { uniqueFilters[event.name] = [ ]; }
uniqueFilters[event.name].push(eventSignature);
});
Object.keys(uniqueFilters).forEach((name) => {
const filters = uniqueFilters[name];
if (filters.length === 1) {
defineReadOnly(this.filters, name, this.filters[filters[0]]);
} else {
logger.warn(`Duplicate definition of ${ name } (${ filters.join(", ")})`);
2019-05-15 01:25:46 +03:00
}
});
}
2019-05-15 01:25:46 +03:00
2019-05-24 01:24:31 +03:00
defineReadOnly(this, "_runningEvents", { });
defineReadOnly(this, "_wrappedEmits", { });
2019-05-15 01:25:46 +03:00
defineReadOnly(this, "address", addressOrName);
if (this.provider) {
defineReadOnly(this, "addressPromise", this.provider.resolveName(addressOrName).then((address) => {
if (address == null) { throw new Error("name not found"); }
return address;
}).catch((error: Error) => {
console.log("ERROR: Cannot find Contract - " + addressOrName);
throw error;
}));
} else {
try {
defineReadOnly(this, "addressPromise", Promise.resolve((<any>(this.interface.constructor)).getAddress(addressOrName)));
} catch (error) {
// Without a provider, we cannot use ENS names
2019-08-02 01:04:06 +03:00
logger.throwArgumentError("provider is required to use non-address contract address", "addressOrName", addressOrName);
2019-05-15 01:25:46 +03:00
}
}
const uniqueFunctions: { [ name: string ]: Array<string> } = { };
2019-05-15 01:25:46 +03:00
Object.keys(this.interface.functions).forEach((name) => {
const fragment = this.interface.functions[name];
// @TODO: This should take in fragment
const run = runMethod(this, name, { });
2019-05-15 01:25:46 +03:00
if (this[name] == null) {
2020-02-04 16:01:26 +03:00
defineReadOnly<any, any>(this, name, run);
2019-05-15 01:25:46 +03:00
}
if (this.functions[name] == null) {
defineReadOnly(this.functions, name, run);
}
if (this.callStatic[name] == null) {
defineReadOnly(this.callStatic, name, runMethod(this, name, { callStatic: true }));
}
if (this.populateTransaction[name] == null) {
defineReadOnly(this.populateTransaction, name, runMethod(this, name, { transaction: true }));
}
if (this.estimate[name] == null) {
defineReadOnly(this.estimate, name, runMethod(this, name, { estimate: true }));
}
if (!uniqueFunctions[fragment.name]) { uniqueFunctions[fragment.name] = [ ]; }
uniqueFunctions[fragment.name].push(name);
});
Object.keys(uniqueFunctions).forEach((name) => {
const signatures = uniqueFunctions[name];
if (signatures.length > 1) {
logger.warn(`Duplicate definition of ${ name } (${ signatures.join(", ")})`);
return;
}
if (this[name] == null) {
defineReadOnly(this, name, this[signatures[0]]);
}
defineReadOnly(this.functions, name, this.functions[signatures[0]]);
defineReadOnly(this.callStatic, name, this.callStatic[signatures[0]]);
defineReadOnly(this.populateTransaction, name, this.populateTransaction[signatures[0]]);
defineReadOnly(this.estimate, name, this.estimate[signatures[0]]);
2019-05-15 01:25:46 +03:00
});
}
static getContractAddress(transaction: { from: string, nonce: BigNumberish }): string {
return getContractAddress(transaction);
}
static getInterface(contractInterface: ContractInterface): Interface {
if (Interface.isInterface(contractInterface)) {
2019-05-15 01:25:46 +03:00
return contractInterface;
}
return new Interface(contractInterface);
}
// @TODO: Allow timeout?
deployed(): Promise<Contract> {
return this._deployed();
}
_deployed(blockTag?: BlockTag): Promise<Contract> {
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(() => {
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((code) => {
if (code === "0x") {
2019-08-02 01:04:06 +03:00
logger.throwError("contract not deployed", Logger.errors.UNSUPPORTED_OPERATION, {
2019-05-15 01:25:46 +03:00
contractAddress: this.address,
operation: "getDeployed"
});
}
return this;
});
}
}
return this._deployedPromise;
}
// @TODO:
// estimateFallback(overrides?: TransactionRequest): Promise<BigNumber>
// @TODO:
// estimateDeploy(bytecode: string, ...args): Promise<BigNumber>
fallback(overrides?: TransactionRequest): Promise<TransactionResponse> {
if (!this.signer) {
2019-09-07 01:46:34 +03:00
logger.throwError("sending a transactions require a signer", Logger.errors.UNSUPPORTED_OPERATION, { operation: "sendTransaction(fallback)" })
2019-05-15 01:25:46 +03:00
}
const tx: TransactionRequest = shallowCopy(overrides || {});
2019-05-15 01:25:46 +03:00
["from", "to"].forEach(function(key) {
if ((<any>tx)[key] == null) { return; }
2019-08-02 01:04:06 +03:00
logger.throwError("cannot override " + key, Logger.errors.UNSUPPORTED_OPERATION, { operation: key })
2019-05-15 01:25:46 +03:00
});
tx.to = this.addressPromise;
return this.deployed().then(() => {
return this.signer.sendTransaction(tx);
});
}
// Reconnect to a different signer or provider
connect(signerOrProvider: Signer | Provider | string): Contract {
if (typeof(signerOrProvider) === "string") {
signerOrProvider = new VoidSigner(signerOrProvider, this.provider);
}
const contract = new (<{ new(...args: any[]): Contract }>(this.constructor))(this.address, this.interface, signerOrProvider);
2019-05-15 01:25:46 +03:00
if (this.deployTransaction) {
defineReadOnly(contract, "deployTransaction", this.deployTransaction);
}
return contract;
}
// Re-attach to a different on-chain instance of this contract
attach(addressOrName: string): Contract {
return new (<{ new(...args: any[]): Contract }>(this.constructor))(addressOrName, this.interface, this.signer || this.provider);
}
static isIndexed(value: any): value is Indexed {
return Indexed.isIndexed(value);
2019-05-15 01:25:46 +03:00
}
2019-05-24 01:24:31 +03:00
private _normalizeRunningEvent(runningEvent: RunningEvent): RunningEvent {
// Already have an instance of this event running; we can re-use it
if (this._runningEvents[runningEvent.tag]) {
return this._runningEvents[runningEvent.tag];
}
return runningEvent
}
2019-05-15 01:25:46 +03:00
2019-05-24 01:24:31 +03:00
private _getRunningEvent(eventName: EventFilter | string): RunningEvent {
2019-05-15 01:25:46 +03:00
if (typeof(eventName) === "string") {
2019-05-24 01:24:31 +03:00
// Listen for "error" events (if your contract has an error event, include
// the full signature to bypass this special event keyword)
if (eventName === "error") {
return this._normalizeRunningEvent(new ErrorRunningEvent());
}
2019-05-15 01:25:46 +03:00
// Listen for any event
if (eventName === "*") {
2019-05-24 01:24:31 +03:00
return this._normalizeRunningEvent(new WildcardRunningEvent(this.address, this.interface));
2019-05-15 01:25:46 +03:00
}
const fragment = this.interface.getEvent(eventName)
2019-05-15 01:25:46 +03:00
if (!fragment) {
2019-08-02 01:04:06 +03:00
logger.throwArgumentError("unknown event - " + eventName, "eventName", eventName);
2019-05-15 01:25:46 +03:00
}
2019-05-24 01:24:31 +03:00
return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment));
2019-05-15 01:25:46 +03:00
}
const filter: EventFilter = {
2019-05-15 01:25:46 +03:00
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
2019-05-24 01:24:31 +03:00
if (eventName.topics) {
if (eventName.topics[0]) {
const fragment = this.interface.getEvent(eventName.topics[0]);
2019-05-24 01:24:31 +03:00
if (fragment) {
return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment, eventName.topics));
2019-05-24 01:24:31 +03:00
}
}
2019-05-15 01:25:46 +03:00
filter.topics = eventName.topics;
}
2019-05-24 01:24:31 +03:00
return this._normalizeRunningEvent(new RunningEvent(getEventTag(filter), filter));
}
_checkRunningEvents(runningEvent: RunningEvent): void {
if (runningEvent.listenerCount() === 0) {
delete this._runningEvents[runningEvent.tag];
}
// If we have a poller for this, remove it
const emit = this._wrappedEmits[runningEvent.tag];
2019-05-24 01:24:31 +03:00
if (emit) {
this.provider.off(runningEvent.filter, emit);
delete this._wrappedEmits[runningEvent.tag];
2019-05-15 01:25:46 +03:00
}
}
2019-05-24 01:24:31 +03:00
private _wrapEvent(runningEvent: RunningEvent, log: Log, listener: Listener): Event {
const event = <Event>deepCopy(log);
2019-05-15 01:25:46 +03:00
2019-05-24 01:24:31 +03:00
try {
runningEvent.prepareEvent(event);
} catch (error) {
this.emit("error", error);
throw error;
2019-05-15 01:25:46 +03:00
}
event.removeListener = () => {
if (!listener) { return; }
2019-05-24 01:24:31 +03:00
runningEvent.removeListener(listener);
this._checkRunningEvents(runningEvent);
2019-05-15 01:25:46 +03:00
};
event.getBlock = () => { return this.provider.getBlock(log.blockHash); }
event.getTransaction = () => { return this.provider.getTransaction(log.transactionHash); }
event.getTransactionReceipt = () => { return this.provider.getTransactionReceipt(log.transactionHash); }
return event;
}
2019-05-24 01:24:31 +03:00
private _addEventListener(runningEvent: RunningEvent, listener: Listener, once: boolean): void {
2019-05-15 01:25:46 +03:00
if (!this.provider) {
2019-08-02 01:04:06 +03:00
logger.throwError("events require a provider or a signer with a provider", Logger.errors.UNSUPPORTED_OPERATION, { operation: "once" })
2019-05-15 01:25:46 +03:00
}
2019-05-24 01:24:31 +03:00
runningEvent.addListener(listener, once);
// Track this running event and its listeners (may already be there; but no hard in updating)
this._runningEvents[runningEvent.tag] = runningEvent;
// If we are not polling the provider, start
if (!this._wrappedEmits[runningEvent.tag]) {
const wrappedEmit = (log: Log) => {
const event = this._wrapEvent(runningEvent, log, listener);
const args = (event.args || []);
args.push(event);
this.emit(runningEvent.filter, ...args);
2019-05-24 01:24:31 +03:00
};
this._wrappedEmits[runningEvent.tag] = wrappedEmit;
2019-05-15 01:25:46 +03:00
2019-05-24 01:24:31 +03:00
// Special events, like "error" do not have a filter
if (runningEvent.filter != null) {
this.provider.on(runningEvent.filter, wrappedEmit);
}
}
2019-05-15 01:25:46 +03:00
}
queryFilter(event: EventFilter, fromBlockOrBlockhash?: BlockTag | string, toBlock?: BlockTag): Promise<Array<Event>> {
const runningEvent = this._getRunningEvent(event);
const filter = shallowCopy(runningEvent.filter);
2019-05-15 01:25:46 +03:00
if (typeof(fromBlockOrBlockhash) === "string" && isHexString(fromBlockOrBlockhash, 32)) {
if (toBlock != null) {
2019-08-02 01:04:06 +03:00
logger.throwArgumentError("cannot specify toBlock with blockhash", "toBlock", toBlock);
2019-05-15 01:25:46 +03:00
}
2020-02-07 02:21:34 +03:00
(<FilterByBlockHash>filter).blockhash = fromBlockOrBlockhash;
2019-05-15 01:25:46 +03:00
} else {
2020-02-07 02:21:34 +03:00
(<Filter>filter).fromBlock = ((fromBlockOrBlockhash != null) ? fromBlockOrBlockhash: 0);
(<Filter>filter).toBlock = ((toBlock != null) ? toBlock: "latest");
2019-05-15 01:25:46 +03:00
}
return this.provider.getLogs(filter).then((logs) => {
2019-05-24 22:59:04 +03:00
return logs.map((log) => this._wrapEvent(runningEvent, log, null));
2019-05-15 01:25:46 +03:00
});
}
2019-05-24 01:24:31 +03:00
on(event: EventFilter | string, listener: Listener): this {
this._addEventListener(this._getRunningEvent(event), listener, false);
2019-05-15 01:25:46 +03:00
return this;
}
2019-05-24 01:24:31 +03:00
once(event: EventFilter | string, listener: Listener): this {
this._addEventListener(this._getRunningEvent(event), listener, true);
2019-05-15 01:25:46 +03:00
return this;
}
emit(eventName: EventFilter | string, ...args: Array<any>): boolean {
if (!this.provider) { return false; }
const runningEvent = this._getRunningEvent(eventName);
const result = (runningEvent.run(args) > 0);
2019-05-15 01:25:46 +03:00
2019-05-24 01:24:31 +03:00
// May have drained all the "once" events; check for living events
this._checkRunningEvents(runningEvent);
2019-05-15 01:25:46 +03:00
return result;
}
listenerCount(eventName?: EventFilter | string): number {
if (!this.provider) { return 0; }
2019-05-24 01:24:31 +03:00
return this._getRunningEvent(eventName).listenerCount();
2019-05-15 01:25:46 +03:00
}
listeners(eventName?: EventFilter | string): Array<Listener> {
if (!this.provider) { return []; }
if (eventName == null) {
const result: Array<Listener> = [ ];
2019-05-24 01:24:31 +03:00
for (let tag in this._runningEvents) {
this._runningEvents[tag].listeners().forEach((listener) => {
result.push(listener)
});
}
return result;
2019-05-15 01:25:46 +03:00
}
2019-05-24 01:24:31 +03:00
return this._getRunningEvent(eventName).listeners();
2019-05-15 01:25:46 +03:00
}
2019-05-24 01:24:31 +03:00
removeAllListeners(eventName?: EventFilter | string): this {
2019-05-15 01:25:46 +03:00
if (!this.provider) { return this; }
2019-05-24 01:24:31 +03:00
if (eventName == null) {
for (const tag in this._runningEvents) {
const runningEvent = this._runningEvents[tag];
2019-05-24 01:24:31 +03:00
runningEvent.removeAllListeners();
this._checkRunningEvents(runningEvent);
2019-05-15 01:25:46 +03:00
}
2019-05-24 01:24:31 +03:00
return this;
}
2019-05-15 01:25:46 +03:00
2019-05-24 01:24:31 +03:00
// Delete any listeners
const runningEvent = this._getRunningEvent(eventName);
2019-05-24 01:24:31 +03:00
runningEvent.removeAllListeners();
this._checkRunningEvents(runningEvent);
2019-05-15 01:25:46 +03:00
return this;
}
2019-05-24 01:24:31 +03:00
off(eventName: EventFilter | string, listener: Listener): this {
2019-05-15 01:25:46 +03:00
if (!this.provider) { return this; }
const runningEvent = this._getRunningEvent(eventName);
2019-05-24 01:24:31 +03:00
runningEvent.removeListener(listener);
this._checkRunningEvents(runningEvent);
2019-05-15 01:25:46 +03:00
return this;
}
2019-05-24 01:24:31 +03:00
removeListener(eventName: EventFilter | string, listener: Listener): this {
2019-05-15 01:25:46 +03:00
return this.off(eventName, listener);
}
}
export class ContractFactory {
readonly interface: Interface;
readonly bytecode: string;
readonly signer: Signer;
constructor(contractInterface: ContractInterface, bytecode: BytesLike | { object: string }, signer?: Signer) {
let bytecodeHex: string = null;
if (typeof(bytecode) === "string") {
bytecodeHex = bytecode;
} else if (isBytes(bytecode)) {
bytecodeHex = hexlify(bytecode);
} else if (bytecode && typeof(bytecode.object) === "string") {
// Allow the bytecode object from the Solidity compiler
bytecodeHex = (<any>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 (!isHexString(bytecodeHex) || (bytecodeHex.length % 2)) {
2019-08-02 01:04:06 +03:00
logger.throwArgumentError("invalid bytecode", "bytecode", bytecode);
2019-05-15 01:25:46 +03:00
}
// If we have a signer, make sure it is valid
if (signer && !Signer.isSigner(signer)) {
2019-08-02 01:04:06 +03:00
logger.throwArgumentError("invalid signer", "signer", signer);
2019-05-15 01:25:46 +03:00
}
defineReadOnly(this, "bytecode", bytecodeHex);
defineReadOnly(this, "interface", getStatic<InterfaceFunc>(new.target, "getInterface")(contractInterface));
2019-05-15 01:25:46 +03:00
defineReadOnly(this, "signer", signer || null);
}
getDeployTransaction(...args: Array<any>): UnsignedTransaction {
let tx: UnsignedTransaction = { };
// If we have 1 additional argument, we allow transaction overrides
if (args.length === this.interface.deploy.inputs.length + 1) {
tx = shallowCopy(args.pop());
for (const key in tx) {
2019-05-15 01:25:46 +03:00
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((key) => {
if ((<any>tx)[key] == null) { return; }
2019-08-02 01:04:06 +03:00
logger.throwError("cannot override " + key, Logger.errors.UNSUPPORTED_OPERATION, { operation: key })
2019-05-15 01:25:46 +03:00
});
// Make sure the call matches the constructor signature
2019-08-02 01:04:06 +03:00
logger.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor");
2019-05-15 01:25:46 +03:00
// Set the data to the bytecode + the encoded constructor arguments
tx.data = hexlify(concat([
this.bytecode,
this.interface.encodeDeploy(args)
]));
return tx
}
deploy(...args: Array<any>): Promise<Contract> {
2019-06-25 04:26:48 +03:00
return resolveAddresses(this.signer, args, this.interface.deploy.inputs).then((args) => {
2019-05-15 01:25:46 +03:00
2019-06-25 04:26:48 +03:00
// Get the deployment transaction (with optional overrides)
const tx = this.getDeployTransaction(...args);
2019-05-15 01:25:46 +03:00
2019-06-25 04:26:48 +03:00
// Send the deployment transaction
return this.signer.sendTransaction(tx).then((tx) => {
const address = (<any>(this.constructor)).getContractAddress(tx);
const contract = (<any>(this.constructor)).getContract(address, this.interface, this.signer);
2019-06-25 04:26:48 +03:00
defineReadOnly(contract, "deployTransaction", tx);
return contract;
});
2019-05-15 01:25:46 +03:00
});
}
attach(address: string): Contract {
return (<any>(this.constructor)).getContract(address, this.interface, this.signer);
}
connect(signer: Signer) {
return new (<{ new(...args: any[]): ContractFactory }>(this.constructor))(this.interface, this.bytecode, signer);
}
static fromSolidity(compilerOutput: any, signer?: Signer): ContractFactory {
if (compilerOutput == null) {
2019-08-02 01:04:06 +03:00
logger.throwError("missing compiler output", Logger.errors.MISSING_ARGUMENT, { argument: "compilerOutput" });
2019-05-15 01:25:46 +03:00
}
if (typeof(compilerOutput) === "string") {
compilerOutput = JSON.parse(compilerOutput);
}
const abi = compilerOutput.abi;
2019-05-15 01:25:46 +03:00
let bytecode: any = null;
if (compilerOutput.bytecode) {
bytecode = compilerOutput.bytecode;
} else if (compilerOutput.evm && compilerOutput.evm.bytecode) {
bytecode = compilerOutput.evm.bytecode;
}
return new this(abi, bytecode, signer);
}
static getInterface(contractInterface: ContractInterface) {
return Contract.getInterface(contractInterface);
}
static getContractAddress(tx: { from: string, nonce: BytesLike | BigNumber | number }): string {
return getContractAddress(tx);
}
static getContract(address: string, contractInterface: ContractInterface, signer?: Signer): Contract {
return new Contract(address, contractInterface, signer);
}
}