UNPKG

12.2 kBTypeScriptView Raw
1/// <reference types="node" />
2import { Message } from 'google-protobuf';
3import EventEmitter from 'events';
4import retry from 'retry';
5import { VMType } from './proto/loom_pb';
6import { EvmTxReceipt, EvmTxObject, EthBlockInfo, EthBlockHashList, EthFilterLogList, EthTxHashList } from './proto/evm_pb';
7import { Address } from './address';
8import { IJSONRPCClient } from './internal/json-rpc-client';
9/**
10 * Middleware handlers are expected to transform the input data and return the result.
11 * Handlers should not modify the original input data in any way.
12 */
13export interface ITxMiddlewareHandler {
14 Handle(txData: Readonly<Uint8Array>): Promise<Uint8Array>;
15}
16export declare enum ClientEvent {
17 /**
18 * Emitted when an event is received from a smart contract.
19 * Listener will receive IChainEventArgs.
20 */
21 Contract = "contractEvent",
22 /**
23 * Emitted when an error occurs that can't be relayed by other means.
24 * Listener will receive IClientErrorEventArgs.
25 */
26 Error = "error",
27 /**
28 * Emitted when a connection is established to the DAppChain.
29 * Listener will receive INetEventArgs.
30 */
31 Connected = "connected",
32 /**
33 * Emitted when a connection with the DAppChain is closed.
34 * Listener will receive INetEventArgs.
35 */
36 Disconnected = "disconnected"
37}
38export interface IClientEventArgs {
39 kind: ClientEvent;
40 /** URL that corresponds to the RPC client this event originated from. */
41 url: string;
42}
43/**
44 * Event that's emitted when some kind of error occurs that can't be relayed by other means,
45 * e.g. socket error that occurs while listening for RPC events.
46 */
47export interface IClientErrorEventArgs extends IClientEventArgs {
48 kind: ClientEvent.Error;
49 /** May contain additional information in case of an RPC error. */
50 error?: any;
51}
52/** Generic event containing data emitted by smart contracts. */
53export interface IChainEventArgs extends IClientEventArgs {
54 /** Identifier (currently only used by EVM events). */
55 id: string;
56 kind: ClientEvent.Contract;
57 /** Address of the contract that emitted the event. */
58 contractAddress: Address;
59 /** Address of the caller that caused the event to be emitted. */
60 callerAddress: Address;
61 /** The block containing the tx that caused this event to be emitted. */
62 blockHeight: string;
63 /**
64 * Data that was actually emitted by the smart contract,
65 * the format and structure is defined by that contract.
66 */
67 data: Uint8Array;
68 /** Hash that identifies the uniqueness of the transaction */
69 transactionHash: string;
70 /** Same as transactionHash in bytes */
71 transactionHashBytes: Uint8Array;
72 /** Topics subscribed on events */
73 topics: Array<string>;
74}
75export declare function isInvalidTxNonceError(err: any): boolean;
76/**
77 * Writes to & reads from a Loom DAppChain.
78 *
79 * The client can listen to events emitted by smart contracts running on a DAppChain,
80 * there is currently only one type of event. The event subscription API matches the NodeJS
81 * EventEmitter API. For example...
82 *
83 * function subscribeToEvents(client: Client) {
84 * client.on(ClientEvent.Contract, (event: IChainEventArgs) => {
85 * // handle event
86 * }
87 * }
88 */
89export declare class Client extends EventEmitter {
90 readonly chainId: string;
91 private _writeClient;
92 private _readClient;
93 /** Middleware to apply to transactions before they are transmitted to the DAppChain. */
94 txMiddleware: ITxMiddlewareHandler[];
95 /**
96 * The retry strategy that should be used to resend a tx when it's rejected because of a bad nonce.
97 * Default is a binary exponential retry strategy with 5 retries.
98 * To understand how to tweak the retry strategy see
99 * https://github.com/tim-kos/node-retry#retrytimeoutsoptions
100 */
101 nonceRetryStrategy: retry.OperationOptions;
102 readonly readUrl: string;
103 readonly writeUrl: string;
104 /**
105 * Constructs a new client to read & write data from/to a Loom DAppChain via web sockets.
106 * @param chainId DAppChain identifier.
107 * @param writeUrl Host & port to send txs, specified as "<protocol>://<host>:<port>".
108 * @param readUrl Host & port of the DAppChain read/query interface, this should only be provided
109 * if it's not the same as `writeUrl`.
110 */
111 constructor(chainId: string, writeUrl: string, readUrl?: string);
112 /**
113 * Constructs a new client to read & write data from/to a Loom DAppChain.
114 * @param chainId DAppChain identifier.
115 * @param writeClient RPC client to use to send txs to the DAppChain.
116 * @param readClient RPC client to use to query the DAppChain and listen to DAppChain events, this
117 * should only be provided if it's not the same as `writeClient`.
118 */
119 constructor(chainId: string, writeClient: IJSONRPCClient, readClient?: IJSONRPCClient);
120 /**
121 * Cleans up all underlying network resources.
122 * Once disconnected the client can no longer be used to interact with the DAppChain.
123 */
124 disconnect(): void;
125 /**
126 * Commits a transaction to the DAppChain.
127 *
128 * Consider using Contract.callAsync() instead.
129 *
130 * @param tx Transaction to commit.
131 * @param opts Options object.
132 * @param opts.middleware Middleware to apply before sending the tx to the DAppChain, setting this
133 * option will override the default set of middleware specified in
134 * the `Client.txMiddleware` property.
135 * @returns Result (if any) returned by the tx handler in the contract that processed the tx.
136 */
137 commitTxAsync<T extends Message>(tx: T, opts?: {
138 middleware?: ITxMiddlewareHandler[];
139 }): Promise<Uint8Array | void>;
140 private _commitTxAsync;
141 /**
142 * Queries the current state of a contract.
143 *
144 * Consider using Contract.staticCallAsync() instead.
145 */
146 queryAsync(contract: Address, query?: Uint8Array, vmType?: VMType, caller?: Address): Promise<Uint8Array | void>;
147 /**
148 * Queries the receipt corresponding to a transaction hash
149 *
150 * @param txHash Transaction hash returned by call transaction.
151 * @return EvmTxReceipt The corresponding transaction receipt.
152 */
153 getEvmTxReceiptAsync(txHash: Uint8Array): Promise<EvmTxReceipt | null>;
154 /**
155 * Returns the information about a transaction requested by transaction hash
156 *
157 * @param txHash Transaction hash returned by call transaction.
158 * @return EvmTxObject The corresponding transaction object data.
159 */
160 getEvmTxByHashAsync(txHash: Uint8Array): Promise<EvmTxObject | null>;
161 /**
162 * Queries the code corresponding to a contract
163 *
164 * @param contractAddress Contract address returned by deploy.
165 * @return Uint8Array The corresponding contract code
166 */
167 getEvmCodeAsync(contractAddress: Address): Promise<Uint8Array | null>;
168 /**
169 * Queries logs with filter terms
170 *
171 * @param filter Filter terms
172 * @return Uint8Array The corresponding result of the filter
173 */
174 getEvmLogsAsync(filterObject: Object): Promise<Uint8Array | null>;
175 /**
176 * Creates a new filter based on filter terms, to notify when the state changes
177 *
178 * The function getEVMNewFilterAsync works in the similar way of the RPC call eth_newFilter, for more
179 *
180 * Also for understand how filters works check https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newfilter
181 *
182 * @param filter Filter terms
183 * @return Uint8Array The corresponding result of the filter
184 */
185 newEvmFilterAsync(filterObject: Object): Promise<string | null>;
186 /**
187 * Polling method for a filter, which returns an array of logs which occurred since last poll
188 *
189 * The ID used was requested from getEVMNewFilterChanges or getEVMNewBlockFilter
190 *
191 * @param id Id of filter previously created
192 * @return Uint8Array The corresponding result of the request for given id
193 */
194 getEvmFilterChangesAsync(id: string): Promise<EthBlockHashList | EthFilterLogList | EthTxHashList | null>;
195 /**
196 * Creates a filter in the node, to notify when a new block arrives
197 *
198 * In order to check if the state has changed, call getEVMFilterChangesAsync
199 *
200 * @return String Filter ID in hex format to be used later with getEVMFilterChangesAsync
201 */
202 newBlockEvmFilterAsync(): Promise<string | null>;
203 /**
204 * Creates a filter in the node, to notify when new pending transactions arrive.
205 *
206 * In order to check if the state has changed, call getEVMFilterChangesAsync
207 *
208 * @return String Filter ID in hex format to be used later with getEVMFilterChangesAsync
209 */
210 newPendingTransactionEvmFilterAsync(): Promise<string | null>;
211 /**
212 * Uninstall/delete previously created filters
213 *
214 * The ID used was requested from getEVMNewFilterChanges or getEVMNewBlockFilter
215 *
216 * @param id Id of filter previously created
217 * @return boolean If true the filter is removed with success
218 */
219 uninstallEvmFilterAsync(id: string): Promise<boolean | null>;
220 /**
221 * Returns information about a block by block number.
222 *
223 * @param num Integer of a block number
224 * @param full If true it returns the full transaction objects, if false only the hashes of the transactions
225 */
226 getEvmBlockByNumberAsync(num: string, full?: boolean): Promise<EthBlockInfo | null>;
227 /**
228 * Returns the information about a transaction requested by transaction hash.
229 *
230 * @param hash String with the hash of the transaction
231 * @param full If true it returns the full transaction objects, if false only the hashes of the transactions
232 */
233 getEvmBlockByHashAsync(hashHexStr: string, full?: boolean): Promise<EthBlockInfo | null>;
234 /**
235 * It works by subscribing to particular events. The node will return a subscription id.
236 * For each event that matches the subscription a notification with relevant data is send
237 * together with the subscription id.
238 *
239 * Possible methods:
240 * * "NewHeads": Fires a notification each time a new header is appended to the chain
241 * * "Logs": Returns logs that are included in new imported blocks and match the given filter criteria
242 *
243 * Example of a "filter" (JSON String) with method "logs":
244 * {
245 * "address": "0xa520fe7702b96808f7bbc0d4a233ed1468216cfd",
246 * "topics": ["0x238a0cb8bb633d06981248b822e7bd33c2a35a6089241d099fa519e361cab902"]
247 * }
248 *
249 * @param method Method selected to the filter, can be "newHeads" or "logs"
250 * @param filter JSON string of the filter
251 */
252 evmSubscribeAsync(method: string, filterObject: Object): Promise<string>;
253 /**
254 * Subscriptions are cancelled method and the subscription id as first parameter.
255 * It returns a bool indicating if the subscription was cancelled successful.
256 *
257 * @param id Id of subscription previously created
258 * @return boolean If true the subscription is removed with success
259 */
260 evmUnsubscribeAsync(id: string): Promise<boolean>;
261 /**
262 * Gets the number of the latest block
263 *
264 * @return The block height
265 */
266 getBlockHeightAsync(): Promise<number>;
267 /**
268 * Gets a nonce for the given public key.
269 *
270 * This should only be called by NonceTxMiddleware.
271 *
272 * @param key A hex encoded public key.
273 * @return The nonce.
274 */
275 getNonceAsync(key: string): Promise<number>;
276 /**
277 * Tries to resolve a contract name to an address.
278 *
279 * @param contractName Name of a smart contract on a Loom DAppChain.
280 * @returns Contract address, or null if a contract matching the given name wasn't found.
281 */
282 getContractAddressAsync(contractName: string): Promise<Address | null>;
283 private _emitContractEvent;
284 private _emitNetEvent;
285}