Skip to content

Commit

Permalink
Pre migration refactor | unit tests (#59)
Browse files Browse the repository at this point in the history
* take into account interlude period

* tests setup

* more tests

* fix build

* fix ci

* fi ci

* clean up interlacing

* util tests

* lint fixes

* disable market for now
  • Loading branch information
Szegoo committed Apr 3, 2024
1 parent bae1075 commit d4fe721
Show file tree
Hide file tree
Showing 13 changed files with 341 additions and 57 deletions.
7 changes: 7 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript",
"next/babel"
]
}
14 changes: 6 additions & 8 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ name: Corehub CI

on:
push:
branches: [main]
branches: [master]
pull_request:
branches: [main]
branches: [master]

jobs:
build:
build-and-test:
runs-on: ubuntu-latest

steps:
Expand All @@ -31,8 +31,6 @@ jobs:
- name: Check Prettier
run: npm run format

all:
needs: [build]
runs-on: ubuntu-latest
steps:
- run: echo Success
# Run tests
- name: Run Tests
run: npm run test
13 changes: 13 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = {
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
'^.+\\.(js|jsx)$': 'babel-jest',
},
moduleNameMapper: {
// If you're using absolute imports or path aliases, set them up here
},
testEnvironment: 'jsdom', // or "node", depending on your project needs
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1', // Ensure this matches the structure defined in tsconfig.json
},
};
12 changes: 10 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"start": "next start",
"build": "next build",
"lint": "next lint",
"format": "npx prettier --write '**/*.{js,jsx,ts,tsx}'"
"format": "npx prettier --write '**/*.{js,jsx,ts,tsx}'",
"test": "jest"
},
"dependencies": {
"@date-io/date-fns": "^3.0.0",
Expand All @@ -16,7 +17,7 @@
"@emotion/styled": "^11.6.0",
"@mui/icons-material": "^5.2.5",
"@mui/lab": "5.0.0-alpha.134",
"@mui/material": "^5.2.8",
"@mui/material": "^5.15.14",
"@mui/x-date-pickers": "^6.19.5",
"@polkadot/api": "^10.8.1",
"@polkadot/api-contract": "^10.8.1",
Expand All @@ -40,18 +41,25 @@
},
"devDependencies": {
"@babel/core": "^7.16.7",
"@babel/preset-env": "^7.24.3",
"@babel/preset-typescript": "^7.24.1",
"@types/jest": "^29.5.12",
"@types/node": "^18.16.1",
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.1",
"@typescript-eslint/eslint-plugin": "^5.59.1",
"@typescript-eslint/parser": "^5.59.1",
"babel-jest": "^29.7.0",
"babel-loader": "^9.1.2",
"eslint": "^8.39.0",
"eslint-config-next": "^13.3.1",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-simple-import-sort": "^7.0.0",
"eslint-plugin-storybook": "^0.5.5",
"eslint-plugin-unused-imports": "^2.0.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"ts-jest": "^29.1.2",
"typescript": "^4.7.4",
"webpack": "^5.81.0"
}
Expand Down
10 changes: 3 additions & 7 deletions src/components/Modals/Interlace/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,16 @@ export const InterlaceModal = ({
const { fetchRegions } = useRegions();

const currentMask = regionMetadata.region.getMask().toBin();
// Represents the first active bit in the bitmap.
const oneStart = currentMask.indexOf('1');
// Represents the last active bit in the bitmap.
const oneEnd = currentMask.lastIndexOf('1');
const activeBits = oneEnd - oneStart + 1;

const [working, setWorking] = useState(false);
const [position, setPosition] = useState(oneStart);

const generateMask = (position: number): string => {
const mask = Array(COREMASK_BIT_LEN).fill('0');
for (let i = oneStart; i <= position; ++i) mask[i] = '1';
return mask.join('');
};

const newMask = generateMask(position);
const newMask = CoreMask.fromChunk(oneStart, position + 1).toBin();

const onInterlace = async () => {
if (!api || !activeAccount || !activeSigner) return;
Expand Down
2 changes: 1 addition & 1 deletion src/components/Sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export const Sidebar = () => {
{
label: 'Explore the Market',
route: '/marketplace',
enabled: true,
enabled: false,
icon: <ExploreIcon />,
},
],
Expand Down
5 changes: 4 additions & 1 deletion src/models/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ export const RELAY_CHAIN_BLOCK_TIME = 6 * SECOND;

export const CORETIME_DECIMALS = 12;
export const CONTRACT_DECIMALS = 18;
export const LISTING_DEPOSIT = 0 * CONTRACT_DECIMALS;

export const CORETIME_TOKEN_UNIT = Math.pow(10, CORETIME_DECIMALS);
export const CONTRACTS_TOKEN_UNIT = Math.pow(10, CONTRACT_DECIMALS);
export const LISTING_DEPOSIT = 0 * CONTRACTS_TOKEN_UNIT;

/// Given that a timeslice is 8 minutes;
export const DAY_IN_TIMESLICES = 180;
Expand Down
49 changes: 26 additions & 23 deletions src/pages/purchase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { useCallback, useEffect, useState } from 'react';
import {
formatBalance,
getBlockTimestamp,
leadinFactorAt,
parseHNString,
} from '@/utils/functions';

Expand All @@ -24,6 +23,14 @@ import { useSaleInfo } from '@/contexts/sales';
import { useToast } from '@/contexts/toast';
import { SalePhase } from '@/models';

import {
getCurrentPhase,
getCurrentPrice,
getSaleEndInBlocks,
getSaleProgress,
getSaleStartInBlocks,
} from '../utils/sale/utils';

const Purchase = () => {
const theme = useTheme();

Expand Down Expand Up @@ -79,29 +86,31 @@ const Purchase = () => {
(await api.query.broker.status()).toHuman() as any
).lastCommittedTimeslice.toString()
);
const _saleStart = saleInfo.saleStart;
const _saleEnd =
blockNumber + 80 * (saleInfo.regionBegin - lastCommittedTimeslice);

const _saleStart = getSaleStartInBlocks(saleInfo, config);
const _saleEnd = getSaleEndInBlocks(
saleInfo,
blockNumber,
lastCommittedTimeslice
);

setCurrentBlockNumber(blockNumber);
setSaleEnd(_saleEnd);
getBlockTimestamp(api, _saleEnd).then((value) =>
setSaleEndTimestamp(value)
);

const saleDuration = _saleEnd - _saleStart;
const elapsed = blockNumber - _saleStart;
const progress = getSaleProgress(
saleInfo,
config,
blockNumber,
lastCommittedTimeslice
);
setProgress(progress);

const progress = elapsed / saleDuration;
setProgress(progress * 100);
setCurrentPhase(getCurrentPhase(saleInfo, blockNumber));

if (saleInfo.saleStart > blockNumber) {
setCurrentPhase(SalePhase.Interlude);
} else if (saleInfo.saleStart + saleInfo.leadinLength > blockNumber) {
setCurrentPhase(SalePhase.Leadin);
} else {
setCurrentPhase(SalePhase.Regular);
}
const saleDuration = _saleEnd - _saleStart;

setSaleSections([
{ name: 'Interlude', value: 0 },
Expand All @@ -124,14 +133,8 @@ const Purchase = () => {
async (api: ApiPromise) => {
const blockNumber = (await api.query.system.number()).toJSON() as number;

const num = Math.min(
blockNumber - saleInfo.saleStart,
saleInfo.leadinLength
);
const through = num / saleInfo.leadinLength;
setCurrentPrice(
Number((leadinFactorAt(through) * saleInfo.price).toFixed())
);
const price = getCurrentPrice(saleInfo, blockNumber);
setCurrentPrice(price);
},
[saleInfo]
);
Expand Down
41 changes: 41 additions & 0 deletions src/utils/functions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { CoreMask, RegionId } from 'coretime-utils';

import {
extractRegionIdFromRaw,
parseHNString,
parseHNStringToString,
} from './functions';

describe('Util functions', () => {
describe('parseHNString', () => {
it('works', () => {
const a = '100,305';
expect(parseHNString(a)).toBe(100305);
const b = '42';
expect(parseHNString(b)).toBe(42);
expect(parseHNString('')).toBe(NaN);
});
});

describe('parseHNStringToString', () => {
it('works', () => {
const a = '100,305';
expect(parseHNStringToString(a)).toBe('100305');
const b = '42';
expect(parseHNStringToString(b)).toBe('42');
expect(parseHNStringToString('')).toBe('');
});
});

describe('extractRegionIdFromRaw', () => {
it('works', () => {
const raw = '316913858982876965003350507519';
const regionId: RegionId = {
begin: 4,
core: 0,
mask: CoreMask.completeMask(),
};
expect(extractRegionIdFromRaw(BigInt(raw))).toStrictEqual(regionId);
});
});
});
17 changes: 8 additions & 9 deletions src/utils/functions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ApiPromise } from '@polkadot/api';
import { formatBalance as polkadotFormatBalance } from '@polkadot/util';
import { CoreMask, RegionId } from 'coretime-utils';
import Decimal from 'decimal.js';

Expand Down Expand Up @@ -82,18 +83,16 @@ export const formatBalance = (balance: string, contractChain: boolean) => {
Decimal.config({ rounding: Decimal.ROUND_DOWN });
const decimals = contractChain ? CONTRACT_DECIMALS : CORETIME_DECIMALS;

if (new Decimal(balance).lt(new Decimal(10).pow(CONTRACT_DECIMALS))) {
return new Decimal(balance)
.dividedBy(new Decimal(10).pow(decimals))
.toPrecision(2);
} else {
return new Decimal(balance)
.dividedBy(new Decimal(10).pow(decimals))
.toFixed(2);
}
return polkadotFormatBalance(balance, {
decimals,
withUnit: false,
withSiFull: true,
});
};

// TODO: should be queried from runtime api instead.
//
// https://github.com/paritytech/polkadot-sdk/pull/3485
export const leadinFactorAt = (when: number) => {
return 2 - when;
};
Expand Down
Loading

0 comments on commit d4fe721

Please sign in to comment.