Skip to content

Commit

Permalink
Fix centrifuge balances
Browse files Browse the repository at this point in the history
  • Loading branch information
samchuk-vlad committed Jan 11, 2024
1 parent f4d49bb commit fa60108
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 19 deletions.
3 changes: 2 additions & 1 deletion src/connections/networks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,8 @@ export const polkadotParachains: Networks = {
centrifuge: {
name: 'Centrifuge',
icon: 'centrifuge.png',
...resolveOnfinalityUrl('centrifuge-parachain'),
// ...resolveOnfinalityUrl('centrifuge-parachain'),
node: 'wss://centrifuge-rpc.dwellir.com',
paraId: 2031,
vestingMethod: 'vesting.vest',
isTransferable: true,
Expand Down
48 changes: 35 additions & 13 deletions src/services/assetRegistry/common.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,54 @@
import { ApiPromise } from '@polkadot/api'
import { newLogger } from '@subsocial/utils'
import { parseStringValue } from '../utils'

const log = newLogger('AssetRegistry')

export const commonAssetRegistries = {
'assets.metadata': generateCommonAssetRegistry([ 'assets', 'metadata' ]),
'assetRegistry.metadataMap': generateCommonAssetRegistry([ 'assetRegistry', 'assetMetadataMap' ]),
'ormlAssetRegistry.metadata': generateCommonAssetRegistry([ 'ormlAssetRegistry', 'metadata' ]),
'currencies.listenAssetsInfo': generateCommonAssetRegistry([ 'currencies', 'listenAssetsInfo' ], (data) => data.metadata),
'assetRegistry.metadata': generateCommonAssetRegistry([ 'assetRegistry', 'metadata' ])
'assets.metadata': generateCommonAssetRegistry(['assets', 'metadata']),
'assetRegistry.metadataMap': generateCommonAssetRegistry(['assetRegistry', 'assetMetadataMap']),
'ormlAssetRegistry.metadata': generateCommonAssetRegistry(['ormlAssetRegistry', 'metadata']),
'currencies.listenAssetsInfo': generateCommonAssetRegistry(
['currencies', 'listenAssetsInfo'],
(data) => data.metadata
),
'assetRegistry.metadata': generateCommonAssetRegistry(['assetRegistry', 'metadata'])
}

function defaultCurrencyDataGetter (data: any) {
function defaultCurrencyDataGetter(data: any) {
return { decimals: data.decimals as number, symbol: data.symbol as string }
}
export default function generateCommonAssetRegistry (
export default function generateCommonAssetRegistry(
getterMethod: [string, string],
currencyDataGetter = defaultCurrencyDataGetter
) {
return async (api: ApiPromise): Promise<Record<string, any>> => {
try {
const [ palletName, storageName ] = getterMethod
const [palletName, storageName] = getterMethod
const assetsRegistryFromStorage = await api.query[palletName][storageName].entries()
const assetRegistry = {}

assetsRegistryFromStorage.forEach(assetsRegistry => {
const [ currency, currencyData ] = assetsRegistry
assetsRegistryFromStorage.forEach((assetsRegistry) => {
const [currency, currencyData] = assetsRegistry
const { decimals, symbol } = currencyDataGetter(currencyData.toPrimitive())

let currencyHuman = currency.toHuman()[0]
if (typeof currencyHuman === 'string') {
currencyHuman = currencyHuman.replace(/,/g, '')
currencyHuman = parseStringValue(currencyHuman)
}

if (typeof currencyHuman === 'object') {
const currencyEntries = Object.entries(currencyHuman)

const [key, value] = currencyEntries[0]

const parsedValue = Array.isArray(value)
? value.map((item) => parseStringValue(item.toString()))
: parseStringValue(value.toString())

currencyHuman = {
[key]: parsedValue
}
}
assetRegistry[symbol] = {
currency: currencyHuman,
Expand All @@ -37,8 +58,9 @@ export default function generateCommonAssetRegistry (
})

return assetRegistry
} catch {
} catch (e) {
log.warn(`Failed to get assets registry from storage`, e)
return {}
}
}
}
}
15 changes: 12 additions & 3 deletions src/services/balances/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import { getGenshiroTokens } from './genshiro'
import { getOrUpdatePropertiesByNetwork } from '../properties'
import { asTypesGenerator } from '../../utils'
import { bnMax } from '@polkadot/util'
import { newLogger } from '@subsocial/utils';

const log = newLogger('Balances')

export type TokenBalances = Record<string, any>

Expand All @@ -14,7 +17,7 @@ const getNativeTokenBalance = async (api: ApiPromise, account: string) => {

const locks = await api.query.balances.locks(account)

const lockedBalance = locks.length && bnMax(...(locks.map(({ amount }) => amount)))
const lockedBalance = locks.length && bnMax(...locks.map(({ amount }) => amount))

const totalBalance = reserved ? free.add(reserved) || 0 : free

Expand All @@ -26,7 +29,11 @@ const getNativeTokenBalance = async (api: ApiPromise, account: string) => {
frozenBalance: frozen?.toString(),
freeBalance: freeBalance?.gt(new BN(0)) ? freeBalance?.toString() : '0',
lockedBalance: lockedBalance?.toString(),
locks: locks.map(({ id, amount, reasons }) => ({ id: id.toHuman(), amount: amount.toString(), reasons}))
locks: locks.map(({ id, amount, reasons }) => ({
id: id.toHuman(),
amount: amount.toString(),
reasons
}))
}
}

Expand Down Expand Up @@ -121,6 +128,7 @@ const getOrmlTokens: GetBalancesType = async (api, network, account, tokens) =>

const balanceGetter =
customOrmlTokenGetter[ormlTokenGetterNetworkMapper[network] ?? ''] ?? defaultOrmlTokenGetter

const balancePromise = tokens.map(async (token) => {
try {
let balances = {} as unknown as Balances
Expand All @@ -136,8 +144,9 @@ const getOrmlTokens: GetBalancesType = async (api, network, account, tokens) =>
tokenBalances[isObject ? token.symbol : token] = {
...balances
}
} catch {
} catch (e) {
// ok
log.warn(`Failed to get balance for ${token}`, e)
}
})

Expand Down
2 changes: 0 additions & 2 deletions src/services/prices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ export const getPrices = async (ids: string) => {
const forceUpdate = needUpdate && (await needUpdate())
const cacheData = await pricesCache.get(cacheKey)

console.log('Is Empty cache data: ', !cacheData?.values || !cacheData?.values.length)

if (!cacheData?.values || !cacheData?.values.length) {
await fetchPrices(ids)
}
Expand Down

0 comments on commit fa60108

Please sign in to comment.