forked from akure/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.ts
577 lines (519 loc) · 16 KB
/
chain.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
import { Buffer } from 'buffer'
import { asset_lists } from '@chain-registry/assets'
import { AssetList, Chain, IBCInfo } from '@chain-registry/types'
import { fromBech32, fromHex, toBech32 } from '@cosmjs/encoding'
import { GasPrice } from '@cosmjs/stargate'
import { assets, chains, ibc } from 'chain-registry'
import RIPEMD160 from 'ripemd160'
import semverGte from 'semver/functions/gte'
import {
BaseChainConfig,
ChainId,
ConfiguredChain,
GenericToken,
SupportedChain,
SupportedChainConfig,
TokenType,
Validator,
} from '@dao-dao/types'
import { cosmos } from '@dao-dao/utils/protobuf'
import { getChainAssets } from './assets'
import {
CHAIN_ENDPOINTS,
CONFIGURED_CHAINS,
MAINNET,
SUPPORTED_CHAINS,
} from './constants'
import { getFallbackImage } from './getFallbackImage'
import { aminoTypes, typesRegistry } from './messages/protobuf'
import {
Validator as RpcValidator,
bondStatusToJSON,
} from './protobuf/codegen/cosmos/staking/v1beta1/staking'
export const getRpcForChainId = (
chainId: string,
// Offset will try a different RPC from the list of available RPCs.
offset = 0
): string => {
let rpc = (
(chainId in CHAIN_ENDPOINTS &&
CHAIN_ENDPOINTS[chainId as keyof typeof CHAIN_ENDPOINTS]) ||
{}
)?.rpc
if (rpc && offset === 0) {
return rpc
}
// If RPC was found but not used, offset > 0, and subtract 1 from offset so we
// try the first RPC in the chain registry list.
if (rpc) {
offset -= 1
}
// Fallback to chain registry.
const chain = maybeGetChainForChainId(chainId)
if (!chain) {
throw new Error(`Unknown chain ID "${chainId}"`)
}
const rpcs = chain?.apis?.rpc ?? []
if (rpcs.length === 0) {
throw new Error(`No RPCs found for chain ID "${chainId}"`)
}
return rpcs[offset % rpcs.length].address
}
export const cosmosValidatorToValidator = ({
operatorAddress: address,
description: { moniker, website, details } = {
moniker: '',
identity: '',
website: '',
securityContact: '',
details: '',
},
commission,
status,
tokens,
}: RpcValidator): Validator => ({
address,
moniker,
website:
website && (website.startsWith('http') ? website : `https://${website}`),
details,
commission: commission?.commissionRates
? Number(commission.commissionRates.rate)
: -1,
status: bondStatusToJSON(status),
tokens: Number(tokens),
})
export const getImageUrlForChainId = (chainId: string): string => {
// Use native token image if available.
const { imageUrl } = maybeGetNativeTokenForChainId(chainId) || {}
if (imageUrl) {
return imageUrl
}
// Fallback to chain logo. Chain logo is sometimes larger and not square.
const { logo_URIs, images } = getChainForChainId(chainId)
const image =
logo_URIs?.png ??
logo_URIs?.jpeg ??
logo_URIs?.svg ??
images?.[0]?.png ??
images?.[0]?.svg
return image || getFallbackImage(chainId)
}
// Convert public key in hex format to a bech32 address.
// https://github.com/cosmos/cosmos-sdk/blob/e09516f4795c637ab12b30bf732ce5d86da78424/crypto/keys/secp256k1/secp256k1.go#L152-L162
// Keplr implementation:
// https://github.com/chainapsis/keplr-wallet/blob/088dc701ce14df77a1ee22b7e39c651e50879d9f/packages/crypto/src/key.ts#L56-L63
export const secp256k1PublicKeyToBech32Address = async (
hexPublicKey: string,
bech32Prefix: string
): Promise<string> => {
const sha256Hash = await crypto.subtle.digest(
'SHA-256',
fromHex(hexPublicKey)
)
const ripemd160Hex = new RIPEMD160()
.update(Buffer.from(sha256Hash))
.digest('hex')
return toBech32(bech32Prefix, fromHex(ripemd160Hex))
}
const cachedChainsById: Record<string, Chain | undefined> = {}
export const maybeGetChainForChainId = (chainId: string): Chain | undefined => {
cachedChainsById[chainId] ||= chains.find(
({ chain_id }) => chain_id === chainId
)
return cachedChainsById[chainId]
}
export const getChainForChainId = (chainId: string): Chain => {
const chain = maybeGetChainForChainId(chainId)
if (!chain) {
throw new Error(`Chain with ID ${chainId} not found`)
}
return chain
}
const cachedAssetListsById: Record<string, AssetList | undefined> = {}
export const maybeGetAssetListForChainId = (
chainId: string
): AssetList | undefined => {
const { chain_name: name } = maybeGetChainForChainId(chainId) ?? {}
if (name) {
cachedAssetListsById[chainId] ||= asset_lists.find(
({ chain_name }) => chain_name === name
)
}
return cachedAssetListsById[chainId]
}
const cachedChainsByName: Record<string, Chain | undefined> = {}
export const maybeGetChainForChainName = (
chainName: string
): Chain | undefined =>
chains.find(({ chain_name }) => chain_name === chainName)
export const getChainForChainName = (chainName: string): Chain => {
cachedChainsByName[chainName] ||= maybeGetChainForChainName(chainName)
if (!cachedChainsByName[chainName]) {
throw new Error(`Chain with name ${chainName} not found`)
}
return cachedChainsByName[chainName]!
}
export const getDisplayNameForChainId = (chainId: string): string =>
maybeGetChainForChainId(chainId)?.pretty_name ?? chainId
const cachedNativeTokens: Record<string, GenericToken | undefined> = {}
export const getNativeTokenForChainId = (chainId: string): GenericToken => {
if (!cachedNativeTokens[chainId]) {
const chain = getChainForChainId(chainId)
const feeDenom = chain.fees?.fee_tokens.find(
({ denom }) => !denom.startsWith('ibc/')
)?.denom
if (!feeDenom) {
throw new Error(`Chain ${chainId} has no fee token`)
}
const assetList =
assets.find(({ chain_name }) => chain_name === chain.chain_name)
?.assets ?? []
const asset = assetList.find(({ base }) => base === feeDenom)
if (!asset) {
throw new Error(`Chain ${chainId} has no asset for fee token ${feeDenom}`)
}
cachedNativeTokens[chainId] = Object.freeze({
chainId,
type: TokenType.Native,
denomOrAddress: feeDenom,
symbol: asset.symbol,
decimals:
asset.denom_units.find(({ denom }) => denom === asset.display)
?.exponent ??
asset.denom_units.find(({ exponent }) => exponent > 0)?.exponent ??
asset.denom_units[0]?.exponent ??
0,
// Use asset images.
imageUrl:
asset.logo_URIs?.png ??
asset.logo_URIs?.jpeg ??
asset.logo_URIs?.svg ??
// Fallback.
getFallbackImage(feeDenom),
source: {
chainId,
denomOrAddress: feeDenom,
},
} as GenericToken)
}
return cachedNativeTokens[chainId]!
}
export const maybeGetNativeTokenForChainId = (
chainId: string
): GenericToken | undefined => {
try {
return getNativeTokenForChainId(chainId)
} catch {
return undefined
}
}
const cachedTokens: Record<string, GenericToken | undefined> = {}
export const getTokenForChainIdAndDenom = (
chainId: string,
denom: string,
// If true, will return placeholder token if not found. If false, will throw
// error.
placeholder = true
): GenericToken => {
try {
// If native token, return it.
const nativeToken = getNativeTokenForChainId(chainId)
if (denom === nativeToken.denomOrAddress) {
return nativeToken
}
const key = `${chainId}:${denom}`
if (!cachedTokens[key]) {
// Try chain assets.
const asset = getChainAssets(chainId).find(
({ denomOrAddress, denomAliases }) =>
denomOrAddress === denom || denomAliases?.includes(denom)
)
if (!asset) {
throw new Error(`Chain ${chainId} has no asset for token ${denom}`)
}
cachedTokens[key] = asset
}
return cachedTokens[key]!
} catch (err) {
if (placeholder) {
return Object.freeze({
chainId,
type: TokenType.Native,
denomOrAddress: denom,
symbol: denom,
decimals: 0,
imageUrl: getFallbackImage(denom),
source: {
chainId,
denomOrAddress: denom,
},
} as GenericToken)
} else {
throw err
}
}
}
export const getIbcTransferInfoBetweenChains = (
srcChainId: string,
destChainId: string
): {
sourceChain: IBCInfo['chain_1']
destinationChain: IBCInfo['chain_1']
sourceChannel: string
info: IBCInfo
} => {
const { chain_name: srcChainName } = getChainForChainId(srcChainId)
const { chain_name: destChainName } = getChainForChainId(destChainId)
const info = ibc.find(
({ chain_1, chain_2, channels }) =>
(chain_1.chain_name === srcChainName &&
chain_2.chain_name === destChainName) ||
(chain_1.chain_name === destChainName &&
chain_2.chain_name === srcChainName &&
channels.some(
({ chain_1, chain_2, version }) =>
version === 'ics20-1' &&
chain_1.port_id === 'transfer' &&
chain_2.port_id === 'transfer'
))
)
if (!info) {
throw new Error(
`Failed to find IBC channel from chain ${srcChainId} to chain ${destChainId}.`
)
}
const srcChainNumber = info.chain_1.chain_name === srcChainName ? 1 : 2
const destChainNumber = info.chain_1.chain_name === destChainName ? 1 : 2
const channel = info.channels.find(
({
[`chain_${srcChainNumber}` as `chain_${typeof srcChainNumber}`]: srcChain,
[`chain_${destChainNumber}` as `chain_${typeof srcChainNumber}`]:
destChain,
version,
}) =>
version === 'ics20-1' &&
srcChain.port_id === 'transfer' &&
destChain.port_id === 'transfer'
)
if (!channel) {
throw new Error(
`Failed to find IBC channel from chain ${srcChainId} to chain ${destChainId}.`
)
}
return {
sourceChain: info[`chain_${srcChainNumber}`],
sourceChannel: channel[`chain_${srcChainNumber}`].channel_id,
destinationChain: info[`chain_${destChainNumber}`],
info,
}
}
export const getIbcTransferInfoFromChannel = (
sourceChainId: string,
sourceChannel: string
): {
destinationChain: IBCInfo['chain_1']
channel: IBCInfo['channels'][number]
info: IBCInfo
} => {
const { chain_name } = getChainForChainId(sourceChainId)
const info = ibc.find(
({ chain_1, chain_2, channels }) =>
// Chain 1 is the source chain.
(chain_1.chain_name === chain_name &&
channels.some(
({ chain_1, version }) =>
version === 'ics20-1' &&
chain_1.port_id === 'transfer' &&
chain_1.channel_id === sourceChannel
)) ||
// Chain 2 is the source chain.
(chain_2.chain_name === chain_name &&
channels.some(
({ chain_2, version }) =>
version === 'ics20-1' &&
chain_2.port_id === 'transfer' &&
chain_2.channel_id === sourceChannel
))
)
if (!info) {
throw new Error(
`Failed to find IBC channel for chain ${sourceChainId} and source channel ${sourceChannel}.`
)
}
const thisChainNumber = info.chain_1.chain_name === chain_name ? 1 : 2
const otherChain = info[`chain_${thisChainNumber === 1 ? 2 : 1}`]
const channel = info.channels.find(
({
[`chain_${thisChainNumber}` as `chain_${typeof thisChainNumber}`]: {
port_id,
channel_id,
},
version,
}) =>
version === 'ics20-1' &&
port_id === 'transfer' &&
channel_id === sourceChannel
)
if (!channel) {
throw new Error(
`Failed to find IBC channel for chain ${sourceChainId} and source channel ${sourceChannel}.`
)
}
return {
destinationChain: otherChain,
channel,
info,
}
}
export const getConfiguredChainConfig = (
chainId: string
): BaseChainConfig | undefined =>
CONFIGURED_CHAINS.find((config) => config.chainId === chainId)
export const getConfiguredChains = ({
mainnet = MAINNET,
}: {
mainnet?: boolean
} = {}): ConfiguredChain[] =>
CONFIGURED_CHAINS.filter(
(config) => mainnet === undefined || config.mainnet === mainnet
).map((config) => ({
chain: getChainForChainId(config.chainId),
...config,
}))
export const getIbcTransferInfoFromConnection = (
sourceChainId: string,
sourceConnectionId: string
): {
info: IBCInfo
destinationChain: IBCInfo['chain_1']
} => {
const { chain_name } = getChainForChainId(sourceChainId)
const info = ibc.find(
({ chain_1, chain_2, channels }) =>
((chain_1.chain_name === chain_name &&
chain_1.connection_id === sourceConnectionId) ||
(chain_2.chain_name === chain_name &&
chain_2.connection_id === sourceConnectionId)) &&
channels.some(
({ chain_1, chain_2, version }) =>
version === 'ics20-1' &&
chain_1.port_id === 'transfer' &&
chain_2.port_id === 'transfer'
)
)
if (!info) {
throw new Error(
`Failed to find IBC info for source chain ${sourceChainId} and connection ${sourceConnectionId}.`
)
}
const thisChainNumber = info.chain_1.chain_name === chain_name ? 1 : 2
const destinationChain = info[`chain_${thisChainNumber === 1 ? 2 : 1}`]
return {
info,
destinationChain,
}
}
export const getSupportedChainConfig = (
chainId: string
): SupportedChainConfig | undefined =>
SUPPORTED_CHAINS.find((config) => config.chainId === chainId)
export const mustGetSupportedChainConfig = (
chainId: string
): SupportedChainConfig => {
const config = getSupportedChainConfig(chainId)
if (!config) {
throw new Error(`Unsupported chain: ${chainId}`)
}
return config
}
export const getSupportedChains = ({
mainnet = MAINNET,
}: {
mainnet?: boolean
} = {}): SupportedChain[] =>
SUPPORTED_CHAINS.filter(
(config) => mainnet === undefined || config.mainnet === mainnet
).map((config) => ({
chain: getChainForChainId(config.chainId),
...config,
}))
// Validates whether the address is for the current chain. If so, return
// undefined. If not, return the correct subdomain.
export const getChainIdForAddress = (address: string): string => {
const supportedChains = getSupportedChains()
// Match supported chain from address prefix. Hopefully there is only one. Use
// the first.
const { prefix } = fromBech32(address)
const chainForAddress = supportedChains.find(
({ chain, mainnet }) =>
chain.bech32_prefix === prefix && mainnet === MAINNET
)
if (!chainForAddress) {
throw new Error(`Unsupported chain: unrecognized prefix "${prefix}"`)
}
return chainForAddress.chain.chain_id
}
/**
* Returns true if the cosmos sdk version is 0.47 or higher, except if the chain
* is Osmosis, in which case it returns false. Osmosis's fork does not support
* all v0.47 features.
*
* @param chainId the chain ID
* @param version the cosmos SDK version string
* @returns true if the cosmos sdk version is 0.47 or higher
*/
export const cosmosSdkVersionIs47OrHigher = (
chainId: string,
version: string
) => chainId !== ChainId.OsmosisMainnet && semverGte(version, '0.47.0')
export const getSignerOptions = ({ chain_id, fees }: Chain) => {
let gasPrice
try {
const nativeToken = getNativeTokenForChainId(chain_id)
const feeToken = fees?.fee_tokens.find(
({ denom }) => denom === nativeToken.denomOrAddress
)
const gasPriceAmount =
feeToken?.average_gas_price ??
feeToken?.high_gas_price ??
feeToken?.low_gas_price ??
feeToken?.fixed_min_gas_price
gasPrice =
feeToken && feeToken.denom.length >= 3 && gasPriceAmount !== undefined
? GasPrice.fromString(gasPriceAmount + feeToken.denom)
: undefined
} catch {}
return {
gasPrice,
registry: typesRegistry,
aminoTypes,
}
}
// Check whether or not the address is a module account.
export const addressIsModule = async (
client: Awaited<
ReturnType<typeof cosmos.ClientFactory.createRPCQueryClient>
>['cosmos'],
address: string
): Promise<boolean> => {
try {
const { account } = await client.auth.v1beta1.account({
address,
})
return (
(account?.typeUrl || account?.$typeUrl) ===
'/cosmos.auth.v1beta1.ModuleAccount'
)
} catch (err) {
if (
err instanceof Error &&
(err.message.includes('not found: key not found') ||
err.message.includes('decoding bech32 failed'))
) {
return false
}
// Rethrow other errors.
throw err
}
}