-
Notifications
You must be signed in to change notification settings - Fork 331
/
stargateclient.ts
420 lines (378 loc) · 13 KB
/
stargateclient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/* eslint-disable @typescript-eslint/naming-convention */
import { toHex } from "@cosmjs/encoding";
import { Uint53 } from "@cosmjs/math";
import { Tendermint34Client, toRfc3339WithNanoseconds } from "@cosmjs/tendermint-rpc";
import { sleep } from "@cosmjs/utils";
import { MsgData } from "cosmjs-types/cosmos/base/abci/v1beta1/abci";
import { Coin } from "cosmjs-types/cosmos/base/v1beta1/coin";
import { Account, accountFromAny, AccountParser } from "./accounts";
import {
AuthExtension,
BankExtension,
setupAuthExtension,
setupBankExtension,
setupStakingExtension,
setupTxExtension,
StakingExtension,
TxExtension,
} from "./modules";
import { QueryClient } from "./queryclient";
import {
isSearchByHeightQuery,
isSearchBySentFromOrToQuery,
isSearchByTagsQuery,
SearchTxFilter,
SearchTxQuery,
} from "./search";
export class TimeoutError extends Error {
public readonly txId: string;
public constructor(message: string, txId: string) {
super(message);
this.txId = txId;
}
}
export interface BlockHeader {
readonly version: {
readonly block: string;
readonly app: string;
};
readonly height: number;
readonly chainId: string;
/** An RFC 3339 time string like e.g. '2020-02-15T10:39:10.4696305Z' */
readonly time: string;
}
export interface Block {
/** The ID is a hash of the block header (uppercase hex) */
readonly id: string;
readonly header: BlockHeader;
/** Array of raw transactions */
readonly txs: readonly Uint8Array[];
}
/** A transaction that is indexed as part of the transaction history */
export interface IndexedTx {
readonly height: number;
/** Transaction hash (might be used as transaction ID). Guaranteed to be non-empty upper-case hex */
readonly hash: string;
/** Transaction execution error code. 0 on success. */
readonly code: number;
readonly rawLog: string;
/**
* Raw transaction bytes stored in Tendermint.
*
* If you hash this, you get the transaction hash (= transaction ID):
*
* ```js
* import { sha256 } from "@cosmjs/crypto";
* import { toHex } from "@cosmjs/encoding";
*
* const transactionId = toHex(sha256(indexTx.tx)).toUpperCase();
* ```
*
* Use `decodeTxRaw` from @cosmjs/proto-signing to decode this.
*/
readonly tx: Uint8Array;
readonly gasUsed: number;
readonly gasWanted: number;
}
export interface SequenceResponse {
readonly accountNumber: number;
readonly sequence: number;
}
/**
* The response after successfully broadcasting a transaction.
* Success or failure refer to the execution result.
*/
export interface DeliverTxResponse {
readonly height: number;
/** Error code. The transaction suceeded iff code is 0. */
readonly code: number;
readonly transactionHash: string;
readonly rawLog?: string;
readonly data?: readonly MsgData[];
readonly gasUsed: number;
readonly gasWanted: number;
}
export function isDeliverTxFailure(result: DeliverTxResponse): boolean {
return !!result.code;
}
export function isDeliverTxSuccess(result: DeliverTxResponse): boolean {
return !isDeliverTxFailure(result);
}
/**
* Ensures the given result is a success. Throws a detailed error message otherwise.
*/
export function assertIsDeliverTxSuccess(result: DeliverTxResponse): void {
if (isDeliverTxFailure(result)) {
throw new Error(
`Error when broadcasting tx ${result.transactionHash} at height ${result.height}. Code: ${result.code}; Raw log: ${result.rawLog}`,
);
}
}
/**
* Ensures the given result is a failure. Throws a detailed error message otherwise.
*/
export function assertIsDeliverTxFailure(result: DeliverTxResponse): void {
if (isDeliverTxSuccess(result)) {
throw new Error(
`Transaction ${result.transactionHash} did not fail at height ${result.height}. Code: ${result.code}; Raw log: ${result.rawLog}`,
);
}
}
/** Use for testing only */
export interface PrivateStargateClient {
readonly tmClient: Tendermint34Client | undefined;
}
export interface StargateClientOptions {
readonly accountParser?: AccountParser;
}
export class StargateClient {
private readonly tmClient: Tendermint34Client | undefined;
private readonly queryClient:
| (QueryClient & AuthExtension & BankExtension & StakingExtension & TxExtension)
| undefined;
private chainId: string | undefined;
private readonly accountParser: AccountParser;
public static async connect(
endpoint: string,
options: StargateClientOptions = {},
): Promise<StargateClient> {
const tmClient = await Tendermint34Client.connect(endpoint);
return new StargateClient(tmClient, options);
}
protected constructor(tmClient: Tendermint34Client | undefined, options: StargateClientOptions) {
if (tmClient) {
this.tmClient = tmClient;
this.queryClient = QueryClient.withExtensions(
tmClient,
setupAuthExtension,
setupBankExtension,
setupStakingExtension,
setupTxExtension,
);
}
const { accountParser = accountFromAny } = options;
this.accountParser = accountParser;
}
protected getTmClient(): Tendermint34Client | undefined {
return this.tmClient;
}
protected forceGetTmClient(): Tendermint34Client {
if (!this.tmClient) {
throw new Error(
"Tendermint client not available. You cannot use online functionality in offline mode.",
);
}
return this.tmClient;
}
protected getQueryClient():
| (QueryClient & AuthExtension & BankExtension & StakingExtension & TxExtension)
| undefined {
return this.queryClient;
}
protected forceGetQueryClient(): QueryClient &
AuthExtension &
BankExtension &
StakingExtension &
TxExtension {
if (!this.queryClient) {
throw new Error("Query client not available. You cannot use online functionality in offline mode.");
}
return this.queryClient;
}
public async getChainId(): Promise<string> {
if (!this.chainId) {
const response = await this.forceGetTmClient().status();
const chainId = response.nodeInfo.network;
if (!chainId) throw new Error("Chain ID must not be empty");
this.chainId = chainId;
}
return this.chainId;
}
public async getHeight(): Promise<number> {
const status = await this.forceGetTmClient().status();
return status.syncInfo.latestBlockHeight;
}
public async getAccount(searchAddress: string): Promise<Account | null> {
try {
const account = await this.forceGetQueryClient().auth.account(searchAddress);
return account ? this.accountParser(account) : null;
} catch (error: any) {
if (/rpc error: code = NotFound/i.test(error.toString())) {
return null;
}
throw error;
}
}
public async getSequence(address: string): Promise<SequenceResponse> {
const account = await this.getAccount(address);
if (!account) {
throw new Error(
"Account does not exist on chain. Send some tokens there before trying to query sequence.",
);
}
return {
accountNumber: account.accountNumber,
sequence: account.sequence,
};
}
public async getBlock(height?: number): Promise<Block> {
const response = await this.forceGetTmClient().block(height);
return {
id: toHex(response.blockId.hash).toUpperCase(),
header: {
version: {
block: new Uint53(response.block.header.version.block).toString(),
app: new Uint53(response.block.header.version.app).toString(),
},
height: response.block.header.height,
chainId: response.block.header.chainId,
time: toRfc3339WithNanoseconds(response.block.header.time),
},
txs: response.block.txs,
};
}
public async getBalance(address: string, searchDenom: string): Promise<Coin> {
return this.forceGetQueryClient().bank.balance(address, searchDenom);
}
/**
* Queries all balances for all denoms that belong to this address.
*
* Uses the grpc queries (which iterates over the store internally), and we cannot get
* proofs from such a method.
*/
public async getAllBalances(address: string): Promise<readonly Coin[]> {
return this.forceGetQueryClient().bank.allBalances(address);
}
public async getDelegation(delegatorAddress: string, validatorAddress: string): Promise<Coin | null> {
let delegatedAmount: Coin | undefined;
try {
delegatedAmount = (
await this.forceGetQueryClient().staking.delegation(delegatorAddress, validatorAddress)
).delegationResponse?.balance;
} catch (e: any) {
if (e.toString().includes("key not found")) {
// ignore, `delegatedAmount` remains undefined
} else {
throw e;
}
}
return delegatedAmount || null;
}
public async getTx(id: string): Promise<IndexedTx | null> {
const results = await this.txsQuery(`tx.hash='${id}'`);
return results[0] ?? null;
}
public async searchTx(query: SearchTxQuery, filter: SearchTxFilter = {}): Promise<readonly IndexedTx[]> {
const minHeight = filter.minHeight || 0;
const maxHeight = filter.maxHeight || Number.MAX_SAFE_INTEGER;
if (maxHeight < minHeight) return []; // optional optimization
function withFilters(originalQuery: string): string {
return `${originalQuery} AND tx.height>=${minHeight} AND tx.height<=${maxHeight}`;
}
let txs: readonly IndexedTx[];
if (isSearchByHeightQuery(query)) {
txs =
query.height >= minHeight && query.height <= maxHeight
? await this.txsQuery(`tx.height=${query.height}`)
: [];
} else if (isSearchBySentFromOrToQuery(query)) {
const sentQuery = withFilters(`message.module='bank' AND transfer.sender='${query.sentFromOrTo}'`);
const receivedQuery = withFilters(
`message.module='bank' AND transfer.recipient='${query.sentFromOrTo}'`,
);
const [sent, received] = await Promise.all(
[sentQuery, receivedQuery].map((rawQuery) => this.txsQuery(rawQuery)),
);
const sentHashes = sent.map((t) => t.hash);
txs = [...sent, ...received.filter((t) => !sentHashes.includes(t.hash))];
} else if (isSearchByTagsQuery(query)) {
const rawQuery = withFilters(query.tags.map((t) => `${t.key}='${t.value}'`).join(" AND "));
txs = await this.txsQuery(rawQuery);
} else {
throw new Error("Unknown query type");
}
const filtered = txs.filter((tx) => tx.height >= minHeight && tx.height <= maxHeight);
return filtered;
}
public disconnect(): void {
if (this.tmClient) this.tmClient.disconnect();
}
/**
* Broadcasts a signed transaction to the network and monitors its inclusion in a block.
*
* If broadcasting is rejected by the node for some reason (e.g. because of a CheckTx failure),
* an error is thrown.
*
* If the transaction is not included in a block before the provided timeout, this errors with a `TimeoutError`.
*
* If the transaction is included in a block, a `DeliverTxResponse` is returned. The caller then
* usually needs to check for execution success or failure.
*/
public async broadcastTx(
tx: Uint8Array,
timeoutMs = 60_000,
pollIntervalMs = 3_000,
): Promise<DeliverTxResponse> {
let timedOut = false;
const txPollTimeout = setTimeout(() => {
timedOut = true;
}, timeoutMs);
const pollForTx = async (txId: string): Promise<DeliverTxResponse> => {
if (timedOut) {
throw new TimeoutError(
`Transaction with ID ${txId} was submitted but was not yet found on the chain. You might want to check later. There was a wait of ${
timeoutMs / 10000
} seconds.`,
txId,
);
}
await sleep(pollIntervalMs);
const result = await this.getTx(txId);
return result
? {
code: result.code,
height: result.height,
rawLog: result.rawLog,
transactionHash: txId,
gasUsed: result.gasUsed,
gasWanted: result.gasWanted,
}
: pollForTx(txId);
};
const broadcasted = await this.forceGetTmClient().broadcastTxSync({ tx });
if (broadcasted.code) {
return Promise.reject(
new Error(
`Broadcasting transaction failed with code ${broadcasted.code} (codespace: ${broadcasted.codeSpace}). Log: ${broadcasted.log}`,
),
);
}
const transactionId = toHex(broadcasted.hash).toUpperCase();
return new Promise((resolve, reject) =>
pollForTx(transactionId).then(
(value) => {
clearTimeout(txPollTimeout);
resolve(value);
},
(error) => {
clearTimeout(txPollTimeout);
reject(error);
},
),
);
}
private async txsQuery(query: string): Promise<readonly IndexedTx[]> {
const results = await this.forceGetTmClient().txSearchAll({ query: query });
return results.txs.map((tx) => {
return {
height: tx.height,
hash: toHex(tx.hash).toUpperCase(),
code: tx.result.code,
rawLog: tx.result.log || "",
tx: tx.tx,
gasUsed: tx.result.gasUsed,
gasWanted: tx.result.gasWanted,
};
});
}
}