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

feat: add useStableCoin test case & handle some edge cases. #203

Merged
merged 1 commit into from
Oct 11, 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
2 changes: 1 addition & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default {
},

// An array of file extensions your modules use
moduleFileExtensions: ['js', 'ts', 'json'],
moduleFileExtensions: ['js', 'ts', 'json', 'tsx'],

// The paths to modules that run some code to configure or set up the testing environment before each test
setupFiles: ['./test/jest-setup.ts'],
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
"@metamask/eth-sig-util": "^4.0.1",
"@octokit/request": "^5.6.3",
"@subql/contract-sdk": "^0.16.2",
"@testing-library/react": "^14.0.0",
"@types/jest": "^28.1.6",
"@types/react": "^18.0.12",
"@types/react": "^18.2.28",
"@typescript-eslint/eslint-plugin": "^5.27.0",
"@typescript-eslint/parser": "^5.27.0",
"axios": "^0.27.2",
Expand All @@ -32,11 +33,13 @@
"husky": "^8.0.1",
"ipfs-http-client": "^53.0.1",
"jest": "^29.6.2",
"jest-environment-jsdom": "^29.7.0",
"jest-mock-axios": "^4.7.2",
"jwt-decode": "^3.1.2",
"lint-staged": "^13.0.0",
"prettier": "^2.7.1",
"react": "^18.1.0",
"react-dom": "^18.2.0",
"ts-jest": "^29.1.1",
"ts-node": "^10.8.1"
},
Expand Down
111 changes: 73 additions & 38 deletions packages/react-hooks/src/useStableCoin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,59 +62,94 @@ export const useStableCoin = (contracts: ContractSDK | undefined, network: SQNet
};

const transPrice = (fromAddress: string | undefined, price: string | number | bigint) => {
const isSQT =
toChecksumAddress(fromAddress || '') === toChecksumAddress(contracts?.sqToken.address || '');
const sortedPrice = isSQT
? formatSQT(price.toString())
: formatUnits(price, STABLE_COIN_DECIMAL);

const resultCalc = BigNumber(sortedPrice).multipliedBy(
isSQT ? rates.sqtToUsdc : rates.usdcToSqt
);
return {
usdcPrice: (isSQT ? resultCalc.toFixed() : sortedPrice).toString(),
sqtPrice: (isSQT ? sortedPrice : resultCalc.toFixed()).toString(),
};
if (!contracts?.sqToken.address || !fromAddress)
return {
usdcPrice: '0',
sqtPrice: '0',
};

try {
const isSQT =
toChecksumAddress(fromAddress) === toChecksumAddress(contracts?.sqToken.address);
const isUSDC = toChecksumAddress(fromAddress) === toChecksumAddress(STABLE_COIN_ADDRESS);

if (!isSQT && !isUSDC) {
return {
usdcPrice: '0',
sqtPrice: '0',
};
}
const sortedPrice = isSQT
? formatSQT(price.toString())
: formatUnits(price, STABLE_COIN_DECIMAL);

const resultCalc = BigNumber(sortedPrice).multipliedBy(
isSQT ? rates.sqtToUsdc : rates.usdcToSqt
);
return {
usdcPrice: (isSQT ? resultCalc.toFixed() : sortedPrice).toString(),
sqtPrice: (isSQT ? sortedPrice : resultCalc.toFixed()).toString(),
};
} catch (e) {
console.error(e);
return {
usdcPrice: '0',
sqtPrice: '0',
};
}
};

const pricePreview = (fromAddress: string | undefined, price: string | number | bigint) => {
const sqtTokenAddress = toChecksumAddress(contracts?.sqToken.address || '');
const prices = transPrice(toChecksumAddress(fromAddress || ''), price);
if (!contracts?.sqToken.address || !fromAddress) return <span>Error: address is invalid</span>;

try {
const sqtTokenAddress = toChecksumAddress(contracts?.sqToken.address);
const prices = transPrice(toChecksumAddress(fromAddress), price);

if (sqtTokenAddress === toChecksumAddress(fromAddress)) {
return (
<span
style={{
color: 'var(--gray-900, #1A202C)',
fontSize: '14px',
fontFamily: 'var(--sq-font-family)',
}}
role="sqtPrice"
aria-label="sqtPrice"
>
{prices.sqtPrice} {TOKEN}
</span>
);
}

if (sqtTokenAddress === toChecksumAddress(fromAddress || '')) {
return (
<span
style={{
color: 'var(--gray-900, #1A202C)',
fontSize: '14px',
fontFamily: 'var(--sq-font-family)',
}}
role="usdcPrice"
aria-label="usdcPrice"
>
{prices.sqtPrice} {TOKEN}
{prices.usdcPrice} {STABLE_TOKEN} <br></br>
<span
style={{
color: 'var(--gray-600, #637381)',
fontSize: '12px',
fontFamily: 'var(--sq-font-family)',
}}
role="usdcToSqtPrice"
aria-label="usdcToSqtPrice"
>
= {prices.sqtPrice} {TOKEN} | {now?.format('HH:mm:ss A')}
</span>
</span>
);
} catch (e) {
console.error(e);
return <span>Error: address is invalid</span>;
}

return (
<span
style={{
color: 'var(--gray-900, #1A202C)',
fontSize: '14px',
fontFamily: 'var(--sq-font-family)',
}}
>
{prices.usdcPrice} {STABLE_TOKEN} <br></br>
<span
style={{
color: 'var(--gray-600, #637381)',
fontSize: '12px',
fontFamily: 'var(--sq-font-family)',
}}
>
= {prices.sqtPrice} {TOKEN} | {now?.format('HH:mm:ss A')}
</span>
</span>
);
};

useInterval(
Expand Down
84 changes: 84 additions & 0 deletions test/react-hooks.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* @jest-environment jsdom
*/
/* eslint-disable header/header */
// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { act, render, screen } from '@testing-library/react';
import { useStableCoin } from '../packages/react-hooks/src';
import { ContractSDK } from '@subql/contract-sdk';
import { SQNetworks, STABLE_COIN_ADDRESSES, STABLE_COIN_DECIMAL } from '@subql/network-config/src';
import { BigNumber } from 'ethers';
import { useEffect } from 'react';

test('useStableCoin should work', async () => {
let calledTimes = 0;
const contracts = {
sqToken: {
address: '0xed3bb617dbC128095f8b0A00B9498C2Ef5c3D04a',
},
priceOracle: {
convertPrice: async (fromAddress, toAddress, decimal) => {
calledTimes = 1;
expect(fromAddress).toEqual(STABLE_COIN_ADDRESSES[SQNetworks.TESTNET]);
expect(toAddress).toEqual('0xed3bb617dbC128095f8b0A00B9498C2Ef5c3D04a');
expect(decimal).toEqual(10 ** STABLE_COIN_DECIMAL);

return BigNumber.from('50000000000000000000');
},
},
} as ContractSDK;

function Setup() {
const { rates, pricePreview, transPrice } = useStableCoin(contracts, SQNetworks.TESTNET);

const testRates = () => {
expect(rates.sqtToUsdc).toEqual(0.02);
expect(rates.usdcToSqt).toEqual(50);

expect(
transPrice('0xed3bb617dbC128095f8b0A00B9498C2Ef5c3D04a', '50000000000000000000').sqtPrice
).toEqual('50');
expect(
transPrice('0xed3bb617dbC128095f8b0A00B9498C2Ef5c3D04a', '50000000000000000000').usdcPrice
).toEqual('1');

expect(transPrice(STABLE_COIN_ADDRESSES[SQNetworks.TESTNET], '1000000').sqtPrice).toEqual(
'50'
);

expect(transPrice(STABLE_COIN_ADDRESSES[SQNetworks.TESTNET], '1000000').usdcPrice).toEqual(
'1.0'
);

expect(transPrice('', '50000000000000000000').sqtPrice).toEqual('0');
expect(transPrice('0x000', '50000000000000000000').sqtPrice).toEqual('0');
expect(
transPrice('0x0000000000000000000000000000000000000000', '50000000000000000000').sqtPrice
).toEqual('0');
};

useEffect(() => {
if (rates.sqtToUsdc !== 0) {
testRates();
}
}, [rates]);

return (
<div>
<span>
{pricePreview('0xed3bb617dbC128095f8b0A00B9498C2Ef5c3D04a', '50000000000000000000')}
</span>

<span>{pricePreview(STABLE_COIN_ADDRESSES[SQNetworks.TESTNET], '1000000')}</span>
</div>
);
}

await act(async () => await render(<Setup />));

expect(await screen.getByRole('sqtPrice').textContent?.includes('50'));
expect(await screen.getByRole('usdcPrice').textContent?.includes('1'));
expect(calledTimes).toEqual(1);
});
4 changes: 3 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
"skipLibCheck": true, /* Skip type checking all .d.ts files. */
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"types": ["node", "jest"]
"types": ["node", "jest"],
"jsx": "react-jsx"

},
"include": ["packages/**/*","test"],
"exclude": ["**/node_modules/**"]
Expand Down
Loading