-
Notifications
You must be signed in to change notification settings - Fork 688
Expand file tree
/
Copy pathvalidate.ts
More file actions
401 lines (344 loc) · 11.1 KB
/
validate.ts
File metadata and controls
401 lines (344 loc) · 11.1 KB
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
import sizeOf from "image-size";
import { readFileSync } from "fs";
import { ChainInfo } from "@keplr-wallet/types";
import {
checkEvmRpcConnectivity,
checkRestConnectivity,
checkRPCConnectivity,
NonRecognizableChainFeatures,
validateBasicChainInfoType,
} from "@keplr-wallet/chain-validator";
import { DenomHelper, sortedJsonByKeyStringify } from "@keplr-wallet/common";
import { ChainIdHelper } from "@keplr-wallet/cosmos";
import WebSocket from "ws";
import libPath from "path";
export const fileToChainInfo = (filePath: string) => {
const file = readFileSync(filePath, "utf-8");
const chainInfo: ChainInfo = JSON.parse(file);
return chainInfo;
};
const handleShadowChainId = (chainId: string): string => {
if (chainId === "mantra-dukong-evm-1") {
return "mantra-dukong-1";
} else if (chainId === "mantra-evm-1") {
return "mantra-1";
} else {
return chainId;
}
};
export const validateCosmosChainInfoFromPath = async (
path: string,
): Promise<ChainInfo> => {
const parsed = libPath.parse(path);
if (parsed.ext !== ".json") {
throw new Error("File is not json");
}
// get json from file
const chainInfo = fileToChainInfo(path);
if (chainInfo.hideInUI && chainInfo.chainId !== "wormchain") {
throw new Error("Should not hide chain in UI");
}
// validate chain info
return await validateCosmosChainInfo(parsed.name, chainInfo);
};
export const validateCosmosChainInfo = async (
chainIdentifier: string,
chainInfo: ChainInfo,
): Promise<ChainInfo> => {
const prev = sortedJsonByKeyStringify(chainInfo);
// validate chain information
chainInfo = await validateBasicChainInfoType(chainInfo);
if (sortedJsonByKeyStringify(chainInfo) !== prev) {
throw new Error("Chain info has unknown field");
}
// Check chain identifier
const parsedChainId = ChainIdHelper.parse(chainInfo.chainId).identifier;
if (parsedChainId !== chainIdentifier) {
throw new Error(
`Chain identifier unmatched: (expected: ${parsedChainId}, actual: ${chainIdentifier})`,
);
}
// Check currencies
checkCurrencies(chainInfo);
for (const feature of chainInfo.features ?? []) {
if (!NonRecognizableChainFeatures.includes(feature)) {
// Pass validation for ibc-v2
if (feature !== "ibc-v2") {
throw new Error(
`Only non recognizable feature should be provided: ${feature}`,
);
}
}
}
if (chainInfo.features?.includes("stargate")) {
throw new Error("'stargate' feature is deprecated");
}
if (chainInfo.features?.includes("no-legacy-stdTx")) {
throw new Error("'no-legacy-stdTx' feature is deprecated");
}
if (chainInfo.beta != null) {
throw new Error("Should not set 'beta' field");
}
if (
chainInfo.rpc.startsWith("http://") ||
chainInfo.rest.startsWith("http://")
) {
throw new Error(
"RPC, LCD endpoints cannot be set as HTTP, please set them as HTTPS",
);
}
const chainId = handleShadowChainId(chainInfo.chainId);
// check RPC alive
await checkRPCConnectivity(
chainId,
chainInfo.rpc,
(url) => new WebSocket(url),
);
if (chainInfo.evm) {
if (chainInfo.evm.chainId === 1329) {
throw new Error(
"Cannot set `evm` field for Sei chain. There is a config of EVM version of Sei chain in /evm/eip155:1329.json",
);
}
await checkEvmRpcConnectivity(chainInfo.evm.chainId, chainInfo.evm.rpc);
}
// check REST alive
if (
chainIdentifier !== "gravity-bridge" &&
chainIdentifier !== "sommelier" &&
chainIdentifier !== "kyve"
) {
await checkRestConnectivity(chainId, chainInfo.rest);
}
// check coinGecko vaild
const coinGeckoIds = new Set<string>();
for (const currency of chainInfo.currencies) {
if (currency.coinGeckoId) {
coinGeckoIds.add(currency.coinGeckoId);
}
}
for (const currency of chainInfo.feeCurrencies) {
if (currency.coinGeckoId) {
coinGeckoIds.add(currency.coinGeckoId);
}
}
if (chainInfo.stakeCurrency?.coinGeckoId) {
coinGeckoIds.add(chainInfo.stakeCurrency.coinGeckoId);
}
await checkCoinGeckoIds(...Array.from(coinGeckoIds));
checkIsTestnet(chainInfo);
return chainInfo;
};
export const validateEvmChainInfoFromPath = async (
path: string,
): Promise<ChainInfo> => {
const parsed = libPath.parse(path);
if (parsed.ext !== ".json") {
throw new Error("File is not json");
}
// get json from file
const file = readFileSync(path, "utf-8");
const chainInfo: Omit<ChainInfo, "rest"> & { websocket: string } =
JSON.parse(file);
// validate chain info
return await validateEvmChainInfo(parsed.name, chainInfo);
};
export const validateEvmChainInfo = async (
chainIdentifier: string,
evmChainInfo: Omit<ChainInfo, "rest"> & { websocket: string },
): Promise<ChainInfo> => {
// Check chain identifier
const parsedChainId = ChainIdHelper.parse(evmChainInfo.chainId).identifier;
if (parsedChainId !== chainIdentifier) {
throw new Error(
`Chain identifier unmatched: (expected: ${parsedChainId}, actual: ${chainIdentifier})`,
);
}
const evmChainId = parseInt(parsedChainId.replace("eip155:", ""));
if (isNaN(evmChainId)) {
throw new Error(
"Invalid chain identifier. It should be eip155:{integer greater-than-zero}",
);
}
const { websocket, features, ...restEVMChainInfo } = evmChainInfo;
const chainInfoCandidate = {
...restEVMChainInfo,
rest: evmChainInfo.rpc,
evm: {
chainId: evmChainId,
rpc: evmChainInfo.rpc,
websocket,
},
features: ["eth-address-gen", "eth-key-sign"].concat(features ?? []),
};
const prev = sortedJsonByKeyStringify(chainInfoCandidate);
// validate chain information
const chainInfo = await (async () => {
try {
return await validateBasicChainInfoType(chainInfoCandidate);
} catch (e: any) {
// Ignore bech32Config error
if (e.message === `"bech32Config" is required`) {
return chainInfoCandidate;
} else {
throw e;
}
}
})();
if (sortedJsonByKeyStringify(chainInfo) !== prev) {
throw new Error("Chain info has unknown field");
}
if (chainInfo.evm == null) {
throw new Error("Something went wrong with 'evm' field");
}
// Check currencies
checkCurrencies(chainInfo);
for (const feature of chainInfo.features ?? []) {
if (!NonRecognizableChainFeatures.includes(feature)) {
// Pass validation for ibc-v2
if (feature !== "ibc-v2") {
throw new Error(
`Only non recognizable feature should be provided: ${feature}`,
);
}
}
}
if (chainInfo.beta != null) {
throw new Error("Should not set 'beta' field");
}
if (chainInfo.rpc.startsWith("http://")) {
throw new Error(
"RPC endpoints cannot be set as HTTP, please set them as HTTPS",
);
}
await checkEvmRpcConnectivity(chainInfo.evm.chainId, chainInfo.rpc);
// check coinGecko vaild
const coinGeckoIds = new Set<string>();
for (const currency of chainInfo.currencies) {
if (currency.coinGeckoId) {
coinGeckoIds.add(currency.coinGeckoId);
}
}
for (const currency of chainInfo.feeCurrencies) {
if (currency.coinGeckoId) {
coinGeckoIds.add(currency.coinGeckoId);
}
}
if (chainInfo.stakeCurrency?.coinGeckoId) {
coinGeckoIds.add(chainInfo.stakeCurrency.coinGeckoId);
}
await checkCoinGeckoIds(...Array.from(coinGeckoIds));
return chainInfo;
};
export const checkImageSize = (path: string) => {
const dimensions = sizeOf(path);
if (dimensions.width !== 256 || dimensions.height !== 256) {
throw new Error(
"Image size is not 256x256px. size : " + JSON.stringify(dimensions),
);
}
};
const checkCoinGeckoIds = async (...coinGeckoIds: string[]) => {
const priceURL =
process.env.PRICE_URL || "https://api.coingecko.com/api/v3/simple/price";
const response = await fetch(
`${priceURL}?vs_currencies=usd&ids=${coinGeckoIds.join(",")}`,
);
if (!response.ok) {
throw new Error(`Failed to fetch coinGeckoId ${coinGeckoIds.join(", ")}`);
}
const data = await response.json();
if (data.hasOwnProperty("error")) {
throw new Error(`Failed to fetch coinGeckoId ${coinGeckoIds.join(", ")}`);
}
for (const coinGeckoId of coinGeckoIds) {
if (data[coinGeckoId] == null || data[coinGeckoId]["usd"] == null) {
throw new Error(
`Failed to fetch coinGeckoId ${coinGeckoId} from coingecko`,
);
}
}
};
export const checkCurrencies = (chainInfo: ChainInfo) => {
// Check stake currency
if (
chainInfo.stakeCurrency &&
!chainInfo.currencies.some(
(currency) =>
currency.coinMinimalDenom === chainInfo.stakeCurrency?.coinMinimalDenom,
)
) {
throw new Error(
`Stake Currency must be included in currencies. stakeCurrency: ${chainInfo.stakeCurrency.coinMinimalDenom}`,
);
}
// Check fee currency
if (
!chainInfo.feeCurrencies
.filter((feeCurrency) => !feeCurrency.coinMinimalDenom.startsWith("ibc/"))
.every((feeCurrency) =>
chainInfo.currencies.some(
(currency) =>
feeCurrency.coinMinimalDenom === currency.coinMinimalDenom,
),
) &&
ChainIdHelper.parse(chainInfo.chainId).identifier !== "gravity-bridge"
) {
throw new Error(`Fee Currency must be included in currencies`);
}
// Check currencies
for (const currency of chainInfo.currencies) {
const denomHelper = new DenomHelper(currency.coinMinimalDenom);
if (denomHelper.type !== "native" && denomHelper.type !== "erc20") {
throw new Error(
`Do not provide not native token or ERC20 token to currencies: ${currency.coinMinimalDenom}`,
);
}
if (
currency.coinMinimalDenom.startsWith("ibc/") &&
ChainIdHelper.parse(chainInfo.chainId).identifier !== "centauri"
) {
// 오스모시스 위의 페넘브라는 일단 봐준다.
if (
ChainIdHelper.parse(chainInfo.chainId).identifier === "osmosis" &&
currency.coinMinimalDenom ===
"ibc/0FA9232B262B89E77D1335D54FB1E1F506A92A7E4B51524B400DC69C68D28372"
) {
continue;
}
if (
ChainIdHelper.parse(chainInfo.chainId).identifier === "neutron" &&
currency.coinMinimalDenom ===
"ibc/9598CDEB7C6DB7FC21E746C8E0250B30CD5154F39CA111A9D4948A4362F638BD"
) {
continue;
}
if (
ChainIdHelper.parse(chainInfo.chainId).identifier === "osmosis" &&
currency.coinMinimalDenom ===
"ibc/573FCD90FACEE750F55A8864EF7D38265F07E5A9273FA0E8DAFD39951332B580"
) {
continue;
}
throw new Error(
`Do not provide ibc currency to currencies: ${currency.coinMinimalDenom}`,
);
}
}
};
export const checkIsTestnet = (chainInfo: ChainInfo) => {
const chainNameInLowerCase = chainInfo.chainName.toLowerCase();
const isTestnet = chainInfo.isTestnet;
if (
(chainNameInLowerCase.includes("testnet") ||
chainNameInLowerCase.includes("devnet") ||
chainInfo.chainId.includes("testnet") ||
chainInfo.chainId.includes("devnet")) &&
!isTestnet
) {
throw new Error(
'Add `"isTestnet": true` if your chain is a testnet or devnet',
);
}
return true;
};