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(frontend): sol txn service #4136

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
92 changes: 92 additions & 0 deletions src/frontend/src/sol/api/solana.api.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import { WALLET_PAGINATION } from '$lib/constants/app.constants';
import type { SolAddress } from '$lib/types/address';
import { last } from '$lib/utils/array.utils';
import { solanaHttpRpc } from '$sol/providers/sol-rpc.providers';
import type { SolCertifiedTransaction } from '$sol/stores/sol-transactions.store';
import type { SolanaNetworkType } from '$sol/types/network';
import type { SolSignature } from '$sol/types/sol-transaction';
import { mapSolTransactionUi } from '$sol/utils/sol-transactions.utils';
import { isNullish, nonNullish } from '@dfinity/utils';
import { address as solAddress } from '@solana/addresses';
import { signature } from '@solana/keys';
import type { Lamports } from '@solana/rpc-types';
import type { Writeable } from 'zod';

//lamports are like satoshis: https://solana.com/docs/terminology#lamport
export const loadSolLamportsBalance = async ({
Expand All @@ -19,3 +27,87 @@ export const loadSolLamportsBalance = async ({

return balance;
};

export const getSolTransactions = async ({
address,
network,
before,
limit = Number(WALLET_PAGINATION)
}: {
address: SolAddress;
network: SolanaNetworkType;
before?: string;
limit?: number;
}): Promise<SolCertifiedTransaction[]> => {
const { getSignaturesForAddress } = solanaHttpRpc(network);
const wallet = solAddress(address);

const transactions: SolCertifiedTransaction[] = [];
let lastSignature = nonNullish(before) ? signature(before) : undefined;

while (transactions.length < limit) {
const signatures = await getSignaturesForAddress(wallet, {
before: lastSignature,
limit
}).send();

if (signatures.length === 0) {
break;
}

lastSignature = last(signatures as Writeable<typeof signatures>)?.signature;

const transactionDetails = await Promise.all(
signatures
.filter(({ err }) => isNullish(err))
.map(async (signature) => await getTransactionDetailForSignature({ signature, network }))
);

const uiTransactions: SolCertifiedTransaction[] = transactionDetails
.filter(nonNullish)

.map((transaction) => ({
data: mapSolTransactionUi({
transaction,
address
}),
certified: false
}));

transactions.push(...uiTransactions);

const hasNoMoreSignaturesLeft = signatures.length < limit;
const hasLoadedEnoughTransactions = transactions.length >= limit;

if (hasNoMoreSignaturesLeft || hasLoadedEnoughTransactions) {
break;
}
}

return transactions.slice(0, limit);
};

const getTransactionDetailForSignature = async ({
signature: { confirmationStatus, signature },
network
}: {
signature: SolSignature;
network: SolanaNetworkType;
}) => {
const { getTransaction } = solanaHttpRpc(network);

const rpcTransaction = await getTransaction(signature, {
maxSupportedTransactionVersion: 0
}).send();

if (isNullish(rpcTransaction)) {
return null;
}

return {
...rpcTransaction,
version: rpcTransaction.version,
confirmationStatus: confirmationStatus,
id: signature.toString()
};
};
83 changes: 83 additions & 0 deletions src/frontend/src/sol/services/sol-transactions.services.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import {
SOLANA_DEVNET_TOKEN_ID,
SOLANA_LOCAL_TOKEN_ID,
SOLANA_TESTNET_TOKEN_ID,
SOLANA_TOKEN_ID
} from '$env/tokens/tokens.sol.env';
import type { SolAddress } from '$lib/types/address';
import { getSolTransactions } from '$sol/api/solana.api';
import {
solTransactionsStore,
type SolCertifiedTransaction
} from '$sol/stores/sol-transactions.store';
import { SolanaNetworks, type SolanaNetworkType } from '$sol/types/network';

export const loadNextSolTransactions = async ({
address,
network,
before,
limit,
signalEnd
}: {
address: SolAddress;
network: SolanaNetworkType;
before?: string;
limit?: number;
signalEnd: () => void;
}): Promise<SolCertifiedTransaction[]> => {
const transactions = await loadSolTransactions({
address,
network,
before,
limit
});

if (transactions.length === 0) {
signalEnd();
return [];
}

return transactions;
};

const networkToSolTokenIdMap = {
[SolanaNetworks.mainnet]: SOLANA_TOKEN_ID,
[SolanaNetworks.testnet]: SOLANA_TESTNET_TOKEN_ID,
[SolanaNetworks.devnet]: SOLANA_DEVNET_TOKEN_ID,
[SolanaNetworks.local]: SOLANA_LOCAL_TOKEN_ID
};

const loadSolTransactions = async ({
address,
network,
before,
limit
}: {
address: SolAddress;
network: SolanaNetworkType;
before?: string;
limit?: number;
}): Promise<SolCertifiedTransaction[]> => {
const solTokenIdForNetwork = networkToSolTokenIdMap[network];

try {
const transactions = await getSolTransactions({
address,
network,
before,
limit
});

solTransactionsStore.append({
tokenId: solTokenIdForNetwork,
transactions: transactions
});

return transactions;
} catch (error: unknown) {
solTransactionsStore.reset(solTokenIdForNetwork);

console.error(`Failed to load transactions for ${solTokenIdForNetwork.description}:`, error);
return [];
}
};
6 changes: 5 additions & 1 deletion src/frontend/src/sol/types/sol-transaction.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { solTransactionTypes } from '$lib/schema/transaction.schema';
import type { TransactionType, TransactionUiCommon } from '$lib/types/transaction';
import type { GetTransactionApi } from '@solana/rpc';
import type { GetSignaturesForAddressApi, GetTransactionApi } from '@solana/rpc';
import type { Commitment } from '@solana/rpc-types';

export type SolTransactionType = Extract<
Expand All @@ -20,3 +20,7 @@ export type SolRpcTransaction = NonNullable<ReturnType<GetTransactionApi['getTra
id: string;
confirmationStatus: Commitment | null;
};

export type SolSignature = ReturnType<
GetSignaturesForAddressApi['getSignaturesForAddress']
>[number];
22 changes: 22 additions & 0 deletions src/frontend/src/tests/mocks/sol-signatures.mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { signature } from '@solana/keys';

export const mockSolSignature = () => {
const chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
let result = '';
for (let i = 0; i < 87; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return signature(result);
};

export const mockSolSignatureResponse = () => ({
signature: mockSolSignature(),
err: null,
confirmationStatus: 'finalized'
});

export const mockSolSignatureWithErrorResponse = () => ({
signature: mockSolSignature(),
err: 'Some error',
confirmationStatus: 'finalized'
});
12 changes: 12 additions & 0 deletions src/frontend/src/tests/mocks/sol-transactions.mock.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { SolCertifiedTransaction } from '$sol/stores/sol-transactions.store';
import type { SolRpcTransaction, SolTransactionUi } from '$sol/types/sol-transaction';
import { mockSolAddress } from '$tests/mocks/sol.mock';
import { address } from '@solana/addresses';
Expand All @@ -18,6 +19,17 @@ export const createMockSolTransactionUi = (id: string): SolTransactionUi => ({
status: 'finalized'
});

export const mockSolCertifiedTransactions: SolCertifiedTransaction[] = [
{
data: createMockSolTransactionUi('tx1'),
certified: false
},
{
data: createMockSolTransactionUi('tx2'),
certified: false
}
];

export const mockSolRpcReceiveTransaction: SolRpcTransaction = {
blockTime: 1736257946n as UnixTimestamp,
confirmationStatus: 'finalized',
Expand Down
Loading
Loading