-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: the calculation of the security deposit amount (#436)
* fetch currencies from blockchain instead of using harcoded metadata * handle undefined blockchain data for /gas * Adjust GetToken and Routing for GET PEN * implement useAssetRegistryMetadata hook * update pendulum color palette * fix get pen button color and /gas get token title * refactor usePriceFetcher * add GLMR token icon * implement PEN styles for Badges * implement styles for GET PEN button * fix style of GET PEN submit button * remove node polyfills for stellar-sdk as stellar-sdk started throwing errors about doubles polyfills definitions * refactor useBalances to use AssetRegistry instead of Vaults * fix types * Update StateUpdater Preact type to newest requirements * update to typescript 5 and update preact * update spacewalk animation * handle 'Native' string input in usePriceFetcher * change calculation of griefingCollateral in FeeBox (Spacewalk) * improve GriefingCollateral calculation checks * extract griefingCollateral calculations to helpers.ts * implement basic tests for calculateGriefingCollateral * Refactor price fetcher * Fix type error * improve readability of useFeePallet, improve calculateGriefingCollateral(and tests) * fix display of dashboard decimals * fix isNativeToken in useBalances * update error handling for buyout * fix comparision in usePriceFetcher hook * improve handleBuyoutError in useBuyout hook * improve get pen/ampe success dialog * fix types in usePriceFetcher * fix types * Fix calculation of griefing fee * Refactor calculation into hook * Limit shown decimals * Move calculation out of FeeBox * Remove test * Fix error for currency code less than 4 * Split `useAccountBalance` into total and transferable * Fix wrong condition in `useBalances` * Simplify condition * Use `_.padEnd()` * Move `useCalculateGriefingCollateral` to extra file * implement tests for useCalculateGriefingCollateral hook * Improve useCalculateGriefingCollateral.test.ts --------- Co-authored-by: Marcel Ebert <[email protected]>
- Loading branch information
1 parent
6d7fe1e
commit 98bc392
Showing
15 changed files
with
263 additions
and
54 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -35,3 +35,4 @@ dist-ssr | |
!.yarn/versions | ||
|
||
vite.config.ts.timestamp-* | ||
coverage/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
95 changes: 95 additions & 0 deletions
95
src/hooks/spacewalk/__tests__/useCalculateGriefingCollateral.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
import { renderHook } from '@testing-library/react-hooks'; | ||
import { waitFor } from '@testing-library/preact'; | ||
import { Asset } from 'stellar-base'; | ||
import Big from 'big.js'; | ||
import { useFeePallet } from '../useFeePallet'; | ||
import { useCalculateGriefingCollateral } from '../useCalculateGriefingCollateral'; | ||
|
||
const STELLAR_ONE_WITH_DECIMALS = 1000000000000; | ||
const VALID_ASSET = new Asset('code', 'GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW'); | ||
// We assume that the price is the same for all assets | ||
const PRICE = 1; | ||
|
||
jest.mock('../../usePriceFetcher', () => ({ | ||
usePriceFetcher: jest.fn().mockReturnValue({ | ||
getTokenPriceForCurrency: jest.fn().mockReturnValue(Promise.resolve(PRICE)), | ||
}), | ||
})); | ||
|
||
jest.mock('../../../NodeInfoProvider', () => ({ | ||
useNodeInfoState: jest.fn().mockReturnValue({ | ||
state: { api: {} }, | ||
}), | ||
})); | ||
|
||
jest.mock('../../../helpers/spacewalk', () => ({ | ||
convertStellarAssetToCurrency: jest.fn().mockImplementation(() => 'convertedCurrency'), | ||
})); | ||
|
||
// useFeePallet mock is implemented in the describe() as we need to spy it during tests | ||
jest.mock('../useFeePallet'); | ||
|
||
describe('useCalculateGriefingCollateral', () => { | ||
const mockGetFees = jest.fn().mockReturnValue({ | ||
griefingCollateralCurrency: 'AUDD', | ||
issueGriefingCollateralFee: 0.05, | ||
}); | ||
|
||
beforeEach(() => { | ||
(useFeePallet as jest.MockedFunction<typeof useFeePallet>).mockReturnValue({ | ||
getFees: mockGetFees, | ||
getTransactionFee: jest.fn(), | ||
}); | ||
|
||
jest.useFakeTimers(); | ||
}); | ||
|
||
it('should return 0 griefing collateral if amount is not valid', async () => { | ||
const { result } = renderHook(() => useCalculateGriefingCollateral(new Big(0), VALID_ASSET)); | ||
|
||
const expectation = () => expect(result.current.eq(new Big(0))).toBeTruthy(); | ||
|
||
expectation(); | ||
await waitFor(expectation); | ||
}); | ||
|
||
it('should return 0 griefing collateral if bridgedAsset is not valid', async () => { | ||
const { result } = renderHook(() => useCalculateGriefingCollateral(new Big(1000), undefined)); | ||
|
||
const expectation = () => expect(result.current.eq(new Big(0))).toBeTruthy(); | ||
|
||
expectation(); | ||
await waitFor(expectation); | ||
}); | ||
|
||
it('should return 0 griefing collateral if griefingCollateralCurrency is not valid', async () => { | ||
mockGetFees.mockReturnValueOnce({ | ||
griefingCollateralCurrency: undefined, | ||
issueGriefingCollateralFee: 0.05, | ||
}); | ||
|
||
const { result } = renderHook(() => useCalculateGriefingCollateral(new Big(1000), VALID_ASSET)); | ||
|
||
const expectation = () => expect(result.current.eq(new Big(0))).toBeTruthy(); | ||
|
||
expectation(); | ||
await waitFor(expectation); | ||
}); | ||
|
||
it('should calculate griefing collateral correctly', async () => { | ||
const amount = new Big(STELLAR_ONE_WITH_DECIMALS); | ||
const { result } = renderHook(() => useCalculateGriefingCollateral(amount, VALID_ASSET)); | ||
|
||
// First returned value (before useEffect is fired) | ||
expect(result.current.eq(0)).toBeTruthy(); | ||
|
||
const griefingFee = mockGetFees().issueGriefingCollateralFee; | ||
// Since we assume the same price for all assets, the decimal griefing collateral is the amount * griefingFee / decimals | ||
const griefingAmount = amount | ||
.times(griefingFee) | ||
.div(10 ** 12) | ||
.toNumber(); | ||
|
||
await waitFor(() => expect(result.current.eq(griefingAmount)).toBeTruthy()); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import { Asset } from 'stellar-base'; | ||
import Big from 'big.js'; | ||
import { useEffect, useState, useMemo } from 'preact/compat'; | ||
import { nativeStellarToDecimal } from '../../shared/parseNumbers/metric'; | ||
import { convertStellarAssetToCurrency } from '../../helpers/spacewalk'; | ||
import { useNodeInfoState } from '../../NodeInfoProvider'; | ||
import { usePriceFetcher } from '../usePriceFetcher'; | ||
import { useFeePallet } from './useFeePallet'; | ||
|
||
const isInvalid = (value: unknown) => { | ||
return !value; | ||
}; | ||
|
||
export const useCalculateGriefingCollateral = (amount: Big, bridgedAsset?: Asset): Big.Big => { | ||
const { getTokenPriceForCurrency } = usePriceFetcher(); | ||
const { getFees } = useFeePallet(); | ||
const [griefingCollateral, setGriefingCollateral] = useState<Big>(new Big(0)); | ||
const { api } = useNodeInfoState().state; | ||
|
||
const { griefingCollateralCurrency, issueGriefingCollateralFee } = getFees(); | ||
|
||
const bridgedCurrency = useMemo(() => { | ||
return bridgedAsset && api ? convertStellarAssetToCurrency(bridgedAsset, api) : null; | ||
}, [bridgedAsset, api]); | ||
|
||
useEffect(() => { | ||
const calculateGriefingCollateral = async () => { | ||
if (isInvalid(amount) || isInvalid(bridgedCurrency) || isInvalid(griefingCollateralCurrency)) return; | ||
|
||
if (bridgedCurrency && griefingCollateralCurrency) { | ||
try { | ||
const assetUSDPrice = await getTokenPriceForCurrency(bridgedCurrency); | ||
const amountUSD = nativeStellarToDecimal(amount).mul(assetUSDPrice); | ||
|
||
const griefingCollateralCurrencyUSD = await getTokenPriceForCurrency(griefingCollateralCurrency); | ||
if (isInvalid(griefingCollateralCurrencyUSD)) return; | ||
|
||
setGriefingCollateral(amountUSD.mul(issueGriefingCollateralFee).div(griefingCollateralCurrencyUSD)); | ||
} catch (error) { | ||
console.error('Error calculating griefing collateral:', error); | ||
} | ||
} | ||
}; | ||
|
||
calculateGriefingCollateral(); | ||
}, [amount, getTokenPriceForCurrency, griefingCollateralCurrency, issueGriefingCollateralFee, bridgedCurrency]); | ||
|
||
return griefingCollateral; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.