-
Notifications
You must be signed in to change notification settings - Fork 345
/
cosmwasmclient.ts
379 lines (344 loc) · 12.9 KB
/
cosmwasmclient.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
/* eslint-disable @typescript-eslint/naming-convention */
import {
Code,
CodeDetails,
Contract,
ContractCodeHistoryEntry,
JsonObject,
} from "@cosmjs/cosmwasm-launchpad";
import { fromAscii, toHex } from "@cosmjs/encoding";
import { Uint53 } from "@cosmjs/math";
import {
Account,
accountFromAny,
AuthExtension,
BankExtension,
Block,
BroadcastTxResponse,
Coin,
IndexedTx,
isSearchByHeightQuery,
isSearchBySentFromOrToQuery,
isSearchByTagsQuery,
QueryClient,
SearchTxFilter,
SearchTxQuery,
SequenceResponse,
setupAuthExtension,
setupBankExtension,
} from "@cosmjs/stargate";
import { TxMsgData } from "@cosmjs/stargate/build/codec/cosmos/base/abci/v1beta1/abci";
import {
broadcastTxCommitSuccess,
Tendermint34Client,
toRfc3339WithNanoseconds,
} from "@cosmjs/tendermint-rpc";
import { assert } from "@cosmjs/utils";
import { CodeInfoResponse } from "./codec/x/wasm/internal/types/query";
import { ContractCodeHistoryOperationType } from "./codec/x/wasm/internal/types/types";
import { setupWasmExtension, WasmExtension } from "./queries";
/** Use for testing only */
export interface PrivateCosmWasmClient {
readonly tmClient: Tendermint34Client | undefined;
readonly queryClient: (QueryClient & AuthExtension & BankExtension & WasmExtension) | undefined;
}
export class CosmWasmClient {
private readonly tmClient: Tendermint34Client | undefined;
private readonly queryClient: (QueryClient & AuthExtension & BankExtension & WasmExtension) | undefined;
private readonly codesCache = new Map<number, CodeDetails>();
private chainId: string | undefined;
public static async connect(endpoint: string): Promise<CosmWasmClient> {
const tmClient = await Tendermint34Client.connect(endpoint);
return new CosmWasmClient(tmClient);
}
protected constructor(tmClient: Tendermint34Client | undefined) {
if (tmClient) {
this.tmClient = tmClient;
this.queryClient = QueryClient.withExtensions(
tmClient,
setupAuthExtension,
setupBankExtension,
setupWasmExtension,
);
}
}
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 & WasmExtension) | undefined {
return this.queryClient;
}
protected forceGetQueryClient(): QueryClient & AuthExtension & BankExtension & WasmExtension {
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 ? accountFromAny(account) : null;
} catch (error) {
if (/rpc error: code = NotFound/i.test(error)) {
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);
}
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();
}
public async broadcastTx(tx: Uint8Array): Promise<BroadcastTxResponse> {
const response = await this.forceGetTmClient().broadcastTxCommit({ tx });
if (broadcastTxCommitSuccess(response)) {
return {
height: response.height,
transactionHash: toHex(response.hash).toUpperCase(),
rawLog: response.deliverTx?.log,
data: response.deliverTx?.data ? TxMsgData.decode(response.deliverTx?.data).data : undefined,
};
}
return response.checkTx.code !== 0
? {
height: response.height,
code: response.checkTx.code,
transactionHash: toHex(response.hash).toUpperCase(),
rawLog: response.checkTx.log,
data: response.checkTx.data ? TxMsgData.decode(response.checkTx.data).data : undefined,
}
: {
height: response.height,
code: response.deliverTx?.code,
transactionHash: toHex(response.hash).toUpperCase(),
rawLog: response.deliverTx?.log,
data: response.deliverTx?.data ? TxMsgData.decode(response.deliverTx?.data).data : undefined,
};
}
public async getCodes(): Promise<readonly Code[]> {
const { codeInfos } = await this.forceGetQueryClient().wasm.listCodeInfo();
return (codeInfos || []).map(
(entry: CodeInfoResponse): Code => {
assert(entry.creator && entry.codeId && entry.dataHash, "entry incomplete");
return {
id: entry.codeId.toNumber(),
creator: entry.creator,
checksum: toHex(entry.dataHash),
source: entry.source || undefined,
builder: entry.builder || undefined,
};
},
);
}
public async getCodeDetails(codeId: number): Promise<CodeDetails> {
const cached = this.codesCache.get(codeId);
if (cached) return cached;
const { codeInfo, data } = await this.forceGetQueryClient().wasm.getCode(codeId);
assert(
codeInfo && codeInfo.codeId && codeInfo.creator && codeInfo.dataHash && data,
"codeInfo missing or incomplete",
);
const codeDetails: CodeDetails = {
id: codeInfo.codeId.toNumber(),
creator: codeInfo.creator,
checksum: toHex(codeInfo.dataHash),
source: codeInfo.source || undefined,
builder: codeInfo.builder || undefined,
data: data,
};
this.codesCache.set(codeId, codeDetails);
return codeDetails;
}
public async getContracts(codeId: number): Promise<readonly Contract[]> {
const { contractInfos } = await this.forceGetQueryClient().wasm.listContractsByCodeId(codeId);
return (contractInfos || []).map(
({ address, contractInfo }): Contract => {
assert(address, "address missing");
assert(
contractInfo && contractInfo.codeId && contractInfo.creator && contractInfo.label,
"contractInfo missing or incomplete",
);
return {
address: address,
codeId: contractInfo.codeId.toNumber(),
creator: contractInfo.creator,
admin: contractInfo.admin || undefined,
label: contractInfo.label,
};
},
);
}
/**
* Throws an error if no contract was found at the address
*/
public async getContract(address: string): Promise<Contract> {
const { address: retrievedAddress, contractInfo } = await this.forceGetQueryClient().wasm.getContractInfo(
address,
);
if (!contractInfo) throw new Error(`No contract found at address "${address}"`);
assert(retrievedAddress, "address missing");
assert(contractInfo.codeId && contractInfo.creator && contractInfo.label, "contractInfo incomplete");
return {
address: retrievedAddress,
codeId: contractInfo.codeId.toNumber(),
creator: contractInfo.creator,
admin: contractInfo.admin || undefined,
label: contractInfo.label,
};
}
/**
* Throws an error if no contract was found at the address
*/
public async getContractCodeHistory(address: string): Promise<readonly ContractCodeHistoryEntry[]> {
const result = await this.forceGetQueryClient().wasm.getContractCodeHistory(address);
if (!result) throw new Error(`No contract history found for address "${address}"`);
const operations: Record<number, "Init" | "Genesis" | "Migrate"> = {
[ContractCodeHistoryOperationType.CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT]: "Init",
[ContractCodeHistoryOperationType.CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS]: "Genesis",
[ContractCodeHistoryOperationType.CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE]: "Migrate",
};
return (result.entries || []).map(
(entry): ContractCodeHistoryEntry => {
assert(entry.operation && entry.codeId && entry.msg);
return {
operation: operations[entry.operation],
codeId: entry.codeId.toNumber(),
msg: JSON.parse(fromAscii(entry.msg)),
};
},
);
}
/**
* Returns the data at the key if present (raw contract dependent storage data)
* or null if no data at this key.
*
* Promise is rejected when contract does not exist.
*/
public async queryContractRaw(address: string, key: Uint8Array): Promise<Uint8Array | null> {
// just test contract existence
await this.getContract(address);
const { data } = await this.forceGetQueryClient().wasm.queryContractRaw(address, key);
return data ?? null;
}
/**
* Makes a smart query on the contract, returns the parsed JSON document.
*
* Promise is rejected when contract does not exist.
* Promise is rejected for invalid query format.
* Promise is rejected for invalid response format.
*/
public async queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject> {
try {
return await this.forceGetQueryClient().wasm.queryContractSmart(address, queryMsg);
} catch (error) {
if (error instanceof Error) {
if (error.message.startsWith("not found: contract")) {
throw new Error(`No contract found at address "${address}"`);
} else {
throw error;
}
} else {
throw 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,
};
});
}
}