@avalabs/evm-module 0.0.2 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/.turbo/turbo-build.log +10 -10
  2. package/.turbo/turbo-lint.log +1 -1
  3. package/.turbo/turbo-test.log +12 -3
  4. package/CHANGELOG.md +30 -0
  5. package/dist/index.cjs +14 -2
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +13 -3
  8. package/dist/index.d.ts +13 -3
  9. package/dist/index.js +10 -2
  10. package/dist/index.js.map +1 -1
  11. package/package.json +17 -4
  12. package/src/handlers/get-network-fee.test.ts +38 -0
  13. package/src/handlers/get-network-fee.ts +41 -0
  14. package/src/handlers/get-transaction-history/converters/etherscan-transaction-converter/convert-transaction-erc20.ts +51 -0
  15. package/src/handlers/get-transaction-history/converters/etherscan-transaction-converter/convert-transaction-normal.ts +58 -0
  16. package/src/handlers/get-transaction-history/converters/etherscan-transaction-converter/get-transaction-from-etherscan.test.ts +116 -0
  17. package/src/handlers/get-transaction-history/converters/etherscan-transaction-converter/get-transaction-from-etherscan.ts +65 -0
  18. package/src/handlers/get-transaction-history/converters/evm-transaction-converter/convert-transaction.ts +47 -0
  19. package/src/handlers/get-transaction-history/converters/evm-transaction-converter/get-nft-metadata.ts +35 -0
  20. package/src/handlers/get-transaction-history/converters/evm-transaction-converter/get-sender-info.ts +38 -0
  21. package/src/handlers/get-transaction-history/converters/evm-transaction-converter/get-tokens.ts +107 -0
  22. package/src/handlers/get-transaction-history/converters/evm-transaction-converter/get-transaction-from-glacier.test.ts +213 -0
  23. package/src/handlers/get-transaction-history/converters/evm-transaction-converter/get-transactions-from-glacier.ts +60 -0
  24. package/src/handlers/get-transaction-history/converters/evm-transaction-converter/get-tx-type.ts +48 -0
  25. package/src/handlers/get-transaction-history/index.test.ts +50 -0
  26. package/src/handlers/get-transaction-history/index.ts +37 -0
  27. package/src/handlers/get-transaction-history/utils/get-explorer-address-by-network.ts +7 -0
  28. package/src/handlers/get-transaction-history/utils/get-small-image-for-nft.ts +16 -0
  29. package/src/handlers/get-transaction-history/utils/ipfs-resolver-with-fallback.ts +18 -0
  30. package/src/handlers/get-transaction-history/utils/is-ethereum-chain-id.ts +15 -0
  31. package/src/handlers/get-transaction-history/utils/resolve.ts +7 -0
  32. package/src/index.ts +32 -20
  33. package/src/manifest.json +1 -1
  34. package/src/types.ts +3 -0
  35. package/tsconfig.json +5 -1
package/package.json CHANGED
@@ -1,24 +1,37 @@
1
1
  {
2
2
  "name": "@avalabs/evm-module",
3
- "version": "0.0.2",
3
+ "version": "0.0.6",
4
4
  "main": "dist/index.cjs",
5
5
  "module": "dist/index.js",
6
6
  "typings": "dist/index.d.ts",
7
7
  "type": "module",
8
+ "dependencies": {
9
+ "@avalabs/utils-sdk": "v2.8.0-alpha.187",
10
+ "@avalabs/chains-sdk": "v2.8.0-alpha.187",
11
+ "@avalabs/etherscan-sdk": "v2.8.0-alpha.187",
12
+ "@avalabs/glacier-sdk": "v2.8.0-alpha.187",
13
+ "bn.js": "5.2.1",
14
+ "lodash.startcase": "4.4.0",
15
+ "@avalabs/vm-module-types": "0.0.6"
16
+ },
8
17
  "devDependencies": {
18
+ "@types/bn.js": "5.1.5",
9
19
  "@types/jest": "29.5.7",
10
- "@types/lodash": "4.14.201",
20
+ "@types/lodash.startcase": "4.4.9",
11
21
  "jest": "29.7.0",
12
22
  "ts-jest": "29.1.1",
13
23
  "tsup": "7.2.0",
14
- "@internal/types": "0.0.1",
24
+ "ethers": "6.8.1",
15
25
  "@internal/tsup-config": "0.0.1",
16
26
  "eslint-config-custom": "0.0.1"
17
27
  },
28
+ "peerDependencies": {
29
+ "ethers": "^6.8.1"
30
+ },
18
31
  "scripts": {
19
32
  "build": "tsup",
20
33
  "lint": "eslint \"src/**/*.ts\"",
21
- "test": "jest --passWithNoTests",
34
+ "test": "jest",
22
35
  "test:watch": "jest --watch"
23
36
  }
24
37
  }
@@ -0,0 +1,38 @@
1
+ import { getNetworkFee } from './get-network-fee';
2
+ import { FeeData, JsonRpcProvider } from 'ethers';
3
+
4
+ describe('get-network-fee', () => {
5
+ it("should throw error if provider.getFeeData() doesn't return eip-1559 compatible fees", async () => {
6
+ jest.spyOn(JsonRpcProvider.prototype, 'getFeeData').mockImplementationOnce(async () => {
7
+ return {
8
+ maxFeePerGas: null,
9
+ } as FeeData;
10
+ });
11
+ const provider = new JsonRpcProvider();
12
+ await expect(getNetworkFee(provider)).rejects.toThrow('Pre-EIP-1559 networks are not supported');
13
+ });
14
+
15
+ it('should return correct network fees based on maxFeePerGas returned from provider.getFeeData', async () => {
16
+ jest.spyOn(JsonRpcProvider.prototype, 'getFeeData').mockImplementationOnce(async () => {
17
+ return {
18
+ maxFeePerGas: 1000000000n, //1 gWei
19
+ } as FeeData;
20
+ });
21
+ const provider = new JsonRpcProvider();
22
+ await expect(getNetworkFee(provider)).resolves.toEqual({
23
+ baseFee: 1000000000n,
24
+ low: {
25
+ maxFeePerGas: 1500000000n,
26
+ maxPriorityFeePerGas: 500000000n,
27
+ },
28
+ medium: {
29
+ maxFeePerGas: 3000000000n,
30
+ maxPriorityFeePerGas: 2000000000n,
31
+ },
32
+ high: {
33
+ maxFeePerGas: 4000000000n,
34
+ maxPriorityFeePerGas: 3000000000n,
35
+ },
36
+ });
37
+ });
38
+ });
@@ -0,0 +1,41 @@
1
+ import { JsonRpcProvider } from 'ethers';
2
+ import type { NetworkFees } from '@avalabs/vm-module-types';
3
+
4
+ const DEFAULT_PRESETS = {
5
+ LOW: 1n,
6
+ MEDIUM: 4n,
7
+ HIGH: 6n,
8
+ };
9
+
10
+ const BASE_PRIORITY_FEE_WEI = 500000000n; //0.5 GWei
11
+
12
+ /**
13
+ * Returns {@link NetworkFees} based on {@link DEFAULT_PRESETS} multipliers.
14
+ * @param provider
15
+ * @throws Error if provider does not support eip-1559
16
+ */
17
+ export async function getNetworkFee(provider: JsonRpcProvider): Promise<NetworkFees> {
18
+ const { maxFeePerGas: maxFeePerGasInWei } = await provider.getFeeData();
19
+ if (!maxFeePerGasInWei) {
20
+ throw new Error('Pre-EIP-1559 networks are not supported');
21
+ }
22
+
23
+ const lowMaxTip = BASE_PRIORITY_FEE_WEI * DEFAULT_PRESETS.LOW;
24
+ const mediumMaxTip = BASE_PRIORITY_FEE_WEI * DEFAULT_PRESETS.MEDIUM;
25
+ const highMaxTip = BASE_PRIORITY_FEE_WEI * DEFAULT_PRESETS.HIGH;
26
+ return {
27
+ baseFee: maxFeePerGasInWei,
28
+ low: {
29
+ maxFeePerGas: maxFeePerGasInWei + lowMaxTip,
30
+ maxPriorityFeePerGas: lowMaxTip,
31
+ },
32
+ medium: {
33
+ maxFeePerGas: maxFeePerGasInWei + mediumMaxTip,
34
+ maxPriorityFeePerGas: mediumMaxTip,
35
+ },
36
+ high: {
37
+ maxFeePerGas: maxFeePerGasInWei + highMaxTip,
38
+ maxPriorityFeePerGas: highMaxTip,
39
+ },
40
+ };
41
+ }
@@ -0,0 +1,51 @@
1
+ import type { Erc20Tx } from '@avalabs/etherscan-sdk';
2
+ import { TokenType, TransactionType, type Transaction } from '@avalabs/vm-module-types';
3
+ import { balanceToDisplayValue } from '@avalabs/utils-sdk';
4
+ import { getExplorerAddressByNetwork } from '../../utils/get-explorer-address-by-network';
5
+ import { BN } from 'bn.js';
6
+
7
+ export function convertTransactionERC20({
8
+ tx,
9
+ address,
10
+ explorerUrl,
11
+ chainId,
12
+ }: {
13
+ tx: Erc20Tx;
14
+ address: string;
15
+ chainId: number;
16
+ explorerUrl: string;
17
+ }): Transaction {
18
+ const isSender = tx.from.toLowerCase() === address.toLowerCase();
19
+ const timestamp = parseInt(tx.timeStamp) * 1000;
20
+ const decimals = parseInt(tx.tokenDecimal);
21
+ const amountBN = new BN(tx.value);
22
+ const amountDisplayValue = balanceToDisplayValue(amountBN, decimals);
23
+ const { from, to, gasPrice, gasUsed, hash, tokenDecimal, tokenName, tokenSymbol } = tx;
24
+ const txType = isSender ? TransactionType.SEND : TransactionType.RECEIVE;
25
+ const explorerLink = getExplorerAddressByNetwork(explorerUrl, hash);
26
+
27
+ return {
28
+ isIncoming: !isSender,
29
+ isOutgoing: isSender,
30
+ isContractCall: false,
31
+ timestamp,
32
+ hash,
33
+ isSender,
34
+ from,
35
+ to,
36
+ tokens: [
37
+ {
38
+ decimal: tokenDecimal,
39
+ name: tokenName,
40
+ symbol: tokenSymbol,
41
+ type: TokenType.ERC20,
42
+ amount: amountDisplayValue,
43
+ },
44
+ ],
45
+ gasUsed,
46
+ gasPrice,
47
+ chainId: chainId.toString(),
48
+ txType,
49
+ explorerLink,
50
+ };
51
+ }
@@ -0,0 +1,58 @@
1
+ import type { NormalTx } from '@avalabs/etherscan-sdk';
2
+ import { TokenType, TransactionType, type NetworkToken, type Transaction } from '@avalabs/vm-module-types';
3
+ import { balanceToDisplayValue } from '@avalabs/utils-sdk';
4
+ import { BN } from 'bn.js';
5
+ import { getExplorerAddressByNetwork } from '../../utils/get-explorer-address-by-network';
6
+
7
+ export const convertTransactionNormal = ({
8
+ tx,
9
+ networkToken,
10
+ chainId,
11
+ explorerUrl,
12
+ address,
13
+ }: {
14
+ tx: NormalTx;
15
+ networkToken: NetworkToken;
16
+ chainId: number;
17
+ explorerUrl: string;
18
+ address: string;
19
+ }): Transaction => {
20
+ const isSender = tx.from.toLowerCase() === address.toLowerCase();
21
+ const timestamp = parseInt(tx.timeStamp) * 1000;
22
+ const decimals = networkToken.decimals;
23
+ const amountBN = new BN(tx.value);
24
+ const amountDisplayValue = balanceToDisplayValue(amountBN, decimals);
25
+ const txType = isSender ? TransactionType.SEND : TransactionType.RECEIVE;
26
+
27
+ const { from, to, gasPrice, gasUsed, hash } = tx;
28
+ const explorerLink = getExplorerAddressByNetwork(explorerUrl, hash);
29
+
30
+ return {
31
+ isIncoming: !isSender,
32
+ isOutgoing: isSender,
33
+ isContractCall: isContractCall(tx),
34
+ timestamp,
35
+ hash,
36
+ isSender,
37
+ from,
38
+ to,
39
+ tokens: [
40
+ {
41
+ decimal: decimals.toString(),
42
+ name: networkToken.name,
43
+ symbol: networkToken.symbol,
44
+ amount: amountDisplayValue,
45
+ type: TokenType.NATIVE,
46
+ },
47
+ ],
48
+ gasUsed,
49
+ gasPrice,
50
+ chainId: chainId.toString(),
51
+ txType,
52
+ explorerLink,
53
+ };
54
+ };
55
+
56
+ function isContractCall(tx: NormalTx): boolean {
57
+ return tx.input !== '0x';
58
+ }
@@ -0,0 +1,116 @@
1
+ import { TokenType } from '@avalabs/vm-module-types';
2
+ import { getTransactionFromEtherscan } from './get-transaction-from-etherscan';
3
+ import type { Erc20Tx, NormalTx } from '@avalabs/etherscan-sdk';
4
+
5
+ const mockNormalTxs: NormalTx[] = [
6
+ {
7
+ blockNumber: 'blockNumber',
8
+ timeStamp: 'timeStamp',
9
+ hash: 'normalTxHash',
10
+ nonce: 'nonce',
11
+ blockHash: 'blockHash',
12
+ transactionIndex: 'transactionIndex',
13
+ from: 'from',
14
+ to: 'to',
15
+ value: '1',
16
+ gas: '1',
17
+ gasPrice: '1',
18
+ isError: 'isError',
19
+ txreceipt_status: 'txreceipt_status',
20
+ input: 'input',
21
+ contractAddress: 'contractAddress',
22
+ cumulativeGasUsed: '1',
23
+ gasUsed: '1',
24
+ confirmations: 'confirmations',
25
+ },
26
+ ];
27
+
28
+ const mockErc20Txs: Erc20Tx[] = [
29
+ {
30
+ blockNumber: 'blockNumber',
31
+ timeStamp: 'timeStamp',
32
+ hash: 'erc20Hash',
33
+ nonce: 'nonce',
34
+ blockHash: 'blockHash',
35
+ from: 'from',
36
+ contractAddress: 'contractAddress',
37
+ to: 'to',
38
+ value: '1',
39
+ tokenName: 'tokenName',
40
+ tokenSymbol: 'tokenSymbol',
41
+ tokenDecimal: '1',
42
+ transactionIndex: 'transactionIndex',
43
+ gas: '1',
44
+ gasPrice: '1',
45
+ input: 'input',
46
+ cumulativeGasUsed: '1',
47
+ gasUsed: '1',
48
+ confirmations: 'confirmations',
49
+ },
50
+ ];
51
+ // const mockTransactions = jest.fn();
52
+ jest.mock('@avalabs/etherscan-sdk', () => ({
53
+ getNormalTxs: () => mockNormalTxs,
54
+ getErc20Txs: () => mockErc20Txs,
55
+ }));
56
+
57
+ describe('get-transaction-from-etherscan', () => {
58
+ it('should have returned 1 normal transaction and 1 erc20 transaction', async () => {
59
+ const result = await getTransactionFromEtherscan({
60
+ isTestnet: false,
61
+ chainId: 1,
62
+ networkToken: {
63
+ name: 'networkToken',
64
+ symbol: 'networkToken',
65
+ decimals: 1,
66
+ description: 'description',
67
+ logoUri: 'logoUri',
68
+ },
69
+ explorerUrl: 'explorerUrl',
70
+ address: 'address',
71
+ nextPageToken: '',
72
+ offset: 1,
73
+ });
74
+ expect(result.transactions.length).toEqual(2);
75
+ });
76
+
77
+ it('should have returned 1 normal if nextPageToken contains only normal', async () => {
78
+ const result = await getTransactionFromEtherscan({
79
+ isTestnet: false,
80
+ chainId: 1,
81
+ networkToken: {
82
+ name: 'networkToken',
83
+ symbol: 'networkToken',
84
+ decimals: 1,
85
+ description: 'description',
86
+ logoUri: 'logoUri',
87
+ },
88
+ explorerUrl: 'explorerUrl',
89
+ address: 'address',
90
+ nextPageToken: JSON.stringify({ page: 1, queries: ['normal'] }),
91
+ offset: 1,
92
+ });
93
+ expect(result.transactions.length).toEqual(1);
94
+ expect(result.transactions[0]?.tokens[0]?.type).toEqual(TokenType.NATIVE);
95
+ });
96
+
97
+ it('should have returned 1 erc20 if nextPageToken contains only erc20', async () => {
98
+ const result = await getTransactionFromEtherscan({
99
+ isTestnet: false,
100
+ chainId: 1,
101
+ networkToken: {
102
+ name: 'networkToken',
103
+ symbol: 'networkToken',
104
+ decimals: 1,
105
+ description: 'description',
106
+ logoUri: 'logoUri',
107
+ },
108
+ explorerUrl: 'explorerUrl',
109
+ address: 'address',
110
+ nextPageToken: JSON.stringify({ page: 1, queries: ['erc20'] }),
111
+ offset: 1,
112
+ });
113
+ expect(result.transactions.length).toEqual(1);
114
+ expect(result.transactions[0]?.tokens[0]?.type).toEqual(TokenType.ERC20);
115
+ });
116
+ });
@@ -0,0 +1,65 @@
1
+ import { convertTransactionNormal } from './convert-transaction-normal';
2
+ import { convertTransactionERC20 } from './convert-transaction-erc20';
3
+ import type { GetTransactionHistory, TransactionHistoryResponse } from '@avalabs/vm-module-types';
4
+ import { getErc20Txs, getNormalTxs } from '@avalabs/etherscan-sdk';
5
+
6
+ interface EtherscanPagination {
7
+ queries: ('normal' | 'erc20')[];
8
+ page?: number;
9
+ }
10
+
11
+ export const getTransactionFromEtherscan = async ({
12
+ isTestnet,
13
+ chainId,
14
+ networkToken,
15
+ explorerUrl,
16
+ address,
17
+ nextPageToken,
18
+ offset,
19
+ }: GetTransactionHistory): Promise<TransactionHistoryResponse> => {
20
+ /*
21
+ Using JSON for nextPageToken because this function is managing both the Normal
22
+ and ERC20 queries. It encodes the current page and the queries that should be
23
+ run. For example, if 'normal' has no more records to fetch then it will be
24
+ excluded from the list and the JSON will be something like:
25
+ { page: 3, queries: ['erc20'] }
26
+ */
27
+ const parsedPageToken = nextPageToken ? (JSON.parse(nextPageToken) as EtherscanPagination) : undefined;
28
+ const page = parsedPageToken?.page || 1;
29
+ const queries = parsedPageToken?.queries || ['normal', 'erc20'];
30
+
31
+ const normalHist = (queries.includes('normal') ? await getNormalTxs(address, !isTestnet, { page, offset }) : []).map(
32
+ (tx) => convertTransactionNormal({ tx, chainId, networkToken, explorerUrl, address }),
33
+ );
34
+
35
+ const erc20Hist = (
36
+ queries.includes('erc20')
37
+ ? await getErc20Txs(address, !isTestnet, undefined, {
38
+ page,
39
+ offset,
40
+ })
41
+ : []
42
+ ).map((tx) =>
43
+ convertTransactionERC20({
44
+ tx,
45
+ address,
46
+ explorerUrl,
47
+ chainId,
48
+ }),
49
+ );
50
+
51
+ // Filter erc20 transactions from normal tx list
52
+ const erc20TxHashes = erc20Hist.map((tx) => tx.hash);
53
+ const filteredNormalTxs = normalHist.filter((tx) => {
54
+ return !erc20TxHashes.includes(tx.hash);
55
+ });
56
+
57
+ const next: EtherscanPagination = { queries: [], page: page + 1 };
58
+ if (normalHist.length) next.queries.push('normal');
59
+ if (erc20Hist.length) next.queries.push('erc20');
60
+
61
+ return {
62
+ transactions: [...filteredNormalTxs, ...erc20Hist],
63
+ nextPageToken: next.queries.length ? JSON.stringify(next) : '', // stop pagination
64
+ };
65
+ };
@@ -0,0 +1,47 @@
1
+ import type { Transaction, NetworkToken } from '@avalabs/vm-module-types';
2
+ import { getTxType } from './get-tx-type';
3
+ import { getSenderInfo } from './get-sender-info';
4
+ import { getTokens } from './get-tokens';
5
+ import { getExplorerAddressByNetwork } from '../../utils/get-explorer-address-by-network';
6
+ import type { TransactionDetails } from '@avalabs/glacier-sdk';
7
+ import { NonContractCallTypes } from '../../../../types';
8
+
9
+ type ConvertTransactionParams = {
10
+ transactions: TransactionDetails;
11
+ explorerUrl: string;
12
+ networkToken: NetworkToken;
13
+ chainId: number;
14
+ address: string;
15
+ };
16
+
17
+ export const convertTransaction = async ({
18
+ transactions,
19
+ explorerUrl,
20
+ networkToken,
21
+ chainId,
22
+ address,
23
+ }: ConvertTransactionParams): Promise<Transaction> => {
24
+ const tokens = await getTokens(transactions, networkToken);
25
+ const txType = getTxType(transactions, address, tokens);
26
+ const { isOutgoing, isIncoming, isSender, from, to } = getSenderInfo(txType, transactions, address);
27
+ const { blockTimestamp, txHash: hash, gasPrice, gasUsed } = transactions.nativeTransaction;
28
+ const explorerLink = getExplorerAddressByNetwork(explorerUrl, hash);
29
+ const isContractCall = !NonContractCallTypes.includes(txType);
30
+
31
+ return {
32
+ isContractCall,
33
+ isIncoming,
34
+ isOutgoing,
35
+ isSender,
36
+ timestamp: blockTimestamp * 1000, // s to ms
37
+ hash,
38
+ from,
39
+ to,
40
+ tokens,
41
+ gasPrice,
42
+ gasUsed,
43
+ chainId: chainId.toString(),
44
+ txType,
45
+ explorerLink,
46
+ };
47
+ };
@@ -0,0 +1,35 @@
1
+ import { ipfsResolverWithFallback } from '../../utils/ipfs-resolver-with-fallback';
2
+
3
+ interface NftMetadata {
4
+ attributes?: string;
5
+ name?: string;
6
+ image?: string;
7
+ description?: string;
8
+ }
9
+
10
+ async function fetchWithTimeout(uri: string, timeout = 5000) {
11
+ const controller = new AbortController();
12
+ setTimeout(() => controller.abort(), timeout);
13
+
14
+ return fetch(uri, { signal: controller.signal });
15
+ }
16
+
17
+ export async function getNftMetadata(tokenUri: string) {
18
+ let data: NftMetadata = {};
19
+ if (!tokenUri) {
20
+ return {};
21
+ } else if (tokenUri.startsWith('data:application/json;base64,')) {
22
+ const value = tokenUri.substring(29);
23
+ try {
24
+ const json = Buffer.from(value, 'base64').toString();
25
+ data = JSON.parse(json);
26
+ } catch {
27
+ data = {};
28
+ }
29
+ } else {
30
+ data = await fetchWithTimeout(ipfsResolverWithFallback(tokenUri))
31
+ .then((r) => r.json())
32
+ .catch(() => ({}));
33
+ }
34
+ return data;
35
+ }
@@ -0,0 +1,38 @@
1
+ import type { TransactionDetails } from '@avalabs/glacier-sdk';
2
+ import { TransactionType } from '@avalabs/vm-module-types';
3
+
4
+ export const getSenderInfo = (
5
+ txType: TransactionType,
6
+ { nativeTransaction, erc20Transfers, erc721Transfers }: TransactionDetails,
7
+ address: string,
8
+ ): { isOutgoing: boolean; isIncoming: boolean; isSender: boolean; from: string; to: string } => {
9
+ const isTransfer = txType === TransactionType.TRANSFER;
10
+ const isNativeSend = txType === TransactionType.SEND;
11
+ const isNativeReceive = txType === TransactionType.RECEIVE;
12
+ let from = nativeTransaction?.from?.address;
13
+ let to = nativeTransaction?.to?.address;
14
+
15
+ // Until multi tokens transaction is supported in UI, using from and to of the only token is helpful for UI
16
+ if (isTransfer && erc20Transfers && erc20Transfers[0]) {
17
+ from = erc20Transfers[0].from.address;
18
+ to = erc20Transfers[0].to.address;
19
+ }
20
+
21
+ if (isTransfer && erc721Transfers && erc721Transfers[0]) {
22
+ from = erc721Transfers[0].from.address;
23
+ to = erc721Transfers[0].to.address;
24
+ }
25
+
26
+ const isOutgoing = isNativeSend || (isTransfer && from === address);
27
+ const isIncoming = isNativeReceive || (isTransfer && to === address);
28
+
29
+ const isSender = from === address;
30
+
31
+ return {
32
+ isOutgoing,
33
+ isIncoming,
34
+ isSender,
35
+ from,
36
+ to,
37
+ };
38
+ };
@@ -0,0 +1,107 @@
1
+ import type { TransactionDetails } from '@avalabs/glacier-sdk';
2
+ import { balanceToDisplayValue } from '@avalabs/utils-sdk';
3
+ import { BN } from 'bn.js';
4
+ import type { TxToken, NetworkToken } from '@avalabs/vm-module-types';
5
+ import { TokenType } from '@avalabs/vm-module-types';
6
+ import { resolve } from '../../utils/resolve';
7
+ import { getNftMetadata } from './get-nft-metadata';
8
+ import { getSmallImageForNFT } from '../../utils/get-small-image-for-nft';
9
+ import { ipfsResolverWithFallback } from '../../utils/ipfs-resolver-with-fallback';
10
+
11
+ export const getTokens = async (
12
+ { nativeTransaction, erc20Transfers, erc721Transfers, erc1155Transfers }: TransactionDetails,
13
+ networkToken: NetworkToken,
14
+ ): Promise<TxToken[]> => {
15
+ const result: TxToken[] = [];
16
+
17
+ if (nativeTransaction.value !== '0') {
18
+ const decimal = networkToken.decimals;
19
+ const amountBN = new BN(nativeTransaction.value);
20
+ const amountDisplayValue = balanceToDisplayValue(amountBN, decimal);
21
+ result.push({
22
+ decimal: decimal.toString(),
23
+ name: networkToken.name,
24
+ symbol: networkToken.symbol,
25
+ amount: amountDisplayValue,
26
+ from: nativeTransaction.from,
27
+ to: nativeTransaction.to,
28
+ type: TokenType.NATIVE,
29
+ });
30
+ }
31
+
32
+ erc20Transfers?.forEach((erc20Transfer) => {
33
+ const decimals = erc20Transfer.erc20Token.decimals;
34
+ const amountBN = new BN(erc20Transfer.value);
35
+ const amountDisplayValue = balanceToDisplayValue(amountBN, decimals);
36
+
37
+ result.push({
38
+ decimal: decimals.toString(),
39
+ name: erc20Transfer.erc20Token.name,
40
+ symbol: erc20Transfer.erc20Token.symbol,
41
+ amount: amountDisplayValue,
42
+ from: erc20Transfer.from,
43
+ to: erc20Transfer.to,
44
+ imageUri: erc20Transfer.erc20Token.logoUri,
45
+ type: TokenType.ERC20,
46
+ });
47
+ });
48
+
49
+ if (erc721Transfers) {
50
+ await Promise.allSettled(
51
+ erc721Transfers.map(async (erc721Transfer) => {
52
+ const token = erc721Transfer.erc721Token;
53
+ const imageUri = await getImageUri(token.tokenUri, token.metadata.imageUri);
54
+
55
+ result.push({
56
+ name: erc721Transfer.erc721Token.name,
57
+ symbol: erc721Transfer.erc721Token.symbol,
58
+ amount: '1',
59
+ imageUri,
60
+ from: erc721Transfer.from,
61
+ to: erc721Transfer.to,
62
+ collectableTokenId: erc721Transfer.erc721Token.tokenId,
63
+ type: TokenType.ERC721,
64
+ });
65
+ }),
66
+ );
67
+ }
68
+
69
+ if (erc1155Transfers) {
70
+ await Promise.allSettled(
71
+ erc1155Transfers.map(async (erc1155Transfer) => {
72
+ const token = erc1155Transfer.erc1155Token;
73
+ const imageUri = await getImageUri(token.tokenUri, token.metadata.imageUri);
74
+
75
+ result.push({
76
+ name: erc1155Transfer.erc1155Token.metadata.name ?? '',
77
+ symbol: erc1155Transfer.erc1155Token.metadata.symbol ?? '',
78
+ amount: erc1155Transfer.value,
79
+ imageUri,
80
+ from: erc1155Transfer.from,
81
+ to: erc1155Transfer.to,
82
+ collectableTokenId: erc1155Transfer.erc1155Token.tokenId,
83
+ type: TokenType.ERC1155,
84
+ });
85
+ }),
86
+ );
87
+ }
88
+
89
+ return result;
90
+ };
91
+
92
+ const getImageUri = async (tokenUri: string, imageUri?: string): Promise<string> => {
93
+ if (imageUri) {
94
+ if (imageUri.startsWith('ipfs://')) {
95
+ return ipfsResolverWithFallback(imageUri);
96
+ } else {
97
+ return imageUri;
98
+ }
99
+ } else {
100
+ const [metadata, error] = await resolve(getNftMetadata(tokenUri));
101
+ if (error) {
102
+ return '';
103
+ } else {
104
+ return metadata.image ? getSmallImageForNFT(metadata.image) : '';
105
+ }
106
+ }
107
+ };