Skip to content

Commit

Permalink
prime sdk updated, add function getSupportedAssets()
Browse files Browse the repository at this point in the history
  • Loading branch information
Rana Khoury authored and Rana Khoury committed May 17, 2024
1 parent bc5d46f commit a21b057
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 55 deletions.
62 changes: 43 additions & 19 deletions __tests__/hooks/useEtherspotAssets.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,51 @@ const ethersProvider = new ethers.providers.JsonRpcProvider('http://localhost:85
const provider = new ethers.Wallet.createRandom().connect(ethersProvider);

describe('useEtherspotAssets()', () => {
it('returns assets', async () => {
const wrapper = ({ children }) => (
<EtherspotTransactionKit provider={provider}>
{children}
</EtherspotTransactionKit>
);

const { result, rerender } = renderHook(({ chainId }) => useEtherspotAssets(chainId), {
initialProps: { chainId: 1 },
wrapper,
describe('getAssets()', () => {
it('returns assets', async () => {
const wrapper = ({ children }) => (
<EtherspotTransactionKit provider={provider}>
{children}
</EtherspotTransactionKit>
);

const { result, rerender } = renderHook(({ chainId }) => useEtherspotAssets(chainId), {
initialProps: { chainId: 1 },
wrapper,
});

// wait for assets to be fetched for chain ID 1
await waitFor(() => expect(result.current).not.toBeNull());
const assetsMainnet = await result.current.getAssets();
expect(assetsMainnet.length).toEqual(3);

// rerender with different chain ID 137
rerender({ chainId: 137 });

const assetsPolygon = await result.current.getAssets();
expect(assetsPolygon.length).toEqual(1);
});
})

// wait for assets to be fetched for chain ID 1
await waitFor(() => expect(result.current).not.toBeNull());
const assetsMainnet = await result.current.getAssets();
expect(assetsMainnet.length).toEqual(3);
describe('getSupportedAssets()', () => {
it('returns all supported assets for chain ID 1', async () => {
const wrapper = ({ children }) => (
<EtherspotTransactionKit provider={provider}>
{children}
</EtherspotTransactionKit>
);

// rerender with different chain ID 137
rerender({ chainId: 137 });
const { result } = renderHook(({ chainId }) => useEtherspotAssets(chainId), {
initialProps: { chainId: 1 },
wrapper,
});

const assetsPolygon = await result.current.getAssets();
expect(assetsPolygon.length).toEqual(1);
// wait for assets to be fetched for chain ID 1
await waitFor(() => expect(result.current).not.toBeNull());
const assetsMainnet = await result.current.getSupportedAssets(1);
expect(assetsMainnet.length).toBeGreaterThanOrEqual(1);

});
});
})

});
12 changes: 5 additions & 7 deletions example/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 20 additions & 9 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
IEstimatedBatches, ISentBatches,
SentBatch,
useEtherspot,
// useEtherspotAssets,
useEtherspotTransactions,
useWalletAddress,
} from '@etherspot/transaction-kit';
Expand Down Expand Up @@ -77,7 +78,8 @@ const exampleCode = {
const App = () => {
const [activeTab, setActiveTab] = useState(tabs.SINGLE_TRANSACTION);
const { batches, estimate, send } = useEtherspotTransactions();
const { getSdk } = useEtherspot();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { getDataService, chainId: etherspotChainId } = useEtherspot();
const [balancePerAddress, setBalancePerAddress] = useState({
[walletAddressByName.Alice]: '',
[walletAddressByName.Bob]: '',
Expand All @@ -89,6 +91,11 @@ const App = () => {
const [isSending, setIsSending] = useState(false);
const etherspotPrimeAddress = useWalletAddress();

// // TO REMOVE - for testing purposes
// const { getSupportedAssets } = useEtherspotAssets();
// const allSupportedAssets = getSupportedAssets();
// console.log(allSupportedAssets)

const batchesTreeView = batches.map((batchGroup, id1) => ({
...batchGroup,
treeNodeId: `batch-group-${batchGroup.id ?? id1}`,
Expand Down Expand Up @@ -119,6 +126,7 @@ const App = () => {

useEffect(() => {
setExpanded(batchesTreeViewExpandedIds);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [batches]);

const handleToggle = (event: React.SyntheticEvent, nodeIds: string[]) => setExpanded(nodeIds);
Expand Down Expand Up @@ -155,7 +163,7 @@ const App = () => {
let expired = false;

const refreshBalances = async () => {
const sdk = await getSdk(+(process.env.REACT_APP_CHAIN_ID as string));
const dataServices = getDataService()

const updatedBalances = {
[walletAddressByName.Alice]: 'N/A',
Expand All @@ -168,7 +176,10 @@ const App = () => {
}

await Promise.all(Object.keys(updatedBalances).map(async (address) => {
const balances = await sdk?.getAccountBalances({ account: address });
const balances = await dataServices.getAccountBalances({
account: address,
chainId: +(process.env.REACT_APP_CHAIN_ID as string)
});
const balance = balances && balances.items.find(({ token }) => token === null);
if (balance) updatedBalances[address] = ethers.utils.formatEther(balance.balance);
}));
Expand All @@ -183,7 +194,8 @@ const App = () => {
return () => {
expired = true;
}
}, [getSdk, etherspotPrimeAddress]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [etherspotPrimeAddress]);

const estimationFailed = estimated?.some((
estimatedGroup,
Expand All @@ -197,18 +209,17 @@ const App = () => {
</Typography>
<Chip
label={
`My balance: ${
etherspotPrimeAddress && balancePerAddress[etherspotPrimeAddress]
? `${balancePerAddress[etherspotPrimeAddress]} MATIC`
: 'Loading...'
`My balance: ${etherspotPrimeAddress && balancePerAddress[etherspotPrimeAddress]
? `${Number(balancePerAddress[etherspotPrimeAddress]).toFixed(4)} ETH`
: 'Loading...'
}`
}
variant={'outlined'}
style={{ marginRight: 10, marginTop: 10 }}
/>
{Object.keys(walletAddressByName).map((addressName: string) => {
const address = walletAddressByName[addressName as keyof typeof walletAddressByName];
const balancePart = `balance: ${balancePerAddress[address] ? `${balancePerAddress[address]} MATIC` : 'Loading...'}`;
const balancePart = `balance: ${balancePerAddress[address] ? `${Number(balancePerAddress[address]).toFixed(4)} ETH` : 'Loading...'}`;
const chipLabel = `${addressName} ${balancePart}`;
return (
<Chip
Expand Down
30 changes: 15 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"homepage": "https://github.com/etherspot/transaction-kit#readme",
"dependencies": {
"@etherspot/eip1271-verification-util": "0.1.2",
"@etherspot/prime-sdk": "1.6.4",
"@etherspot/prime-sdk": "^1.8.1",
"buffer": "^6.0.3",
"ethers": "^5.6.9",
"lodash": "^4.17.21"
Expand All @@ -42,7 +42,7 @@
"@lifi/types": "^9.2.0",
"@rollup/plugin-replace": "^5.0.2",
"@rollup/plugin-typescript": "^8.3.3",
"@testing-library/react": "^14.0.0",
"@testing-library/react": "^14.3.1",
"@types/jest": "^29.2.5",
"@types/lodash.uniq": "^4.5.7",
"@types/react": "^18.0.15",
Expand All @@ -54,11 +54,11 @@
"react": "^18.2.0",
"react-test-renderer": "^18.2.0",
"rimraf": "^5.0.1",
"rollup": "^2.76.0",
"rollup": "^2.79.1",
"rollup-plugin-dts": "^4.2.3",
"typescript": "^4.7.4"
},
"peerDependencies": {
"react": ">=16.13.0"
}
}
}
21 changes: 20 additions & 1 deletion src/hooks/useEtherspotAssets.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useMemo } from 'react';
import { TokenListToken } from '@etherspot/prime-sdk/dist/sdk/data';
import { BridgingProvider, Token, TokenListToken } from '@etherspot/prime-sdk/dist/sdk/data';

// hooks
import useEtherspot from './useEtherspot';

interface IEtherspotAssetsHook {
getAssets: (chainId?: number) => Promise<TokenListToken[]>;
getSupportedAssets: (chainId?: number, bridgingProvider?: BridgingProvider) => Promise<Token[]>
}

/**
Expand Down Expand Up @@ -44,8 +45,26 @@ const useEtherspotAssets = (chainId?: number): IEtherspotAssetsHook => {
return assets;
};

const getSupportedAssets = async (chainId?: number, bridgingProvider?: BridgingProvider): Promise<Token[]> => {
let supportedAssets: Token[] = [];

try {
const dataService = getDataService();
supportedAssets = await dataService.getSupportedAssets({ chainId, provider: bridgingProvider });
} catch (e) {
console.warn(
`Sorry, an error occurred whilst trying to fetch supported Etherspot assets.`
+ ` Please try again. Error:`,
e,
);
}

return supportedAssets;
};

return ({
getAssets,
getSupportedAssets,
});
};

Expand Down

0 comments on commit a21b057

Please sign in to comment.