Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix internal assets #1606

Merged
merged 2 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions centrifuge-app/src/pages/IssuerPool/Assets/CreateLoan.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ function IssuerCreateLoan() {

const tx: Transaction = {
id: txId,
title: 'Create document',
title: 'Create asset',
status: 'creating',
args: [],
}
Expand Down Expand Up @@ -327,7 +327,7 @@ function IssuerCreateLoan() {
doTransaction([submittable], undefined, txId)
} catch (e) {
console.error(e)
updateTransaction(txId, { status: 'failed', failedReason: 'Failed to create document NFT' })
updateTransaction(txId, { status: 'failed', failedReason: 'Failed to create asset' })
}

setSubmitting(false)
Expand Down
16 changes: 8 additions & 8 deletions centrifuge-app/src/pages/IssuerPool/Assets/PricingInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ export function PricingInput({ poolId }: { poolId: string }) {
/>
)}
</Field>
<FieldWithErrorMessage
as={NumberInput}
label={<Tooltips type="maxPriceVariation" variant="secondary" label="Max price variation*" />}
placeholder={0}
rightElement="%"
name="pricing.maxPriceVariation"
validate={validate.maxPriceVariation}
/>
</>
)}

Expand Down Expand Up @@ -106,14 +114,6 @@ export function PricingInput({ poolId }: { poolId: string }) {
// Max 5 years from now
max={new Date(Date.now() + 5 * 365 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10)}
/>
<FieldWithErrorMessage
as={NumberInput}
label={<Tooltips type="maxPriceVariation" variant="secondary" label="Max price variation*" />}
placeholder={0}
rightElement="%"
name="pricing.maxPriceVariation"
validate={validate.maxPriceVariation}
/>

{(values.pricing.valuationMethod === 'discountedCashFlow' ||
values.pricing.valuationMethod === 'outstandingDebt') && (
Expand Down
26 changes: 20 additions & 6 deletions centrifuge-app/src/pages/Loan/FinancingRepayment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,29 @@ import { LabelValueStack } from '../../components/LabelValueStack'
export const FinancingRepayment: React.FC<{
drawDownDate: string | null
closingDate: string | null
totalFinanced: string
totalRepaid: string
}> = ({ drawDownDate, closingDate, totalFinanced, totalRepaid }) => {
outstandingPrincipal: string
outstandingInterest: string
repaidPrincipal: string
repaidInterest: string
repaidUnscheduled: string | null
}> = ({
drawDownDate,
closingDate,
outstandingPrincipal,
outstandingInterest,
repaidPrincipal,
repaidInterest,
repaidUnscheduled,
}) => {
return (
<>
{!!drawDownDate && <LabelValueStack label="1st drawdown date" value={drawDownDate} />}
{!!closingDate && <LabelValueStack label="Date Closed" value={closingDate} />}
<LabelValueStack label="Total financed" value={totalFinanced} />
<LabelValueStack label="Total repaid" value={totalRepaid} />
{!!closingDate && <LabelValueStack label="Date closed" value={closingDate} />}
<LabelValueStack label="Principal outstanding" value={outstandingPrincipal} />
<LabelValueStack label="Interest outstanding" value={outstandingInterest} />
<LabelValueStack label="Principal paid" value={repaidPrincipal} />
<LabelValueStack label="Interest paid" value={repaidInterest} />
{!!repaidUnscheduled && <LabelValueStack label="Unscheduled repayments" value={repaidUnscheduled} />}
</>
)
}
7 changes: 7 additions & 0 deletions centrifuge-app/src/pages/Loan/TransactionTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ export const TransactionTable = ({ transactions, currency, loanType, decimals, p
? new CurrencyBalance(trx.quantity, 18)
.toDecimal()
.mul((pricing as ExternalPricingInfo).notional.toDecimal())
: trx.amount
? trx.amount.toDecimal()
: Dec(0)
)
}
Expand All @@ -64,6 +66,8 @@ export const TransactionTable = ({ transactions, currency, loanType, decimals, p
? new CurrencyBalance(trx.quantity, 18)
.toDecimal()
.mul((pricing as ExternalPricingInfo).notional.toDecimal())
: trx.amount
? trx.amount.toDecimal()
: Dec(0)
)
}
Expand All @@ -82,6 +86,9 @@ export const TransactionTable = ({ transactions, currency, loanType, decimals, p
if (loanType === 'external' && type === 'BORROWED') return 'Purchase'
if (loanType === 'external' && type === 'REPAID') return 'Sale'

if (loanType === 'internal' && type === 'BORROWED') return 'Financed'
if (loanType === 'internal' && type === 'REPAID') return 'Repaid'

return `${type[0]}${type.slice(1).toLowerCase()}`
}

Expand Down
38 changes: 27 additions & 11 deletions centrifuge-app/src/pages/Loan/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Loan as LoanType, Pool, PricingInfo, TinlakeLoan } from '@centrifuge/centrifuge-js'
import { CurrencyBalance, Loan as LoanType, Pool, PricingInfo, TinlakeLoan } from '@centrifuge/centrifuge-js'
import {
AnchorButton,
Box,
Expand Down Expand Up @@ -181,14 +181,17 @@ const Loan: React.FC<{ setShowOraclePricing?: () => void }> = ({ setShowOraclePr
},
]
: []),
...('presentValue' in loan
? [
{
label: 'Current value',
value: `${formatBalance(loan.presentValue, pool.currency.symbol, 2, 2)}`,
},
]
: []),
...[
{
label: 'Current value',
value: `${formatBalance(
'presentValue' in loan ? loan.presentValue : new CurrencyBalance(0, pool.currency.decimals),
pool.currency.symbol,
2,
2
)}`,
},
],
]}
/>

Expand All @@ -203,8 +206,21 @@ const Loan: React.FC<{ setShowOraclePricing?: () => void }> = ({ setShowOraclePr
<FinancingRepayment
drawDownDate={'originationDate' in loan ? formatDate(loan.originationDate) : null}
closingDate={null}
totalFinanced={formatBalance('totalBorrowed' in loan ? loan.totalBorrowed : 0, pool.currency)}
totalRepaid={formatBalance('totalBorrowed' in loan ? loan.totalRepaid : 0, pool.currency)}
outstandingPrincipal={formatBalance(
'outstandingPrincipal' in loan ? loan.outstandingPrincipal : 0,
pool.currency
)}
outstandingInterest={formatBalance(
'outstandingInterest' in loan ? loan.outstandingInterest : 0,
pool.currency
)}
repaidPrincipal={formatBalance('repaid' in loan ? loan.repaid.principal : 0, pool.currency)}
repaidInterest={formatBalance('repaid' in loan ? loan.repaid.interest : 0, pool.currency)}
repaidUnscheduled={
'repaid' in loan && !loan.repaid.unscheduled.isZero()
? formatBalance(loan.repaid.unscheduled, pool.currency)
: null
}
/>
)}
</Shelf>
Expand Down
101 changes: 7 additions & 94 deletions centrifuge-app/src/utils/usePools.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
import Centrifuge, {
BorrowerTransaction,
CurrencyBalance,
ExternalLoan,
ExternalPricingInfo,
Pool,
PoolMetadata,
} from '@centrifuge/centrifuge-js'
import Centrifuge, { ActiveLoan, BorrowerTransaction, Pool, PoolMetadata } from '@centrifuge/centrifuge-js'
import { useCentrifuge, useCentrifugeQuery, useWallet } from '@centrifuge/centrifuge-react'
import BN from 'bn.js'
import Decimal from 'decimal.js-light'
import { useEffect } from 'react'
import { useQuery } from 'react-query'
import { combineLatest, map, Observable } from 'rxjs'
import { Dec } from './Decimal'
import { getLatestPrice } from './getLatestPrice'
import { TinlakePool, useTinlakePools } from './tinlake/useTinlakePools'
import { useLoan, useLoans } from './useLoans'
import { useMetadata } from './useMetadata'
Expand Down Expand Up @@ -99,94 +90,16 @@ export function useBorrowerTransactions(poolId: string, from?: Date, to?: Date)
}

export function useAverageAmount(poolId: string) {
const borrowerTransactions = useBorrowerTransactions(poolId)
const pool = usePool(poolId)
const loans = useLoans(poolId)

if (
!loans?.length ||
!pool ||
!borrowerTransactions ||
!('valuationMethod' in loans[0].pricing && loans[0].pricing.valuationMethod === 'oracle')
)
return new BN(0)

const poolsByLoanId =
borrowerTransactions.reduce((pools, trx) => {
const [, assetId] = trx.loanId.split('-')

const loan = loans.find((loan) => loan.id === assetId) as ExternalLoan
const borrowerAssetTransactions = borrowerTransactions?.filter(
(borrowerTransaction) => borrowerTransaction.loanId === `${loan.poolId}-${loan.id}`
)

if (pools[assetId]) {
pools[assetId] = [
...pools[assetId],
{
...trx,
oracleValue: getLatestPrice(loan.pricing.oracle.value, borrowerAssetTransactions, pool.currency.decimals),
},
]
} else {
pools[assetId] = [
{
...trx,
oracleValue: getLatestPrice(loan.pricing.oracle.value, borrowerAssetTransactions, pool.currency.decimals),
},
]
}
if (!loans?.length || !pool) return new BN(0)

return pools
}, {} as Record<string, Array<BorrowerTransaction & { oracleValue: CurrencyBalance | null }>>) || {}

const currentFaces = Object.entries(poolsByLoanId).reduce((sum, [assetId, transactions]) => {
const pricing = loans.find((loan) => loan.id === assetId)?.pricing as ExternalPricingInfo

const currentFace =
transactions.reduce((sum, trx) => {
if (trx.type === 'BORROWED') {
sum = sum.add(
trx.quantity
? new CurrencyBalance(trx.quantity, 18)
.toDecimal()
.mul((pricing as ExternalPricingInfo).notional.toDecimal())
: Dec(0)
)
}
if (trx.type === 'REPAID') {
sum = sum.sub(
trx.quantity
? new CurrencyBalance(trx.quantity, 18)
.toDecimal()
.mul((pricing as ExternalPricingInfo).notional.toDecimal())
: Dec(0)
)
}
return sum
}, Dec(0)) || Dec(0)

sum = { ...sum, [assetId]: currentFace }

return sum
}, {} as Record<string, Decimal>)

const currentValues = Object.entries(currentFaces).reduce((values, [assetId, currentFace]) => {
const loan = loans.find((loan) => loan.id === assetId) as ExternalLoan
const borrowerAssetTransactions = borrowerTransactions?.filter(
(borrowerTransaction) => borrowerTransaction.loanId === `${loan.poolId}-${loan.id}`
)

const latestPrice = getLatestPrice(loan.pricing.oracle.value, borrowerAssetTransactions, pool.currency.decimals)
?.toDecimal()
.div(100)

values[assetId] = currentFace.mul(latestPrice || Dec(1))
return values
}, {} as Record<string, Decimal>)

return Object.values(currentValues)
.reduce((sum, value) => sum.add(value), Dec(0))
return loans
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh wow, much cleaner!

.reduce((sum, loan) => {
if (loan.status !== 'Active') return sum
return sum.add((loan as ActiveLoan).presentValue.toDecimal())
}, Dec(0))
.div(loans.filter((loan) => loan.status === 'Active').length)
}

Expand Down