Skip to content

Commit

Permalink
feat: add missing quantity settlement price for handleLoanDebtTransfe…
Browse files Browse the repository at this point in the history
…rred1024 (#192)

* test: fix by adding chainspec to runtime mock

* chore: upgrade deps

* feat: add missing quantity & settlement price for handleLoanDebtTransferred1024
Fixes #178

* fix: add missing quantity & settlement price for `handleLoanDebtTransferred1024`
Fixes #178

* Update src/mappings/handlers/loansHandlers.ts

* Update src/mappings/handlers/loansHandlers.ts

* Update src/mappings/handlers/loansHandlers.ts

---------

Co-authored-by: Jeroen <[email protected]>
  • Loading branch information
filo87 and hieronx committed Jun 5, 2024
1 parent e99d281 commit 6a7b554
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 81 deletions.
1 change: 0 additions & 1 deletion jest/globals.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,4 @@ global['logger'] = {
}

global['api'] = { query: {}, rpc: {} }

global['chainId'] = '0xb3db41421702df9a7fcac62b53ffeac85f7853cc4e689e0b93aeb3db18c09d82'
11 changes: 7 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@
"@jest/globals": "^29.2.0",
"@polkadot/api": "^10",
"@polkadot/typegen": "^10",
"@subql/cli": "^4.11.0",
"@subql/testing": "^2.1.1",
"@subql/types": "^3.5.0",
"@subql/types-core": "^0.6.0",
"@subql/cli": "latest",
"@subql/testing": "latest",
"@subql/types": "latest",
"@subql/types-core": "latest",
"@types/jest": "^29.1.2",
"@types/node-fetch": "^2.6.11",
"@typescript-eslint/eslint-plugin": "^6.15.0",
Expand All @@ -63,5 +63,8 @@
},
"exports": {
"chaintypes": "./src/chaintypes.ts"
},
"resolutions": {
"ipfs-unixfs": "6.0.6"
}
}
2 changes: 2 additions & 0 deletions src/helpers/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,3 +482,5 @@ export type ExtendedCall = typeof api.call & {
listFees: AugmentedCall<'promise', (poolId: string) => Observable<Option<PoolFeesList>>>
}
}

export type ApiQueryLoansActiveLoans = Vec<ITuple<[u64, LoanInfoActive]>>
9 changes: 8 additions & 1 deletion src/mappings/handlers/loansHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { AssetTransactionData, AssetTransactionService } from '../services/asset
import { AccountService } from '../services/accountService'
import { EpochService } from '../services/epochService'
import { AssetType, AssetValuationMethod } from '../../types'
import { bnToBn, nToBigInt } from '@polkadot/util'
import { WAD } from '../../config'

export const handleLoanCreated = errorHandler(_handleLoanCreated)
async function _handleLoanCreated(event: SubstrateEvent<LoanCreatedEvent>) {
Expand Down Expand Up @@ -406,8 +408,8 @@ async function _handleLoanDebtTransferred1024(event: SubstrateEvent<LoanDebtTran
if (fromAsset.isNonCash() && toAsset.isOffchainCash()) {
//Track repayment
await fromAsset.activate()
await fromAsset.updateExternalAssetPricingFromState()
await fromAsset.repay(amount)
await fromAsset.updateIpfsAssetName()
await fromAsset.save()

await pool.increaseRepayments1024(amount)
Expand All @@ -423,13 +425,16 @@ async function _handleLoanDebtTransferred1024(event: SubstrateEvent<LoanDebtTran
amount: amount,
fromAssetId: fromLoanId.toString(10),
toAssetId: toLoanId.toString(10),
settlementPrice: fromAsset.currentPrice,
quantity: nToBigInt(bnToBn(amount).mul(WAD).div(bnToBn(fromAsset.currentPrice))),
})
await principalRepayment.save()
}

if (fromAsset.isOffchainCash() && toAsset.isNonCash()) {
//Track borrowed / financed amount
await toAsset.activate()
await toAsset.updateExternalAssetPricingFromState()
await toAsset.borrow(amount)
await toAsset.updateIpfsAssetName()
await toAsset.save()
Expand All @@ -448,6 +453,8 @@ async function _handleLoanDebtTransferred1024(event: SubstrateEvent<LoanDebtTran
principalAmount: amount,
fromAssetId: fromLoanId.toString(10),
toAssetId: toLoanId.toString(10),
settlementPrice: toAsset.currentPrice,
quantity: nToBigInt(bnToBn(amount).mul(WAD).div(bnToBn(toAsset.currentPrice))) ,
})
await purchaseTransaction.save()
}
Expand Down
18 changes: 17 additions & 1 deletion src/mappings/services/assetService.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Option } from '@polkadot/types'
import { bnToBn, nToBigInt } from '@polkadot/util'
import { WAD } from '../../config'
import { LoanPricingAmount, NftItemMetadata } from '../../helpers/types'
import { ApiQueryLoansActiveLoans, LoanPricingAmount, NftItemMetadata } from '../../helpers/types'
import { Asset, AssetType, AssetValuationMethod, AssetStatus } from '../../types'
import { ActiveLoanData } from './poolService'
import { cid, readIpfs } from '../../helpers/ipfsFetch'
Expand Down Expand Up @@ -191,6 +191,22 @@ export class AssetService extends Asset {
public isNonCash() {
return this.type === AssetType.Other
}

public async updateExternalAssetPricingFromState() {
logger.info(`Executing state call loans.activeLoans to update asset ${this.id} pricing information`)
const loansCall = await api.query.loans.activeLoans<ApiQueryLoansActiveLoans>(this.poolId)
const assetTuple = loansCall.find((tuple) => tuple[0].toString(10) === this.id.split('-')[1])
if (!assetTuple) throw new Error(`Asset ${this.id} not found in pool active loans!`)
const loanData = assetTuple[1]
if (loanData.pricing.isInternal) throw new Error(`Asset ${this.id} is not of type External!`)
const { outstandingQuantity, latestSettlementPrice } = loanData.pricing.asExternal
this.outstandingQuantity = outstandingQuantity.toBigInt()
this.currentPrice = latestSettlementPrice.toBigInt()
logger.info(
`Updated outstandingQuantity: ${outstandingQuantity.toString(10)} ` +
`currentPrice: ${latestSettlementPrice.toString(10)} for asset ${this.id}`
)
}
}

interface AssetSpecs {
Expand Down
3 changes: 3 additions & 0 deletions src/mappings/services/trancheService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ api.query['ormlTokens'] = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any

// eslint-disable-next-line @typescript-eslint/no-explicit-any
api['runtimeVersion'] = { specVersion: { toNumber: ()=> 1029 } } as any

api.rpc['pools'] = {
trancheTokenPrices: jest.fn(() => [
{ toBigInt: () => BigInt('2000000000000000000') },
Expand Down
Loading

0 comments on commit 6a7b554

Please sign in to comment.