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

[unit tests] events #76

Merged
merged 2 commits into from
Dec 8, 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
104 changes: 104 additions & 0 deletions packages/sdk/src/events/__tests__/events.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { describe, test, expect, beforeAll } from '@jest/globals';
import { expectSDKModule } from '../../../tests/utils/expect/expect-sdk-module.js';
import { LidoSDKEvents } from '../events.js';
import { LidoSDKStethEvents } from '../steth-events.js';
import { useEvents } from '../../../tests/utils/fixtures/use-events.js';
import { LIDO_CONTRACT_NAMES } from '../../index.js';

import { expectRebaseEvent } from '../../../tests/utils/expect/expect-rebase-event.js';

describe('LidoSDKEvents', () => {
const { stethEvents, core } = useEvents();
let lidoAddress = '';

beforeAll(async () => {
lidoAddress = await core.getContractAddress(LIDO_CONTRACT_NAMES.lido);
});

test('is correct module', () => {
expectSDKModule(LidoSDKEvents);
expectSDKModule(LidoSDKStethEvents);
expect(stethEvents).toBeInstanceOf(LidoSDKStethEvents);
});

test('getLastRebaseEvent', async () => {
const event = await stethEvents.getLastRebaseEvent();
expectRebaseEvent(event, lidoAddress);
});

test.each([[1], [2], [3], [10]])(
'getLastRebaseEvents %i count',
async (count) => {
const events = await stethEvents.getLastRebaseEvents({ count });
expect(events).toHaveLength(count);
for (const event of events) {
expectRebaseEvent(event);
}
// eslint-disable-next-line sonarjs/no-ignored-return
events.reduce((rebaseEvent1, rebaseEvent2) => {
expect(rebaseEvent1.blockNumber).toBeLessThan(rebaseEvent2.blockNumber);
return rebaseEvent2;
});
},
);

test.each([500, 5000, 50000])(
'getLastRebaseEvents %i step',
async (stepBlock) => {
const count = 5;
const events = await stethEvents.getLastRebaseEvents({
count,
stepBlock,
});
expect(events).toHaveLength(count);
for (const event of events) {
expectRebaseEvent(event);
}
// eslint-disable-next-line sonarjs/no-ignored-return
events.reduce((rebaseEvent1, rebaseEvent2) => {
expect(rebaseEvent1.blockNumber).toBeLessThan(rebaseEvent2.blockNumber);
return rebaseEvent2;
});
},
);

test('getRebaseEvents', async () => {
const events = await stethEvents.getRebaseEvents({
back: { days: 10n },
maxCount: 10,
});
expect(events).toHaveLength(10);
for (const event of events) {
expectRebaseEvent(event);
}
});

test('getRebaseEvents fits range', async () => {
const todayTimestamp = BigInt(Math.floor(Date.now() / 1000));
const earlierTimestamp = todayTimestamp - 3600n * 24n * 3n;
const events = await stethEvents.getRebaseEvents({
from: { timestamp: earlierTimestamp },
to: { timestamp: todayTimestamp },
maxCount: 10,
});
expect(events).toHaveLength(10);
for (const event of events) {
expectRebaseEvent(event);

const block = await core.rpcProvider.getBlock({
blockNumber: event.blockNumber,
});

expect(block.timestamp).toBeLessThanOrEqual(todayTimestamp);
expect(block.timestamp).toBeGreaterThanOrEqual(earlierTimestamp);
}
});

test.each([[1], [2], [10], [20]])(
'getFirstRebaseEvent at %i days',
async (days) => {
const rebaseEvent = await stethEvents.getFirstRebaseEvent({ days });
expectRebaseEvent(rebaseEvent);
},
);
});
4 changes: 2 additions & 2 deletions packages/sdk/src/events/steth-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ export class LidoSDKStethEvents extends LidoSDKModule {

const contract = await this.getContractStETH();

for (let day = 1; day <= DAYS_LIMIT; day++) {
const from = fromBlockNumber - BigInt(days + 1 - day) * BLOCKS_BY_DAY;
for (let dayOffset = 0; dayOffset < DAYS_LIMIT; dayOffset++) {
const from = fromBlockNumber - BigInt(days - dayOffset) * BLOCKS_BY_DAY;
invariantArgument(from >= 0n, 'Days range precedes first block');
const to = from + BLOCKS_BY_DAY;

Expand Down
19 changes: 19 additions & 0 deletions packages/sdk/tests/utils/expect/expect-rebase-event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { expect } from '@jest/globals';
import { expectPositiveBn } from './expect-bn.js';
import { expectAddress } from './expect-address.js';

export const expectRebaseEvent = (event: any, lidoAddress?: string) => {
expect(event).toBeDefined();

expect(event).toHaveProperty('eventName', 'TokenRebased');

expectPositiveBn(event.args.postTotalEther);
expectPositiveBn(event.args.postTotalShares);
expectPositiveBn(event.args.preTotalEther);
expectPositiveBn(event.args.preTotalShares);
expectPositiveBn(event.args.reportTimestamp);
expectPositiveBn(event.args.sharesMintedAsFees);
expectPositiveBn(event.args.timeElapsed);

lidoAddress && expectAddress(event.address, lidoAddress);
};
8 changes: 8 additions & 0 deletions packages/sdk/tests/utils/fixtures/use-events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { LidoSDKEvents } from '../../../src/index.js';
import { useRpcCore } from './use-core.js';

export const useEvents = () => {
const core = useRpcCore();
const events = new LidoSDKEvents({ core });
return events;
};
46 changes: 46 additions & 0 deletions playground/components/custom-rpc-input/custom-rpc-input.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { useSDK } from '@lido-sdk/react';
import { Accordion, Button, DataTableRow, Input } from '@lidofinance/lido-ui';
import { useCustomRpc } from 'providers/web3';
import { useEffect, useState } from 'react';
import { Controls, StyledBlock } from './styles';

export const CustomRpcInput = () => {
const { chainId } = useSDK();
const { activeRpc, setCustomRpcUrl, customRpc } = useCustomRpc();
const [url, setUrl] = useState('');

const isDefault = activeRpc[chainId] !== customRpc[chainId];

useEffect(() => {
const customUrl = customRpc[chainId] ?? '';
setUrl(customUrl);
}, [chainId]);

Check warning on line 17 in playground/components/custom-rpc-input/custom-rpc-input.tsx

View workflow job for this annotation

GitHub Actions / check-all

React Hook useEffect has a missing dependency: 'customRpc'. Either include it or remove the dependency array

return (
<Accordion summary="Custom RPC">
<StyledBlock>
<Input
value={url}
onChange={(e) => setUrl(e.currentTarget.value)}
label={`RPC Url for chain ${chainId}`}
/>
<Controls>
<Button
disabled={!url}
fullwidth
onClick={() => setCustomRpcUrl(chainId, url)}
>
Save
</Button>
<Button fullwidth onClick={() => setCustomRpcUrl(chainId, null)}>
Reset
</Button>
</Controls>

<DataTableRow title="Current RPC">
{isDefault ? 'default' : 'custom'}
</DataTableRow>
</StyledBlock>
</Accordion>
);
};
1 change: 1 addition & 0 deletions playground/components/custom-rpc-input/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { CustomRpcInput } from './custom-rpc-input';
16 changes: 16 additions & 0 deletions playground/components/custom-rpc-input/styles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Block } from '@lidofinance/lido-ui';
import styled from 'styled-components';

export const Controls = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
gap: 20px;
`;

export const StyledBlock = styled(Block)`
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 20px;
`;
6 changes: 0 additions & 6 deletions playground/config/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,3 @@ import dynamics from './dynamics';
export const getBackendRPCPath = (chainId: CHAINS) => {
return dynamics.rpcProviderUrls[chainId];
};

export const backendRPC = {
[CHAINS.Mainnet]: getBackendRPCPath(CHAINS.Mainnet),
[CHAINS.Goerli]: getBackendRPCPath(CHAINS.Goerli),
[CHAINS.Holesky]: getBackendRPCPath(CHAINS.Holesky),
};
2 changes: 2 additions & 0 deletions playground/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Head from 'next/head';
import Layout from 'components/layout';
import { Demo } from 'demo';
import { ConnectionError } from 'components/connection-error';
import { CustomRpcInput } from 'components/custom-rpc-input';

const Home = () => {
return (
Expand All @@ -11,6 +12,7 @@ const Home = () => {
<title>Lido | SDK Playground</title>
</Head>
<ConnectionError />
<CustomRpcInput />
<Demo />
</Layout>
);
Expand Down
7 changes: 4 additions & 3 deletions playground/providers/sdk.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { createWalletClient, custom } from 'viem';

import { LidoSDK } from '@lidofinance/lido-ethereum-sdk';
import invariant from 'tiny-invariant';
import { getBackendRPCPath } from 'config';
import { useCustomRpc } from './web3';

const context = createContext<LidoSDK | null>(null);

Expand All @@ -17,6 +17,7 @@ export const useLidoSDK = () => {

export const LidoSDKProvider: React.FC<PropsWithChildren> = ({ children }) => {
const { providerWeb3, chainId, account } = useSDK();
const { activeRpc } = useCustomRpc();
const value = useMemo(() => {
const client =
providerWeb3 && account
Expand All @@ -26,14 +27,14 @@ export const LidoSDKProvider: React.FC<PropsWithChildren> = ({ children }) => {
: undefined;
const sdk = new LidoSDK({
chainId: chainId as any,
rpcUrls: [getBackendRPCPath(chainId)],
rpcUrls: [activeRpc[chainId]],
web3Provider: client as any,
logMode: 'debug',
});
// inject lido_sdk for console access
if (typeof window !== 'undefined') (window as any).lido_sdk = sdk;
return sdk;
}, [providerWeb3, chainId, account]);
}, [providerWeb3, chainId, account, activeRpc]);

return <context.Provider value={value}>{children}</context.Provider>;
};
Loading
Loading