Skip to content

Commit

Permalink
Added 3 new chain APIs
Browse files Browse the repository at this point in the history
1- check account balance
2- get account from seed
3- replicate recent CIDs which uploads manifest for recent cids and clears the recent list from client
  • Loading branch information
ehsan6sha committed Nov 21, 2023
1 parent d053cad commit 4fdcf72
Show file tree
Hide file tree
Showing 3 changed files with 137 additions and 26 deletions.
44 changes: 19 additions & 25 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { clearCidsFromRecent } from '../../.history/src/protocols/fula_20231120182146';

import {
fula,
Expand Down Expand Up @@ -438,32 +437,27 @@ const App = () => {
/>

<Button
title={inprogress ? 'Putting & Getting...' : 'Check Account'}
title={inprogress ? 'Putting & Getting...' : 'Check Account Balance'}
onPress={async () => {
try {
if (initComplete) {
fula.checkConnection().then((r: any) => {
console.log('connection check');
console.log(r);
if (r) {
console.log('initialization is completed. check account');
blockchain
.checkAccountExists(
'5DAfEJDKAeejGCzw7kdvrzkhwyoNLZ1iSsq4LZkYPMMi6pgf'
)
.then((res: any) => {
console.log('replicationRequest created');
console.log(res);
})
.catch((e: any) => {
console.log('replicationRequest creation failed');
console.log(e);
});
}
});
} else {
console.log('wait for init to complete');
}
chainApi.init().then(async (api: any) => {
console.log('api created');
console.log('check account balance');
let accountId = await chainApi.getAccountIdFromSeed(
'0xde74b73a4e99c09ae760e7d05c1cf50bd166312fe1be6fb46609b690efb0e472'
);
console.log('account ID is ' + accountId);
chainApi
.checkAccountBalance(api, accountId)
.then((res: any) => {
console.log('account balance created');
console.log(res);
})
.catch((e: any) => {
console.log('account balance creation failed');
console.log(e);
});
});
} catch (e) {}
}}
color={inprogress ? 'green' : 'blue'}
Expand Down
44 changes: 43 additions & 1 deletion src/protocols/chain-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { default as EventTypes } from '../interfaces/lookup';

import { ApiPromise, WsProvider } from '@polkadot/api';
import { Keyring } from '@polkadot/keyring';
const { cryptoWaitReady } = require('@polkadot/util-crypto');
import type * as BType from '../types/blockchain';

const types = {
Expand Down Expand Up @@ -64,7 +65,7 @@ function createManifest(
export const batchUploadManifest = async (
api: ApiPromise | undefined,
seed: string,
cids_i: [string],
cids_i: string[],
poolId_i: number,
replicationFactor_i: number = 4
): Promise<{ hash: string }> => {
Expand Down Expand Up @@ -200,3 +201,44 @@ export const checkJoinRequest = async (
return Promise.reject(err);
}
};

/*
checkAccountExsists: This function takes accountId and checks if the account exists
*/
export const checkAccountBalance = async (
api: ApiPromise | undefined,
accountId: string
): Promise<string> => {
console.log('checkAcocuntExsists in react-native started');
try {
if (api === undefined) {
api = await init();
}
// Type guard to assure TypeScript that api is not undefined
if (!api?.query?.system?.account) {
throw new Error('Failed to initialize api or api.query.account');
}

let {
data: { free: balance },
} = await api.query.system.account(accountId);

if (balance && balance !== '0' && balance > 0) {
return Promise.resolve(balance.toHuman());
}
return Promise.resolve('0');
} catch (err) {
return Promise.reject(err);
}
};

export const getAccountIdFromSeed = async (seed: string): Promise<string> => {
try {
await cryptoWaitReady();
const keyring = new Keyring({ type: 'sr25519' });
const account = keyring.addFromUri(seed, { name: 'account' }, 'sr25519');
return Promise.resolve(account.address);
} catch (err) {
return Promise.reject(err);
}
};
75 changes: 75 additions & 0 deletions src/protocols/fula.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import Fula from '../interfaces/fulaNativeModule';
import {
init as chainApiInit,
batchUploadManifest,
checkAccountBalance,
getAccountIdFromSeed,
} from './chain-api';
import { ApiPromise } from '@polkadot/api';

/**
* Get gets the value corresponding to the given key from the local datastore.
Expand Down Expand Up @@ -326,3 +333,71 @@ export const setAuth = (peerId: string, allow: boolean): Promise<boolean> => {
export const isReady = (filesystemCheck: boolean = true): Promise<boolean> => {
return Fula.isReady(filesystemCheck);
};

/**
* replicate replicates data on the nework
*/
export const replicateRecentCids = async (
api: ApiPromise,
seed: string,
replicationNo: number = 4
): Promise<{ status: boolean; msg: string }> => {
let status = true;
let msg = '';
if (!api) {
api = await chainApiInit();
}
if (api) {
console.log('uploading manifests');
try {
let account = await getAccountIdFromSeed(seed);
const accountBal = await checkAccountBalance(api, account);
if (accountBal !== '0') {
const recentCids = await listRecentCidsAsString();
if (recentCids) {
const res = await batchUploadManifest(
api,
seed,
recentCids,
replicationNo
);
console.log('res received');
console.log(res);
if (res && res.hash) {
const signedBlock = await api.rpc.chain.getBlock(res.hash);
if (signedBlock?.block?.extrinsics?.length) {
await clearCidsFromRecent(recentCids);
} else {
status = false;
msg = 'block data is not found';
}
} else {
status = false;
msg = 'hash is not returned';
}
}
} else {
status = false;
msg = 'Account balance is not enough or account does not exists';
}
} catch (e: any) {
console.log('res failed');
console.log(e);
let errorMessage = '';

if (e instanceof Error) {
// If it's an Error instance, use the message property
errorMessage = e.message;
} else {
// If it's not an Error instance, convert it to string
errorMessage = e.toString();
}
status = false;
msg = errorMessage;
}
}

// Return a value (true/false) depending on the outcome of the function
// For example:
return { status: status, msg: msg }; // or false, depending on your logic
};

0 comments on commit 4fdcf72

Please sign in to comment.