Skip to content

Commit

Permalink
fix: asset metadata updates (#248)
Browse files Browse the repository at this point in the history
  • Loading branch information
filo87 authored Aug 29, 2024
1 parent d57d2bf commit d310b6a
Show file tree
Hide file tree
Showing 9 changed files with 76 additions and 9 deletions.
7 changes: 6 additions & 1 deletion chains-cfg/_root.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -174,4 +174,9 @@ dataSources:
kind: substrate/EventHandler
filter:
module: oraclePriceFeed
method: Fed
method: Fed
- handler: handleAssetMetadataSet
kind: substrate/EventHandler
filter:
module: uniques
method: MetadataSet
4 changes: 2 additions & 2 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -449,8 +449,8 @@ type Asset @entity {
type: AssetType!
valuationMethod: AssetValuationMethod!

collateralNftClassId: BigInt
collateralNftItemId: BigInt
collateralNftClassId: BigInt @index
collateralNftItemId: BigInt @index

metadata: String
name: String
Expand Down
4 changes: 3 additions & 1 deletion src/helpers/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//find out types: const a = createType(api.registry, '[u8;32]', 18)
import { AugmentedCall, AugmentedRpc, PromiseRpcResult } from '@polkadot/api/types'
import { Enum, Null, Struct, u128, u32, u64, U8aFixed, Option, Vec, Bytes, Result } from '@polkadot/types'
import { Enum, Null, Struct, u128, u32, u64, U8aFixed, Option, Vec, Bytes, Result, bool } from '@polkadot/types'
import { AccountId32, Perquintill, Balance } from '@polkadot/types/interfaces'
import { ITuple, Observable } from '@polkadot/types/types'

Expand Down Expand Up @@ -480,6 +480,8 @@ export type TokensEndowedDepositedWithdrawnEvent = ITuple<
[currencyId: TokensCurrencyId, who: AccountId32, amount: u128]
>

export type UniquesMetadataSetEvent = ITuple<[collection: u64, item: u128, data: Bytes, isFrozen: bool]>

export type PoolFeesProposedEvent = ITuple<[poolId: u64, feeId: u64, bucket: PoolFeeBucket, fee: PoolFeeInfo]>
export type PoolFeesAddedEvent = ITuple<[poolId: u64, bucket: PoolFeeBucket, feeId: u64, fee: PoolFeeInfo]>
export type PoolFeesRemovedEvent = ITuple<[poolId: u64, bucket: PoolFeeBucket, feeId: u64]>
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ export * from './mappings/handlers/evmHandlers'
export * from './mappings/handlers/ethHandlers'
export * from './mappings/handlers/poolFeesHandlers'
export * from './mappings/handlers/oracleHandlers'
export * from './mappings/handlers/uniquesHandlers'
11 changes: 9 additions & 2 deletions src/mappings/handlers/poolsHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { AssetTransactionData, AssetTransactionService } from '../services/asset
import { substrateStateSnapshotter } from '../../helpers/stateSnapshot'
import { Pool, PoolSnapshot } from '../../types'
import { InvestorPositionService } from '../services/investorPositionService'
import { PoolFeeService } from '../services/poolFeeService'

export const handlePoolCreated = errorHandler(_handlePoolCreated)
async function _handlePoolCreated(event: SubstrateEvent<PoolCreatedEvent>): Promise<void> {
Expand Down Expand Up @@ -41,10 +42,16 @@ async function _handlePoolCreated(event: SubstrateEvent<PoolCreatedEvent>): Prom
event.block.block.header.number.toNumber()
)
await pool.initData()
await pool.initIpfsMetadata().catch((err) => {
const poolFeesMetadata = await pool.initIpfsMetadata().catch<ReturnType<typeof pool.initIpfsMetadata>>((err) => {
logger.error(`IPFS Request failed ${err}`)
return Promise.resolve()
return Promise.resolve([])
})

for (const { id: feeId, name } of poolFeesMetadata) {
const poolFee = await PoolFeeService.getById(pool.id, feeId.toString(10))
await poolFee.setName(name)
await poolFee.save()
}
await pool.save()

// Initialise the tranches
Expand Down
27 changes: 27 additions & 0 deletions src/mappings/handlers/uniquesHandlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { SubstrateEvent } from '@subql/types'
import { errorHandler } from '../../helpers/errorHandler'
import { UniquesMetadataSetEvent } from '../../helpers/types'
import { AssetService } from '../services/assetService'

export const handleAssetMetadataSet = errorHandler(_handleAssetMetadataSet)
async function _handleAssetMetadataSet(event: SubstrateEvent<UniquesMetadataSetEvent>) {
const [_collectionId, _itemId, _metadata] = event.event.data

const collectionId = _collectionId.toString(10)
const itemId = _itemId.toString(10)
const metadata = _metadata.toUtf8()

logger.info(
`uniques.MetadataSet event fired for ${collectionId}:${itemId}` +
`at block ${event.block.block.header.number.toNumber()}`
)

const asset = await AssetService.getByNftId(collectionId, itemId)
if (!asset) return logger.warn('Corresponding asset not found. Maybe not yet initialised? Skipping...')

logger.info(`Found corresponding asset ${asset.id}`)

await asset.setMetadata(metadata)
await asset.updateIpfsAssetName()
await asset.save()
}
14 changes: 14 additions & 0 deletions src/mappings/services/assetService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,16 @@ export class AssetService extends Asset {
return asset
}

static async getByNftId(collectionId: string, itemId: string) {
const asset = (
await AssetService.getByFields([
['collateralNftClassId', '=', collectionId],
['collateralNftItemId', '=', itemId],
])
).pop() as AssetService
return asset
}

public borrow(amount: bigint) {
logger.info(`Increasing borrowings for asset ${this.id} by ${amount}`)
this.borrowedAmountByPeriod += amount
Expand Down Expand Up @@ -176,6 +186,10 @@ export class AssetService extends Asset {
return this
}

public setMetadata(metadata: string) {
this.metadata = metadata
}

static extractPrincipalAmount(principalObject: LoanPricingAmount) {
let principal: bigint
switch (principalObject.type) {
Expand Down
1 change: 1 addition & 0 deletions src/mappings/services/poolFeeService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ export class PoolFeeService extends PoolFee {
}

public setName(name: string) {
logger.info(`Setting name for fee ${this.id} to: ${name}`)
this.name = name
}

Expand Down
16 changes: 13 additions & 3 deletions src/mappings/services/poolService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export class PoolService extends Pool {
this.metadata = metadata
}

public async initIpfsMetadata() {
public async initIpfsMetadata(): Promise<PoolIpfsMetadata['pool']['poolFees']> {
if (!this.metadata) {
logger.warn('No IPFS metadata')
return
Expand All @@ -157,16 +157,26 @@ export class PoolService extends Pool {
this.assetClass = metadata.pool.asset.class
this.assetSubclass = metadata.pool.asset.subClass
this.icon = metadata.pool.icon.uri
return metadata.pool.poolFees ?? []
}

public async getIpfsPoolFeeName(poolFeeId: string): Promise<string> {
public async getIpfsPoolFeeMetadata(): Promise<PoolIpfsMetadata['pool']['poolFees']> {
if (!this.metadata) return logger.warn('No IPFS metadata')
const metadata = await readIpfs<PoolIpfsMetadata>(this.metadata.match(cid)[0])
if (!metadata.pool.poolFees) {
return null
}
return metadata.pool.poolFees
}

public async getIpfsPoolFeeName(poolFeeId: string): Promise<string> {
if (!this.metadata) return logger.warn('No IPFS metadata')
const poolFeeMetadata = await this.getIpfsPoolFeeMetadata()
if (!poolFeeMetadata) {
logger.warn('Missing poolFee object in pool metadata!')
return null
}
return metadata.pool.poolFees.find((elem) => elem.id.toString(10) === poolFeeId)?.name ?? null
return poolFeeMetadata.find((elem) => elem.id.toString(10) === poolFeeId)?.name ?? null
}

static async getById(poolId: string) {
Expand Down

0 comments on commit d310b6a

Please sign in to comment.