@avalabs/avalanche-module 0.0.22 → 0.1.0

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.
package/src/env.ts DELETED
@@ -1,25 +0,0 @@
1
- import { Environment } from '@avalabs/vm-module-types';
2
-
3
- type Env = {
4
- glacierApiUrl: string;
5
- proxyApiUrl: string;
6
- };
7
-
8
- export const prodEnv: Env = {
9
- glacierApiUrl: 'https://glacier-api.avax.network',
10
- proxyApiUrl: 'https://proxy-api.avax.network',
11
- };
12
-
13
- export const devEnv: Env = {
14
- glacierApiUrl: 'https://glacier-api-dev.avax.network',
15
- proxyApiUrl: 'https://proxy-api-dev.avax.network',
16
- };
17
-
18
- export const getEnv = (environment: Environment): Env => {
19
- switch (environment) {
20
- case Environment.PRODUCTION:
21
- return prodEnv;
22
- case Environment.DEV:
23
- return devEnv;
24
- }
25
- };
@@ -1,91 +0,0 @@
1
- import type { AggregatedAssetAmount, PChainBalance } from '@avalabs/glacier-sdk';
2
- import { balanceToDisplayValue, bnToBig } from '@avalabs/utils-sdk';
3
- import { BN } from 'bn.js';
4
- import { calculateTotalBalance, getTokenValue } from './utils';
5
- import { TokenType, type NetworkToken, type TokenWithBalancePVM } from '@avalabs/vm-module-types';
6
-
7
- export const convertPChainBalance = ({
8
- balance,
9
- networkToken,
10
- priceInCurrency,
11
- marketCap,
12
- vol24,
13
- change24,
14
- coingeckoId,
15
- }: {
16
- balance: PChainBalance;
17
- networkToken: NetworkToken;
18
- priceInCurrency?: number;
19
- marketCap?: number;
20
- vol24?: number;
21
- change24?: number;
22
- coingeckoId: string;
23
- }): TokenWithBalancePVM => {
24
- const decimals = networkToken.decimals;
25
- const balancePerType: Record<string, number> = {};
26
-
27
- const balanceTypes: Record<string, AggregatedAssetAmount[]> = {
28
- unlockedUnstaked: balance.unlockedUnstaked,
29
- unlockedStaked: balance.unlockedStaked,
30
- pendingStaked: balance.pendingStaked,
31
- lockedStaked: balance.lockedStaked,
32
- lockedStakeable: balance.lockedStakeable,
33
- lockedPlatform: balance.lockedPlatform,
34
- atomicMemoryLocked: balance.atomicMemoryLocked,
35
- atomicMemoryUnlocked: balance.atomicMemoryUnlocked,
36
- };
37
-
38
- for (const balanceType in balanceTypes) {
39
- const balancesToAdd = balanceTypes[balanceType];
40
- if (!balancesToAdd || !balancesToAdd.length) {
41
- balancePerType[balanceType] = 0;
42
- continue;
43
- }
44
-
45
- balancesToAdd.forEach((uxto: AggregatedAssetAmount) => {
46
- const previousBalance = balancePerType[balanceType] ?? 0;
47
- const newBalance = previousBalance + Number(uxto.amount);
48
- balancePerType[balanceType] = newBalance;
49
- });
50
- }
51
-
52
- const available = balancePerType['unlockedUnstaked'] ? new BN(balancePerType['unlockedUnstaked']) : new BN(0);
53
- const availableInCurrency = priceInCurrency
54
- ? bnToBig(available, decimals).mul(priceInCurrency).toNumber()
55
- : undefined;
56
- const availableDisplayValue = balanceToDisplayValue(available, decimals);
57
- const totalBalance = calculateTotalBalance(balance);
58
- const balanceInCurrency = priceInCurrency
59
- ? bnToBig(totalBalance, decimals).mul(priceInCurrency).toNumber()
60
- : undefined;
61
- const balanceDisplayValue = balanceToDisplayValue(totalBalance, decimals);
62
-
63
- return {
64
- ...networkToken,
65
- type: TokenType.NATIVE,
66
- priceInCurrency,
67
- balance: totalBalance,
68
- balanceInCurrency,
69
- balanceDisplayValue,
70
- balanceCurrencyDisplayValue: balanceInCurrency?.toFixed(2),
71
- available,
72
- availableInCurrency,
73
- availableDisplayValue,
74
- availableCurrencyDisplayValue: availableInCurrency?.toFixed(2),
75
- utxos: balance,
76
- balancePerType: {
77
- lockedStaked: getTokenValue(decimals, balancePerType['lockedStaked']),
78
- lockedStakeable: getTokenValue(decimals, balancePerType['lockedStakeable']),
79
- lockedPlatform: getTokenValue(decimals, balancePerType['lockedPlatform']),
80
- atomicMemoryLocked: getTokenValue(decimals, balancePerType['atomicMemoryLocked']),
81
- atomicMemoryUnlocked: getTokenValue(decimals, balancePerType['atomicMemoryUnlocked']),
82
- unlockedUnstaked: getTokenValue(decimals, balancePerType['unlockedUnstaked']),
83
- unlockedStaked: getTokenValue(decimals, balancePerType['unlockedStaked']),
84
- pendingStaked: getTokenValue(decimals, balancePerType['pendingStaked']),
85
- },
86
- marketCap,
87
- vol24,
88
- change24,
89
- coingeckoId,
90
- };
91
- };
@@ -1,74 +0,0 @@
1
- import type { AggregatedAssetAmount, XChainBalances } from '@avalabs/glacier-sdk';
2
- import { balanceToDisplayValue, bnToBig } from '@avalabs/utils-sdk';
3
- import { calculateTotalBalance, getTokenValue } from './utils';
4
- import { TokenType, type NetworkToken, type TokenWithBalanceAVM } from '@avalabs/vm-module-types';
5
-
6
- export const convertXChainBalance = ({
7
- balance,
8
- networkToken,
9
- priceInCurrency,
10
- marketCap,
11
- vol24,
12
- change24,
13
- coingeckoId,
14
- }: {
15
- balance: XChainBalances;
16
- networkToken: NetworkToken;
17
- priceInCurrency?: number;
18
- marketCap?: number;
19
- vol24?: number;
20
- change24?: number;
21
- coingeckoId: string;
22
- }): TokenWithBalanceAVM => {
23
- const decimals = networkToken.decimals;
24
- const balancePerType: Record<string, number> = {};
25
-
26
- const balanceTypes: Record<string, AggregatedAssetAmount[]> = {
27
- unlocked: balance.unlocked,
28
- locked: balance.locked,
29
- atomicMemoryUnlocked: balance.atomicMemoryUnlocked,
30
- atomicMemoryLocked: balance.atomicMemoryLocked,
31
- };
32
-
33
- for (const balanceType in balanceTypes) {
34
- const balancesToAdd = balanceTypes[balanceType];
35
- if (!balancesToAdd || !balancesToAdd.length) {
36
- balancePerType[balanceType] = 0;
37
- continue;
38
- }
39
-
40
- balancesToAdd.forEach((uxto: AggregatedAssetAmount) => {
41
- const previousBalance = balancePerType[balanceType] ?? 0;
42
- const newBalance = previousBalance + Number(uxto.amount);
43
- balancePerType[balanceType] = newBalance;
44
- });
45
- }
46
-
47
- const totalBalance = calculateTotalBalance(balance);
48
- const balanceDisplayValue = balanceToDisplayValue(totalBalance, decimals);
49
- const balanceInCurrency = priceInCurrency
50
- ? bnToBig(totalBalance, decimals).mul(priceInCurrency).toNumber()
51
- : undefined;
52
- const balanceCurrencyDisplayValue = balanceInCurrency?.toFixed(2);
53
-
54
- return {
55
- ...networkToken,
56
- coingeckoId,
57
- type: TokenType.NATIVE,
58
- priceInCurrency,
59
- balance: totalBalance,
60
- balanceInCurrency,
61
- balanceDisplayValue,
62
- balanceCurrencyDisplayValue,
63
- utxos: balance,
64
- balancePerType: {
65
- unlocked: getTokenValue(decimals, balancePerType['unlocked']),
66
- locked: getTokenValue(decimals, balancePerType['locked']),
67
- atomicMemoryUnlocked: getTokenValue(decimals, balancePerType['atomicMemoryUnlocked']),
68
- atomicMemoryLocked: getTokenValue(decimals, balancePerType['atomicMemoryLocked']),
69
- },
70
- marketCap,
71
- vol24,
72
- change24,
73
- };
74
- };
@@ -1,100 +0,0 @@
1
- import {
2
- NetworkVMType,
3
- type GetBalancesParams,
4
- type GetBalancesResponse,
5
- type TokenWithBalanceAVM,
6
- type TokenWithBalancePVM,
7
- } from '@avalabs/vm-module-types';
8
- import { type AvalancheGlacierService } from '../../services/glacier-service/glacier-service';
9
- import {
10
- BlockchainId,
11
- Network,
12
- type ListPChainBalancesResponse,
13
- type ListXChainBalancesResponse,
14
- } from '@avalabs/glacier-sdk';
15
- import type { TokenService } from '@internal/utils';
16
- import { VsCurrencyType } from '@avalabs/coingecko-sdk';
17
- import { isPchainBalance, isXchainBalance } from './utils';
18
- import { convertPChainBalance } from './convert-p-chain-balance';
19
- import { convertXChainBalance } from './covnert-x-chain-balance';
20
-
21
- export const getBalances = async ({
22
- addresses,
23
- currency,
24
- network,
25
- glacierService,
26
- tokenService,
27
- }: GetBalancesParams & {
28
- glacierService: AvalancheGlacierService;
29
- tokenService: TokenService;
30
- }): Promise<GetBalancesResponse> => {
31
- const isHealthy = glacierService.isHealthy();
32
- if (!isHealthy) {
33
- return Promise.reject('Glacier is unhealthy. Try again later.');
34
- }
35
-
36
- const lowercaseCurrency = currency.toLowerCase();
37
- const address = addresses[0] ?? '';
38
- const networkToken = network.networkToken;
39
- const coingeckoId = network.pricingProviders?.coingecko.nativeTokenId;
40
-
41
- const blockchainId = network.vmName === NetworkVMType.PVM ? BlockchainId.P_CHAIN : BlockchainId.X_CHAIN;
42
- const networkName = network.isTestnet ? Network.FUJI : Network.MAINNET;
43
-
44
- const chainBalances = await glacierService
45
- .getChainBalance({
46
- blockchainId,
47
- network: networkName,
48
- addresses: addresses.join(','),
49
- })
50
- .then((value) => (value as ListPChainBalancesResponse | ListXChainBalancesResponse).balances);
51
-
52
- const simplePriceResponse = coingeckoId
53
- ? await tokenService.getSimplePrice({
54
- coinIds: [coingeckoId],
55
- currencies: [lowercaseCurrency] as VsCurrencyType[],
56
- })
57
- : {};
58
-
59
- const priceInCurrency = simplePriceResponse?.[coingeckoId ?? '']?.[lowercaseCurrency]?.price ?? undefined;
60
- const marketCap = simplePriceResponse?.[coingeckoId ?? '']?.[lowercaseCurrency]?.marketCap ?? undefined;
61
- const vol24 = simplePriceResponse?.[coingeckoId ?? '']?.[lowercaseCurrency]?.vol24 ?? undefined;
62
- const change24 = simplePriceResponse?.[coingeckoId ?? '']?.[lowercaseCurrency]?.change24 ?? undefined;
63
-
64
- let balance: TokenWithBalanceAVM | TokenWithBalancePVM;
65
- if (isPchainBalance(chainBalances)) {
66
- balance = convertPChainBalance({
67
- balance: chainBalances,
68
- networkToken,
69
- priceInCurrency,
70
- marketCap,
71
- vol24,
72
- change24,
73
- coingeckoId: coingeckoId ?? '',
74
- });
75
-
76
- return {
77
- [address]: {
78
- [networkToken.symbol]: balance,
79
- },
80
- };
81
- }
82
-
83
- if (isXchainBalance(chainBalances)) {
84
- balance = convertXChainBalance({
85
- balance: chainBalances,
86
- networkToken,
87
- priceInCurrency,
88
- marketCap,
89
- vol24,
90
- change24,
91
- coingeckoId: coingeckoId ?? '',
92
- });
93
- return {
94
- [address]: {
95
- [networkToken.symbol]: balance,
96
- },
97
- };
98
- }
99
- return Promise.reject('Incorrect type balance was returned from glacier');
100
- };
@@ -1,9 +0,0 @@
1
- import type { TokenWithBalance, TokenWithBalanceAVM, TokenWithBalancePVM } from '@avalabs/vm-module-types';
2
-
3
- export const isTokenWithBalancePVM = (token: TokenWithBalance): token is TokenWithBalancePVM => {
4
- return 'balancePerType' in token && 'unlockedUnstaked' in token.balancePerType;
5
- };
6
-
7
- export const isTokenWithBalanceAVM = (token: TokenWithBalance): token is TokenWithBalanceAVM => {
8
- return 'balancePerType' in token && 'unlocked' in token.balancePerType;
9
- };
@@ -1,27 +0,0 @@
1
- import type { PChainBalance, XChainBalances } from '@avalabs/glacier-sdk';
2
- import BN from 'bn.js';
3
-
4
- export const isPchainBalance = (balanceResult: PChainBalance | XChainBalances): balanceResult is PChainBalance => {
5
- return Object.keys(balanceResult).includes('unlockedUnstaked');
6
- };
7
-
8
- export const isXchainBalance = (balanceResult: PChainBalance | XChainBalances): balanceResult is XChainBalances => {
9
- return Object.keys(balanceResult).includes('locked');
10
- };
11
-
12
- export function calculateTotalBalance(uxtos: PChainBalance | XChainBalances): BN {
13
- const sum = Object.values(uxtos).reduce(function (totalAcc, utxoList) {
14
- const typeSum = utxoList.reduce(function (typeAcc, utxo) {
15
- const balanceToAdd = Number(utxo.amount);
16
- return typeAcc + balanceToAdd;
17
- }, 0);
18
-
19
- return totalAcc + typeSum;
20
- }, 0);
21
-
22
- return new BN(sum);
23
- }
24
-
25
- export function getTokenValue(decimals: number, amount?: number) {
26
- return amount === undefined ? 0 : amount / 10 ** decimals;
27
- }
@@ -1,19 +0,0 @@
1
- import { getNetworkFee } from './get-network-fee';
2
-
3
- describe('get-network-fee', () => {
4
- it('should return fixed network fees', async () => {
5
- await expect(getNetworkFee()).resolves.toEqual({
6
- baseFee: 1000000n,
7
- low: {
8
- maxFeePerGas: 1000000n,
9
- },
10
- medium: {
11
- maxFeePerGas: 1000000n,
12
- },
13
- high: {
14
- maxFeePerGas: 1000000n,
15
- },
16
- isFixedFee: true,
17
- });
18
- });
19
- });
@@ -1,21 +0,0 @@
1
- import type { NetworkFees } from '@avalabs/vm-module-types';
2
-
3
- /**
4
- * Returns {@link NetworkFees} based on a fixed fee.
5
- */
6
- export async function getNetworkFee(): Promise<NetworkFees> {
7
- // this is 0.001 Avax denominated in nAvax, taken from https://docs.avax.network/reference/standards/guides/txn-fees#fee-schedule
8
- return {
9
- baseFee: BigInt(1000000),
10
- low: {
11
- maxFeePerGas: BigInt(1000000),
12
- },
13
- medium: {
14
- maxFeePerGas: BigInt(1000000),
15
- },
16
- high: {
17
- maxFeePerGas: BigInt(1000000),
18
- },
19
- isFixedFee: true,
20
- };
21
- }
@@ -1,132 +0,0 @@
1
- import { type PChainTransaction, type NetworkToken } from '@avalabs/glacier-sdk';
2
- import Big from 'big.js';
3
- import { Avalanche } from '@avalabs/wallets-sdk';
4
- import { TokenType, type Transaction } from '@avalabs/vm-module-types';
5
- import { getExplorerAddressByNetwork, getTokenValue } from './utils';
6
-
7
- export function convertPChainTransaction({
8
- tx,
9
- address,
10
- networkToken,
11
- chainId,
12
- explorerUrl,
13
- isTestnet,
14
- }: {
15
- tx: PChainTransaction;
16
- address: string;
17
- networkToken: NetworkToken;
18
- chainId: number;
19
- explorerUrl?: string;
20
- isTestnet?: boolean;
21
- }): Transaction {
22
- const froms = new Set(tx.consumedUtxos.flatMap((utxo) => utxo.addresses) || []);
23
- const tos = new Set(tx.emittedUtxos.flatMap((utxo) => utxo.addresses) || []);
24
-
25
- const amount = getAmount({
26
- tx,
27
- isTestnet,
28
- networkToken,
29
- froms,
30
- });
31
-
32
- const avaxBurnedAmount = getBurnedAmount({ tx, isTestnet, networkToken });
33
- const chainAddress = address.toLowerCase().startsWith('p-') ? address.slice(2) : address;
34
- const isSender = froms.has(chainAddress);
35
-
36
- return {
37
- hash: tx.txHash,
38
- isContractCall: false,
39
- isIncoming: !isSender,
40
- isOutgoing: isSender,
41
- from: [...froms.values()].join(','),
42
- to: [...tos.values()].join(','),
43
- isSender,
44
- timestamp: tx.blockTimestamp * 1000, // to millis
45
- tokens: [
46
- {
47
- decimal: networkToken.decimals.toString(),
48
- name: networkToken.name,
49
- symbol: networkToken.symbol,
50
- type: TokenType.NATIVE,
51
- amount: amount.toString(),
52
- },
53
- ],
54
- gasUsed: avaxBurnedAmount.toString(),
55
- explorerLink: getExplorerAddressByNetwork(explorerUrl ?? '', tx.txHash, 'tx'),
56
- txType: tx.txType,
57
- chainId: chainId.toString(),
58
- };
59
- }
60
-
61
- function getAmount({
62
- tx,
63
- isTestnet,
64
- networkToken,
65
- froms,
66
- }: {
67
- tx: PChainTransaction;
68
- isTestnet?: boolean;
69
- networkToken: NetworkToken;
70
- froms: Set<string>;
71
- }): Big {
72
- const isImportExport = ['ImportTx', 'ExportTx'].includes(tx.txType);
73
- const isBaseTx = tx.txType === 'BaseTx';
74
-
75
- const nonChangeEmittedUtxosAmt = tx.emittedUtxos
76
- .filter(
77
- (utxo) => utxo.asset.assetId === getAvaxAssetId(!!isTestnet) && !utxo.addresses.some((addr) => froms.has(addr)),
78
- )
79
- .reduce((agg, utxo) => agg.add(utxo.asset.amount), new Big(0));
80
- const txValue = tx.value.find((val) => val.assetId === getAvaxAssetId(!!isTestnet))?.amount;
81
- // This ternary attempts to cover the case where users send themselves AVAX
82
- // in which case the senders are the recipients and we should use the total tx value.
83
- const baseTxValue = nonChangeEmittedUtxosAmt.gt(new Big(0))
84
- ? nonChangeEmittedUtxosAmt
85
- : txValue
86
- ? new Big(txValue)
87
- : new Big(0) ?? new Big(0);
88
-
89
- const pBlockchainId = isTestnet ? Avalanche.FujiContext.pBlockchainID : Avalanche.MainnetContext.pBlockchainID;
90
-
91
- const importExportAmount = tx.emittedUtxos
92
- .filter(
93
- (utxo) =>
94
- utxo.asset.assetId === getAvaxAssetId(!!isTestnet) &&
95
- ((tx.txType === 'ImportTx' && utxo.consumedOnChainId === pBlockchainId) ||
96
- (tx.txType === 'ExportTx' && utxo.consumedOnChainId !== pBlockchainId)),
97
- )
98
- .reduce((agg, utxo) => agg.add(utxo.amount), new Big(0));
99
- const nAvaxAmount = isBaseTx
100
- ? baseTxValue
101
- : isImportExport
102
- ? importExportAmount
103
- : tx.amountStaked.length === 0
104
- ? aggregateValue(tx.value, !!isTestnet)
105
- : aggregateValue(tx.amountStaked, !!isTestnet);
106
- return getTokenValue({ amount: nAvaxAmount?.toNumber(), decimals: networkToken.decimals });
107
- }
108
-
109
- function getBurnedAmount({
110
- tx,
111
- isTestnet,
112
- networkToken,
113
- }: {
114
- tx: PChainTransaction;
115
- isTestnet?: boolean;
116
- networkToken: NetworkToken;
117
- }): Big {
118
- const nAvaxFee = tx.amountBurned
119
- ?.filter((value) => value.assetId === getAvaxAssetId(!!isTestnet))
120
- .reduce((accumulator, value) => accumulator.add(value.amount), new Big(0));
121
- return getTokenValue({ amount: nAvaxFee?.toNumber(), decimals: networkToken.decimals });
122
- }
123
-
124
- function aggregateValue(value: PChainTransaction['value'], isTestnet: boolean): Big | undefined {
125
- return value
126
- .filter((value_) => value_.assetId === getAvaxAssetId(isTestnet))
127
- .reduce((accumulator, value_) => accumulator.add(value_.amount), new Big(0));
128
- }
129
-
130
- function getAvaxAssetId(isTestnet: boolean): string {
131
- return isTestnet ? Avalanche.FujiContext.avaxAssetID : Avalanche.MainnetContext.avaxAssetID;
132
- }
@@ -1,106 +0,0 @@
1
- import { type NetworkToken, XChainNonLinearTransaction, XChainLinearTransaction } from '@avalabs/glacier-sdk';
2
- import Big from 'big.js';
3
- import { Avalanche } from '@avalabs/wallets-sdk';
4
- import { TokenType, type Transaction } from '@avalabs/vm-module-types';
5
- import { getExplorerAddressByNetwork, getTokenValue } from './utils';
6
-
7
- export function convertXChainTransaction({
8
- tx,
9
- address,
10
- networkToken,
11
- chainId,
12
- explorerUrl,
13
- isTestnet,
14
- }: {
15
- tx: XChainNonLinearTransaction | XChainLinearTransaction;
16
- address: string;
17
- networkToken: NetworkToken;
18
- chainId: number;
19
- isTestnet?: boolean;
20
- explorerUrl?: string;
21
- }): Transaction {
22
- const froms = new Set(tx.consumedUtxos.flatMap((utxo) => utxo.addresses) || []);
23
- const tos = new Set(tx.emittedUtxos.flatMap((utxo) => utxo.addresses) || []);
24
-
25
- const amount = getAmount({
26
- tx,
27
- isTestnet,
28
- networkToken,
29
- });
30
- const avaxBurnedAmount = getBurnedAmount({ isTestnet, tx, totalAmountCreated: amount, networkToken });
31
- const chainAddress = address.toLowerCase().startsWith('x-') ? address.slice(2) : address;
32
- const isSender = froms.has(chainAddress);
33
-
34
- return {
35
- hash: tx.txHash,
36
- isContractCall: false,
37
- isIncoming: !isSender,
38
- isOutgoing: isSender,
39
- from: [...froms.values()].join(','),
40
- to: [...tos.values()].join(','),
41
- isSender,
42
- timestamp: tx.timestamp * 1000, // to millis
43
- tokens: [
44
- {
45
- decimal: networkToken.decimals.toString(),
46
- name: networkToken.name,
47
- symbol: networkToken.symbol,
48
- type: TokenType.NATIVE,
49
- amount: amount.toString(),
50
- },
51
- ],
52
- gasUsed: avaxBurnedAmount.toString(),
53
- explorerLink: getExplorerAddressByNetwork(explorerUrl ?? '', tx.txHash, 'tx'),
54
- txType: tx.txType,
55
- chainId: chainId.toString(),
56
- };
57
- }
58
-
59
- function getAmount({
60
- tx,
61
- isTestnet,
62
- networkToken,
63
- }: {
64
- tx: XChainNonLinearTransaction | XChainLinearTransaction;
65
- isTestnet?: boolean;
66
- networkToken: NetworkToken;
67
- }): Big {
68
- const isImportExport = ['ImportTx', 'ExportTx'].includes(tx.txType);
69
- const xBlockchainId = isTestnet ? Avalanche.FujiContext.xBlockchainID : Avalanche.MainnetContext.xBlockchainID;
70
- const importExportAmount = tx.emittedUtxos
71
- .filter(
72
- (utxo) =>
73
- utxo.asset.assetId === getAvaxAssetId(!!isTestnet) &&
74
- ((tx.txType === 'ImportTx' && utxo.consumedOnChainId === xBlockchainId) ||
75
- (tx.txType === 'ExportTx' && utxo.consumedOnChainId !== xBlockchainId)),
76
- )
77
- .reduce((agg, utxo) => agg.add(utxo.asset.amount), new Big(0));
78
-
79
- const totalAmountCreated = tx.amountCreated
80
- .filter((asset) => asset.assetId === getAvaxAssetId(!!isTestnet))
81
- .reduce((accumulator, asset) => accumulator.add(asset.amount), new Big(0));
82
- const nAvaxAmt = isImportExport ? importExportAmount : totalAmountCreated;
83
- return getTokenValue({ amount: nAvaxAmt.toNumber(), decimals: networkToken.decimals });
84
- }
85
-
86
- function getBurnedAmount({
87
- isTestnet,
88
- tx,
89
- totalAmountCreated,
90
- networkToken,
91
- }: {
92
- isTestnet?: boolean;
93
- tx: XChainNonLinearTransaction | XChainLinearTransaction;
94
- totalAmountCreated: Big;
95
- networkToken: NetworkToken;
96
- }): Big {
97
- const totalAmountUnlocked = tx.amountUnlocked
98
- .filter((asset) => asset.assetId === getAvaxAssetId(!!isTestnet))
99
- .reduce((accumulator, asset) => accumulator.add(asset.amount), new Big(0));
100
- const nAvaxFee = totalAmountUnlocked.minus(totalAmountCreated);
101
- return getTokenValue({ amount: nAvaxFee.toNumber(), decimals: networkToken.decimals });
102
- }
103
-
104
- function getAvaxAssetId(isTestnet: boolean): string {
105
- return isTestnet ? Avalanche.FujiContext.avaxAssetID : Avalanche.MainnetContext.avaxAssetID;
106
- }
@@ -1,59 +0,0 @@
1
- import type { GetTransactionHistory, Transaction, TransactionHistoryResponse } from '@avalabs/vm-module-types';
2
- import { BlockchainId, Network, SortOrder } from '@avalabs/glacier-sdk';
3
- import { isPChainTransactions, isXChainTransactions } from './utils';
4
- import { convertPChainTransaction } from './convert-p-chain-transaction';
5
- import { convertXChainTransaction } from './convert-x-chain-transaction';
6
- import type { AvalancheGlacierService } from '../../services/glacier-service/glacier-service';
7
-
8
- export const getTransactionHistory = async ({
9
- address,
10
- nextPageToken,
11
- offset,
12
- network,
13
- glacierService,
14
- }: GetTransactionHistory & { glacierService: AvalancheGlacierService }): Promise<TransactionHistoryResponse> => {
15
- const { isTestnet, networkToken, explorerUrl, chainId } = network;
16
- const isHealthy = glacierService.isHealthy();
17
- if (!isHealthy) {
18
- return {
19
- transactions: [],
20
- nextPageToken: '',
21
- };
22
- }
23
-
24
- const response = await glacierService.listLatestPrimaryNetworkTransactions({
25
- addresses: address,
26
- blockchainId: getBlockchainIdByAddress(address),
27
- network: isTestnet ? Network.FUJI : Network.MAINNET,
28
- pageSize: offset,
29
- pageToken: nextPageToken,
30
- sortOrder: SortOrder.DESC,
31
- });
32
-
33
- let transactions: Transaction[] = [];
34
- if (isPChainTransactions(response)) {
35
- transactions = response.transactions.map((value) =>
36
- convertPChainTransaction({ tx: value, isTestnet, address, networkToken, explorerUrl, chainId }),
37
- );
38
- }
39
- if (isXChainTransactions(response)) {
40
- transactions = response.transactions.map((value) =>
41
- convertXChainTransaction({ tx: value, isTestnet, address, networkToken, explorerUrl, chainId }),
42
- );
43
- }
44
-
45
- return {
46
- transactions,
47
- nextPageToken: response.nextPageToken,
48
- };
49
- };
50
-
51
- const getBlockchainIdByAddress = (address: string) => {
52
- // A comma separated list of X-Chain or P-Chain wallet addresses,
53
- // starting with "avax"/"fuji", "P-avax"/"P-fuji" or "X-avax"/"X-fuji"
54
- const firstAddress = address.split(',')[0];
55
- if (firstAddress?.toLowerCase().startsWith('p-')) {
56
- return BlockchainId.P_CHAIN;
57
- }
58
- return BlockchainId.X_CHAIN;
59
- };