forked from InjectiveLabs/injective-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokens.ts
247 lines (205 loc) · 6.58 KB
/
tokens.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
import { execSync } from 'child_process'
import { HttpRestClient } from '@injectivelabs/utils'
import { DenomClient, ChainGrpcBankApi } from '@injectivelabs/sdk-ts'
import { Token, TokenType } from '@injectivelabs/token-metadata'
import { Network, getNetworkEndpoints } from '@injectivelabs/networks'
import fsPromises from 'fs/promises'
import fs from 'fs'
type CosmostationToken = {
denom: string
type: string
origin_chain: string
origin_denom: string
origin_type: string
symbol: string
decimals: 6
description: string
image: string
coinGeckoId: string
}
const ENDPOINTS = getNetworkEndpoints(Network.Mainnet)
const bankApi = new ChainGrpcBankApi(ENDPOINTS.grpc)
const denomClient = new DenomClient(Network.Mainnet)
const chainListClient = new HttpRestClient('https://raw.githubusercontent.com/')
const ASSETS_JSON_PATH =
'/shane-moore/chainlist/main/chain/injective/assets.json'
const COSMOSTATION_BRANCH_NAME = `update-injective-assets-${new Date().getTime()}`
const COSMOSTATION_REPO_PATH = './chainlist'
const githubToken = process.argv
.find((arg) => arg.startsWith('--GITHUB_TOKEN='))
?.split('=')[1]
if (!githubToken) {
console.error('Error: GitHub token is required.')
process.exit(1)
}
async function fetchExistingCosmostationTokens(): Promise<CosmostationToken[]> {
try {
const response = (await chainListClient.get(ASSETS_JSON_PATH)) as any
return response.data as Promise<CosmostationToken[]>
} catch (error) {
console.error(`Error fetching existing assets: ${error}`)
return []
}
}
async function fetchSupplyTokenMeta() {
const { supply } = await bankApi.fetchAllTotalSupply()
const denoms = supply.map((token) => token?.denom)
const tokens = await denomClient.getDenomsToken(denoms)
return tokens.filter(
(token) =>
token && token?.tokenType !== TokenType.Unknown && token?.coinGeckoId,
)
}
function getType(tokenType: string) {
const typeMap = {
[TokenType.Ibc]: 'ibc',
[TokenType.Erc20]: 'bridge',
} as { [key: string]: string }
return typeMap[tokenType] || 'native'
}
function getOriginChain(token: Token) {
const typeMap = {
[TokenType.Ibc]: token.name.toLowerCase(),
[TokenType.Erc20]: 'ethereum',
[TokenType.TokenFactory]: 'injective',
[TokenType.Native]: 'injective',
} as { [key: string]: string }
return typeMap[token.tokenType] || ''
}
function getTokenMetaByTokenType(tokenType: string, token: Token) {
switch (tokenType) {
case TokenType.Ibc:
return {
enable: true,
channel: token.ibc?.channelId,
port: 'transfer',
}
case TokenType.Erc20:
return {
contract: token.erc20?.address,
}
default:
return {}
}
}
function tokenExistsInArray(token: Token, array: Token[]) {
return array.some(
(asset) => asset.denom.toLowerCase() === token.denom.toLowerCase(),
)
}
function getOriginDenom(token: Token) {
switch (token.tokenType) {
case TokenType.Ibc:
return token.ibc?.baseDenom
case TokenType.TokenFactory:
return token.denom
default:
return token.symbol.toLowerCase()
}
}
function convertToCosmostationTokens(
tokens: Token[],
existingCosmostationTokens: any[],
): CosmostationToken[] {
return tokens.reduce(
(acc, token) => {
const tokenExists = tokenExistsInArray(token, acc)
if (tokenExists) {
const indexInExisting = acc.findIndex(
(asset) => asset.denom.toLowerCase() === token.denom.toLowerCase(),
)
if (!acc[indexInExisting].coinGeckoId) {
acc[indexInExisting] = {
...acc[indexInExisting],
coinGeckoId: token.coinGeckoId,
}
}
return acc
}
const newToken = {
denom: token.denom,
symbol: token.symbol,
description: token.name,
decimals: token.decimals,
coinGeckoId: token.coinGeckoId,
type: getType(token.tokenType),
origin_denom: getOriginDenom(token),
origin_chain: getOriginChain(token),
...getTokenMetaByTokenType(token.tokenType, token),
}
return [...acc, newToken]
},
[...existingCosmostationTokens],
)
}
async function createPullRequest(githubToken: string) {
const githubClient = new HttpRestClient('https://api.github.com/')
githubClient.setConfig({
headers: {
Authorization: `token ${githubToken}`,
Accept: 'application/vnd.github.v3+json',
},
})
const pullRequestData = {
title: 'Add Injective assets automatically',
head: COSMOSTATION_BRANCH_NAME,
base: 'main',
body: "This PR updates Injective's assets.json with new token metadata automatically.",
}
try {
const response = (await githubClient.post(
'/repos/shane-moore/chainlist/pulls',
pullRequestData,
)) as any
console.log(`Pull request created: ${response.data.html_url}`)
} catch (error) {
console.error(`Error creating pull request: ${error}`)
}
}
async function createCosmostationBranch(tokens: CosmostationToken[]) {
/**
* Check if cosmostation repo exists on your local and remove if so
*/
if (fs.existsSync(COSMOSTATION_REPO_PATH)) {
execSync(`rm -rf ${COSMOSTATION_REPO_PATH}`)
}
execSync(
`git clone https://github.com/shane-moore/chainlist.git ${COSMOSTATION_REPO_PATH}`,
)
process.chdir(COSMOSTATION_REPO_PATH)
execSync(`git checkout -b ${COSMOSTATION_BRANCH_NAME}`)
console.log('New branch created.')
/** Ensure new metadata are copied over before proceeding */
await fsPromises.writeFile(
'./chain/injective/assets.json',
JSON.stringify(tokens, null, 2),
)
console.log('assets.json updated.')
execSync('git add chain/injective/assets.json')
execSync(`git commit -m "chore: automated update of injective assets.json"`)
execSync(`git push -u origin ${COSMOSTATION_BRANCH_NAME}`)
console.log('Changes pushed to remote.')
}
;(async () => {
try {
const existingCosmostationTokens = await fetchExistingCosmostationTokens()
if (existingCosmostationTokens.length === 0) {
console.log('no assets found in cosmostation assets.json list')
}
const bankTokens = (await fetchSupplyTokenMeta()) as Token[]
const convertedCosmostationTokens = convertToCosmostationTokens(
bankTokens,
existingCosmostationTokens,
)
await createCosmostationBranch(convertedCosmostationTokens)
await createPullRequest(githubToken)
/**
* Check if cosmostation repo exists on your local and remove if so
*/
if (fs.existsSync(COSMOSTATION_REPO_PATH)) {
execSync(`rm -rf ${COSMOSTATION_REPO_PATH}`)
}
} catch (error) {
console.error(`Error: ${error}`)
}
})()