Skip to content

Commit

Permalink
refactor getCapacityInfo
Browse files Browse the repository at this point in the history
  • Loading branch information
claireolmstead committed Feb 6, 2024
1 parent 93213ee commit aada014
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 82 deletions.
17 changes: 0 additions & 17 deletions src/components/BecomeAProvider.svelte
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
<script lang="ts">
import { dotApi } from '$lib/stores';
import { onMount } from 'svelte';
import type { web3Enable, web3FromSource } from '@polkadot/extension-dapp';
import { defaultDotApi } from '$lib/storeTypes';
import type { DotApi } from '$lib/storeTypes';
import { user } from '$lib/stores/userStore';
import { nonProviderAccountsStore } from '$lib/stores/accountsStore';
import BlockSection from './BlockSection.svelte';
Expand All @@ -13,22 +8,10 @@
import EmailProviderRequest from './EmailProviderRequest.svelte';
import { pageContent } from '$lib/stores/pageContentStore';
let localDotApi: DotApi = defaultDotApi;
let thisWeb3FromSource: typeof web3FromSource;
let thisWeb3Enable: typeof web3Enable;
// a callback for when the user cancels this action
export let cancelAction = () => {
pageContent.login();
};
onMount(async () => {
const extension = await import('@polkadot/extension-dapp');
thisWeb3FromSource = extension.web3FromSource;
thisWeb3Enable = extension.web3Enable;
});
dotApi.subscribe((api) => (localDotApi = api));
</script>

<div id="become-a-provider" class="content-block column w-single-block">
Expand Down
26 changes: 7 additions & 19 deletions src/components/Capacity.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,18 @@
import { dotApi, storeChainInfo, storeCurrentAction } from '$lib/stores';
import { user } from '$lib/stores/userStore';
import type { ApiPromise } from '@polkadot/api';
import { getMsaEpochAndCapacityInfo } from '$lib/polkadotApi';
import { getCapacityInfo, type CapacityDetails } from '$lib/polkadotApi';
import { balanceToHuman } from '$lib/utils.js';
import ListCard from './ListCard.svelte';
import { ActionForms } from '$lib/storeTypes.js';
import { onMount } from 'svelte';
import { afterUpdate } from 'svelte';
type CapacityDetails = {
remainingCapacity: bigint;
totalTokensStaked: bigint;
totalCapacityIssued: bigint;
lastReplenishedEpoch: bigint;
};
const defaultDetails: CapacityDetails = {
remainingCapacity: 0n,
totalCapacityIssued: 0n,
totalTokensStaked: 0n,
lastReplenishedEpoch: 0n,
};
let capacityDetails: CapacityDetails;
let capacityDetails: CapacityDetails = defaultDetails;
onMount(async () => {
let { capacityDetails } = await getMsaEpochAndCapacityInfo($dotApi.api as ApiPromise, $user.address);
capacityDetails = { ...defaultDetails, ...capacityDetails };
afterUpdate(async () => {
if ($user?.msaId && $user?.msaId > 0) {
capacityDetails = await getCapacityInfo($dotApi.api as ApiPromise, $user.msaId);
}
});
function showStake() {
Expand Down
1 change: 0 additions & 1 deletion src/components/CreateProvider.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import { user } from '$lib/stores/userStore';
import { getMsaInfo } from '$lib/polkadotApi';
import type { MsaInfo } from '$lib/storeTypes';
import { nonProviderAccountsStore, providerAccountsStore } from '$lib/stores/accountsStore';
import { pageContent } from '$lib/stores/pageContentStore';
let newProviderName = '';
Expand Down
1 change: 0 additions & 1 deletion src/components/Nav.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<script lang="ts">
import { navigating } from '$app/stores';
import { onMount } from 'svelte';
import iconLogo from '$lib/assets/icon-logo.png';
Expand Down
5 changes: 3 additions & 2 deletions src/components/Provider.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
import type { AccountBalances } from '$lib/polkadotApi';
import ListCard from './ListCard.svelte';
import { ActionForms } from '$lib/storeTypes.js';
import { afterUpdate } from 'svelte';
import { onMount } from 'svelte';
let accountBalances: AccountBalances = { free: 0n, reserved: 0n, frozen: 0n };
afterUpdate(async () => {
onMount(async () => {
console.log($dotApi.selectedEndpoint);
if ($dotApi.api) {
accountBalances = await getBalances($dotApi.api, $user.address);
}
Expand Down
7 changes: 6 additions & 1 deletion src/components/ProviderLogin.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@
$: canConnect = $user?.network != null && $providerAccountsStore.size > 0 && $user?.address !== '';
async function connect() {
await createAndConnectToApi($user.network?.endpoint?.toString()!);
if (!$user.network?.endpoint?.origin) {
alert('Error connecting to endpoint.');
return;
}
console.log('HERE USER', $user);
await createAndConnectToApi($user.network?.endpoint?.origin);
$isLoggedIn = true;
pageContent.dashboard();
}
Expand Down
5 changes: 3 additions & 2 deletions src/components/SelectNetworkAndAccount.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,14 @@
try {
networkErrorMsg = '';
controlKeysErrorMsg = '';
const curApi = await createApi(network.endpoint!?.toString());
if (!network.endpoint) throw new Error('Undefined endpoint.');
const curApi = await createApi(network.endpoint?.origin);
await fetchAccountsForNetwork(network, thisWeb3Enable, thisWeb3Accounts, curApi.api as ApiPromise);
await curApi.api?.disconnect();
} catch (e) {
console.log(e);
networkErrorMsg = `Could not connect to ${
network.endpoint?.toString() || 'empty value'
network.endpoint?.origin || 'empty value'
}. Please enter a valid and reachable Websocket URL.`;
console.error(networkErrorMsg);
}
Expand Down
57 changes: 31 additions & 26 deletions src/lib/polkadotApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,14 @@ async function updateChainInfo(api: ApiPromise) {
}

export async function createAndConnectToApi(networkEndpoint: string) {
dotApi.subscribe(async (apiState: DotApi) => await apiState.api?.disconnect());

let initializedDotApi = await createApi(networkEndpoint);
dotApi.set((currentApi: DotApi) => (currentApi = initializedDotApi));

await updateChainInfo(initializedDotApi.api!);
const initializedDotApi = await createApi(networkEndpoint);
dotApi.set(initializedDotApi);
await updateChainInfo(initializedDotApi.api);
}

export async function createApi(networkEndpoint: string): Promise<DotApi> {
const wsProvider = new WsProvider(networkEndpoint);

const apiPromise = await ApiPromise.create({
provider: wsProvider,
throwOnConnect: true,
Expand All @@ -45,7 +43,6 @@ export async function createApi(networkEndpoint: string): Promise<DotApi> {
selectedEndpoint: networkEndpoint,
options,
};

return initializedDotApi;
}

Expand Down Expand Up @@ -83,24 +80,32 @@ export async function getMsaInfo(apiPromise: ApiPromise, publicKey: string): Pro
return msaInfo;
}

export async function getMsaEpochAndCapacityInfo(
apiPromise: ApiPromise,
accountId: string
): Promise<{ epochNumber: bigint; msaInfo: MsaInfo; capacityDetails: any }> {
const msaInfo = await getMsaInfo(apiPromise, accountId);
const epochNumber = await getEpoch(apiPromise);
let capacityDetails;
if (msaInfo.msaId > 0) {
const providerRegistry: Option<any> = await apiPromise.query.msa.providerToRegistryEntry(msaInfo.msaId);
if (providerRegistry.isSome) {
const details: any = (await apiPromise.query.capacity.capacityLedger(msaInfo.msaId)).unwrapOrDefault();
capacityDetails = {
remainingCapacity: details.remainingCapacity.toBigInt(),
totalTokensStaked: details.totalTokensStaked.toBigInt(),
totalCapacityIssued: details.totalCapacityIssued.toBigInt(),
lastReplenishedEpoch: details.lastReplenishedEpoch.toBigInt(),
};
}
export type CapacityDetails = {
remainingCapacity: bigint;
totalTokensStaked: bigint;
totalCapacityIssued: bigint;
lastReplenishedEpoch: bigint;
};

export async function getCapacityInfo(apiPromise: ApiPromise, msaId: number): Promise<CapacityDetails> {
let capacityDetails: CapacityDetails = {
remainingCapacity: 0n,
totalCapacityIssued: 0n,
totalTokensStaked: 0n,
lastReplenishedEpoch: 0n,
};

const providerRegistry: Option<any> = await apiPromise.query.msa.providerToRegistryEntry(msaId);

if (providerRegistry.isSome) {
const details: any = (await apiPromise.query.capacity.capacityLedger(msaId)).unwrapOrDefault();
capacityDetails = {
remainingCapacity: details.remainingCapacity.toBigInt(),
totalTokensStaked: details.totalTokensStaked.toBigInt(),
totalCapacityIssued: details.totalCapacityIssued.toBigInt(),
lastReplenishedEpoch: details.lastReplenishedEpoch.toBigInt(),
};
}
return { msaInfo, epochNumber, capacityDetails };

return capacityDetails;
}
12 changes: 1 addition & 11 deletions test/e2e/page.test.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { cleanup, fireEvent, render, waitFor } from '@testing-library/svelte';
import '@testing-library/jest-dom';
import Page from '$routes/+page.svelte';

// global.alert = () => {};
// vitest mocking
globalThis.alert = () => {};

const getByTextContent = (text) => {
// Passing function to `getByText`
return screen.getByText((content, element) => {
const hasText = (element) => element.textContent === text;
const elementHasText = hasText(element);
const childrenDontHaveText = Array.from(element?.children || []).every((child) => !hasText(child));
return elementHasText && childrenDontHaveText;
});
};

describe('End to End Tests', () => {
// TODO: @testing-library/svelte claims to add this automatically but it doesn't work without explicit afterEach
afterEach(() => cleanup());
Expand Down
1 change: 0 additions & 1 deletion test/unit-and-integration/capacity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { cleanup, render, waitFor } from '@testing-library/svelte';
import '@testing-library/jest-dom';
import { storeChainInfo, dotApi } from '../../src/lib/stores';
import Capacity from '$components/Capacity.svelte';
import { getByTextContent } from '../helpers';
import { user } from '../../src/lib/stores/userStore';
import { ChainInfo } from '../../src/lib/storeTypes';

Expand Down
2 changes: 1 addition & 1 deletion test/unit-and-integration/provider.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { cleanup, render, waitFor } from '@testing-library/svelte';
import { cleanup, render } from '@testing-library/svelte';
import '@testing-library/jest-dom';
import { dotApi, storeCurrentAction, storeChainInfo } from '../../src/lib/stores';
import { user } from '../../src/lib/stores/userStore';
Expand Down

0 comments on commit aada014

Please sign in to comment.