Skip to content

Commit

Permalink
Update connection logic
Browse files Browse the repository at this point in the history
  • Loading branch information
olehmell committed Sep 1, 2023
1 parent 398c488 commit 56b9c49
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 926 deletions.
6 changes: 1 addition & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,11 @@
},
"dependencies": {
"@babel/runtime": "^7.15.3",
"@bifrost-finance/api": "^1.6.1",
"@equilab/api": "^1.12.23",
"@isaacs/ttlcache": "^1.0.3",
"@kodadot1/uniquery": "^0.3.0-rc.0",
"@polkadot/api-base": "^9.11.1",
"@polkadot/apps-config": "0.116.2-64",
"@polkadot/networks": "^7.3.1",
"@polkawallet/bridge": "^0.0.4",
"@subsocial/api": "0.7.9",
"@subsocial/api": "0.8.14",
"axios": "^0.26.0",
"connect-timeout": "^1.9.0",
"cors": "^2.8.5",
Expand Down
126 changes: 46 additions & 80 deletions src/connections/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { Apis, GetApiFn } from './networks/types'
import { ApiPromise, WsProvider, HttpProvider } from '@polkadot/api'
import { newLogger } from '@subsocial/utils'
import rpc from '@polkadot/types/interfaces/jsonrpc'
import { typesChain, typesBundle } from '@polkadot/apps-config/api'
import { SubsocialApi } from '@subsocial/api'
import { wsReconnectTimeout } from '../constant'
import { updatePropertiesByNetwork } from '../services/properties'
Expand Down Expand Up @@ -45,18 +44,24 @@ type Props = {
}

const defaultGetApi: GetApiFn = ({ provider, types }) =>
new ApiPromise({ provider, types, rpc, typesBundle: typesBundle as any, typesChain })
new ApiPromise({
provider,
types,
rpc,
throwOnConnect: false,
throwOnUnknown: false
})

const connect = async ({
node,
wsNode,
getApi,
types,
network,
node,
getApi,
types,
network,
mixedApis,
isMixedConnection,
mixedApis,
wsNode,
wsApis
}: Props) => {
}: Props) => {
if (!node) return

const nodeName = `${network} node at ${node}`
Expand All @@ -65,37 +70,32 @@ const connect = async ({

const isHttps = node.includes('https')

let wsApi = undefined

const provider = isHttps
? new HttpProvider(node, {})
: new WsProvider(node, wsReconnectTimeout, {}, 100 * SEC)

if (isHttps && isMixedConnection) {
const wsProvider = new WsProvider(wsNode, wsReconnectTimeout, {}, 100 * SEC)

wsApi = getApi({ provider: wsProvider, types })
}

const api = getApi({ provider, types })

;(wsApi || api).on('ready', () => {
console.log(`Connected to ${nodeName}`)
updatePropertiesByNetwork(api, network)
api.on('ready', async () => {
log.info(`Connected to ${nodeName}`)
mixedApis[network] = api

await updatePropertiesByNetwork(api, network)
})

try {
const apiReady = await api.isReadyOrError
const wsApiReady = await wsApi?.isReadyOrError
if (isHttps && isMixedConnection) {
const wsProvider = new WsProvider(wsNode, wsReconnectTimeout, {}, 100 * SEC)

mixedApis[network] = apiReady
wsApis[network] = wsApiReady
const wsApi = getApi({ provider: wsProvider, types })

if (validatorsStakingNetworks.includes(network)) {
await getValidatorsData(wsApi, network)
}
} catch {
console.error(`Problem with connection to ${nodeName}`)
wsApi.on('ready', async () => {
log.info(`Connected to ${nodeName}`)
wsApis[network] = wsApi

if (validatorsStakingNetworks.includes(network)) {
await getValidatorsData(wsApi, network)
}
})
}
}

Expand All @@ -109,58 +109,24 @@ export const createConnections = async () => {
const mixedApis: Apis = {} as Apis
const wsApis: Apis = {} as Apis

// For fast connection on localhost
if (process.env.NODE_ENV === 'dev') {
const promises = Object.entries(networks).map(
async ([
network,
{ node, types, getApi = defaultGetApi, disabled, isMixedConnection, wsNode }
]) => {
if (node) {
try {
!disabled &&
(await connect({
network,
node,
wsNode,
types,
isMixedConnection,
mixedApis,
wsApis,
getApi
}))
} catch (err) {
log.error('Unexpected error:', err)
}
}
}
)
for (const value of Object.entries(networks)) {
const [
network,
{ node, types, getApi = defaultGetApi, isMixedConnection, wsNode, disabled }
] = value

await Promise.all(promises)
} else {
for (const value of Object.entries(networks)) {
const [
if (node) {
!disabled &&
connect({
network,
{ node, types, getApi = defaultGetApi, isMixedConnection, wsNode, disabled }
] = value

if (node) {
try {
!disabled &&
(await connect({
network,
node,
types,
wsNode,
mixedApis,
wsApis,
isMixedConnection,
getApi
}))
} catch (err) {
log.error('Unexpected error:', err)
}
}
node,
types,
wsNode,
mixedApis,
wsApis,
isMixedConnection,
getApi
}).catch(log.error)
}
}

Expand Down
8 changes: 3 additions & 5 deletions src/connections/networks/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Networks } from './types'
import { getBitfrostApi, resolveOnfinalityUrl } from './utils'
import { resolveOnfinalityUrl } from './utils'
import { RelayChain } from '../../services/crowdloan/types'

export const subsocial = {
Expand Down Expand Up @@ -100,7 +100,7 @@ export const kusamaParachains: Networks = {
},
heiko: {
name: 'Parallel Heiko',
node: 'wss://heiko-rpc.parallel.fi',
...resolveOnfinalityUrl('parallel-heiko'),
icon: 'parallel.svg',
nativeToken: 'HKO',
paraId: 2085,
Expand All @@ -127,7 +127,6 @@ export const kusamaParachains: Networks = {
...resolveOnfinalityUrl('bifrost-parachain'),
icon: 'bifrost.svg',
paraId: 2001,
getApi: getBitfrostApi,
isTransferable: true,
tokenTransferMethod: 'tokens.transfer(recipient,id,amount)'
},
Expand Down Expand Up @@ -233,7 +232,7 @@ export const kusamaParachains: Networks = {
},
shadow: {
name: 'Crust Shadow',
node: 'wss://rpc-shadow.crust.network',
node: '',
icon: 'shadow.svg',
nativeToken: 'CSM',
paraId: 2012,
Expand Down Expand Up @@ -419,7 +418,6 @@ export const polkadotParachains: Networks = {
...resolveOnfinalityUrl('bifrost-polkadot'),
icon: 'bifrost.svg',
paraId: 2030,
getApi: getBitfrostApi,
isTransferable: true,
tokenTransferMethod: 'tokens.transfer(recipient,id,amount)'
},
Expand Down
4 changes: 0 additions & 4 deletions src/connections/networks/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { ApiPromise, GetApiFn } from './types'
import { options } from '@bifrost-finance/api'
import { ONFINALITY_API_KEY } from '../../constant'

export const getBitfrostApi: GetApiFn = ({ provider }) => new ApiPromise(options({ provider }))

export const resolveOnfinalityUrl = (chainName: string) => {
return {
node: `wss://${chainName}.api.onfinality.io/ws?apikey=${ONFINALITY_API_KEY}`,
Expand Down
5 changes: 5 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,8 @@ export const startHttpServer = (apis: Connections) => {
log.info(`HTTP server started on port ${port}`)
})
}

process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
// Application specific logging, throwing an error, or other logic here
});
Loading

0 comments on commit 56b9c49

Please sign in to comment.