Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Adds new tx contract data model [REFACTOR] #102

Draft
wants to merge 2 commits into
base: abhk/hex
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions config/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ type AppConfig = {
base: Chain,
},
bridgeApiBaseUrl: string,
bridgeIndexerBaseUrl: string,
bridgeIndexerPollingInterval: number,
bridgePricePollingInterval: number,
bridgeHeadsPollingInterval: number,
Expand Down Expand Up @@ -41,8 +40,7 @@ export const appConfig: AppConfig = {
ethereum: process.env.NEXT_PUBLIC_ETH_NETWORK === 'mainnet' ? mainnet : sepolia,
base: process.env.NEXT_PUBLIC_ETH_NETWORK === 'mainnet' ? base : baseSepolia,
},
bridgeApiBaseUrl: process.env.NEXT_PUBLIC_BRIDGE_API_URL || 'http://0.0.0.0:8080',
bridgeIndexerBaseUrl: process.env.NEXT_PUBLIC_BRIDGE_INDEXER_URL ||'http://167.71.41.169:3000',
bridgeApiBaseUrl: process.env.NEXT_PUBLIC_BRIDGE_API_URL || 'https://hex-bridge-api.sandbox.avail.tools',
bridgeIndexerPollingInterval: 30,
bridgeHeadsPollingInterval: 600,
bridgePricePollingInterval: 60,
Expand Down
110 changes: 51 additions & 59 deletions services/transactions.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
import axios from "axios";
import { appConfig } from "@/config/default";
import { Transaction } from "@/types/transaction";
import { Chain } from "@/types/common";
import { TransactionResponseType } from "@/types/common";
import { Logger } from "@/utils/logger";
import { fetchWormholeTransactions } from "@/hooks/wormhole/helper";

const indexerInstance = axios.create({
baseURL: appConfig.bridgeIndexerBaseUrl,
headers: { "Access-Control-Allow-Origin": "*" },
withCredentials: false
const bridgeApiInstance = axios.create({
baseURL: appConfig.bridgeApiBaseUrl,
headers: { "Access-Control-Allow-Origin": "*" },
withCredentials: false,
});

type TransactionQueryParams = {
availAddress?: string;
ethAddress?: string;
sourceChain?: string;
destinationChain?: string;
availAddress?: string;
ethAddress?: string;
};

function validateParams({ availAddress, ethAddress }: TransactionQueryParams) {
Expand All @@ -26,47 +24,47 @@ function validateParams({ availAddress, ethAddress }: TransactionQueryParams) {
}
}

/**
function validateTransactionResponseType(queryParam: string) : string {
const chainAddressResponseMapping: Record<string, TransactionResponseType> = Object.freeze({
"ethAddress": TransactionResponseType.ETH_SEND,
"availAddress": TransactionResponseType.AVAIL_SEND
})
return chainAddressResponseMapping[queryParam];
}
Comment on lines +27 to +33
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: This function doesn't handle the case where queryParam is not one of the keys in chainAddressResponseMapping, which could lead to undefined being returned.

Suggested change
function validateTransactionResponseType(queryParam: string) : string {
const chainAddressResponseMapping: Record<string, TransactionResponseType> = Object.freeze({
"ethAddress": TransactionResponseType.ETH_SEND,
"availAddress": TransactionResponseType.AVAIL_SEND
})
return chainAddressResponseMapping[queryParam];
}
function validateTransactionResponseType(queryParam: string) : TransactionResponseType {
const chainAddressResponseMapping: Record<string, TransactionResponseType> = Object.freeze({
"ethAddress": TransactionResponseType.ETH_SEND,
"availAddress": TransactionResponseType.AVAIL_SEND
})
const type = chainAddressResponseMapping[queryParam];
if (!type) {
throw new Error(`Invalid query parameter: ${queryParam}`);
}
return type;
}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In fact early return/throws validation is way better.

e.g:

#L28 if !["",""].includes(queryParams) throw new Error(`Invalid query parameter: ${queryParam}`)


/**
* @description Fetches transactions from the indexer
*
* @param userAddress
* @param sourceChain
* @param destinationChain
*
* @param address
* @param queryParam
* @returns List of transactions
*/
async function fetchTransactions(userAddress: string, sourceChain?: string, destinationChain?: string): Promise<Transaction[]> {
try {
const response = await indexerInstance.get(`/transactions`, {
params: {
userAddress,
sourceChain,
destinationChain,
limit: 100,
page: 0,
},
});
const transactions = response.data.data.result;
if (destinationChain) {
return transactions.map((transaction: Transaction) => ({
...transaction,
destinationChain,
}));
}

return transactions;
} catch (e: any) {
Logger.error(`ERROR_FETCHING_TRANSACTIONS: ${e}`);
return [];
}
*/
async function fetchTransactions(
address: string,
queryParam: string
): Promise<Transaction[]> {
try {
const response = await bridgeApiInstance.get(`/transactions`, {
params: {
[queryParam]: address,
},
});
return response.data[validateTransactionResponseType(queryParam)];
} catch (e: any) {
Logger.error(`ERROR_FETCHING_TRANSACTIONS: ${e}`);
return [];
}
}

const fetchWithErrorHandling = async (address: string, source: Chain, dest?: Chain) => {
try {
return await fetchTransactions(address, source, dest);
} catch (error) {
Logger.error(`Failed to fetch transactions for ${address} from ${source} to ${dest}: ${error}`);
return [];
}
const fetchWithErrorHandling = async (address: string, queryParam: string) => {
try {
return await fetchTransactions(address, queryParam);
} catch (error) {
Logger.error(
`Failed to fetch transactions for ${address} from ${queryParam}: ${error}`
);
return [];
}
};

/**
Expand All @@ -75,10 +73,11 @@ const fetchWithErrorHandling = async (address: string, source: Chain, dest?: Cha
* @param {TransactionQueryParams}
* @returns Transaction[]
*/
export const getAllTransactions = async (
{ availAddress, ethAddress, sourceChain, destinationChain }: TransactionQueryParams
): Promise<Transaction[]> => {
validateParams({ availAddress, ethAddress });
export const getAllTransactions = async ({
availAddress,
ethAddress,
}: TransactionQueryParams): Promise<Transaction[]> => {
validateParams({ availAddress, ethAddress });

const allTransactions: Transaction[] = [];
const seenHashes = new Set<string>();
Expand All @@ -95,18 +94,11 @@ export const getAllTransactions = async (
const fetchPromises: Promise<Transaction[]>[] = [];

if (ethAddress) {
fetchPromises.push(
fetchWithErrorHandling(ethAddress, Chain.ETH, Chain.AVAIL),
fetchWithErrorHandling(ethAddress, Chain.AVAIL, Chain.ETH),
// fetchWormholeTransactions(false, ethAddress as `0x${string}`)
);
fetchPromises.push(fetchWithErrorHandling(ethAddress, "ethAddress"));
}

if (availAddress) {
fetchPromises.push(
fetchWithErrorHandling(availAddress, Chain.AVAIL, Chain.ETH),
fetchWithErrorHandling(availAddress, Chain.ETH, Chain.AVAIL)
);
fetchPromises.push(fetchWithErrorHandling(availAddress, "availAddress"));
}

const results = await Promise.all(fetchPromises);
Expand Down
5 changes: 5 additions & 0 deletions types/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export enum TransactionStatus {
CLAIM_PENDING = "PENDING",
}

export enum TransactionResponseType {
AVAIL_SEND = "availSend",
ETH_SEND = "ethSend"
}

export interface ethBalance {
decimals: number;
formatted: string;
Expand Down
35 changes: 14 additions & 21 deletions types/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,25 +77,18 @@ export interface sendMessageParams {
}

export interface Transaction {
status: TransactionStatus,
destinationChain: Chain,
messageId?: number,
sourceChain: Chain,
amount: string,
dataType?: "ERC20",
depositorAddress: `0x${string}` | string,
receiverAddress: string,
sourceBlockHash?: `${string}`,
sourceBlockNumber?: number,
sourceTransactionHash: `0x${string}`,
sourceTransactionIndex?: number,
sourceTimestamp: string
sourceTokenAddress?: `0x${string}`;
destinationTransactionHash?: `0x${string}` | string;
destinationTransactionBlockNumber?: number;
destinationTransactionTimestamp?: number;
destinationTransactionIndex?: number;
destinationTokenAddress?: `0x${string}`;
message?: string;
blockHash?: `0x${string}`;
amount: string,
depositorAddress: string,
destinationBlockHash?: string,
destinationBlockNumber?: number,
destinationTimestamp?: string,
messageId: number,
receiverAddress: string,
sourceBlockHash: string,
sourceBlockNumber: number,
sourceTimestamp: string,
sourceTransactionHash: string,
sourceTransactionIndex?: number,
status: TransactionStatus,
tokenId: string
}