UNPKG

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