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

🚧 Work in progress for stellar coin module #8898

Draft
wants to merge 2 commits into
base: develop
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
116 changes: 116 additions & 0 deletions libs/coin-modules/coin-stellar/src/api/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { createApi } from "./index";

const mockGetOperations = jest.fn();

jest.mock("../logic/listOperations", () => ({
listOperations: () => mockGetOperations(),
}));

const api = createApi({
explorer: {
url: "explorer.com",
fetchLimit: 200,
},
useStaticFees: true,
enableNetworkLogs: false,
});

describe("operations", () => {
beforeEach(() => {
jest.clearAllMocks();
});

it("should return 0 operations for a valid account", async () => {
mockGetOperations.mockResolvedValue([[], 0]);

// When
const operations = await api.listOperations("addr", { limit: 100 });

// Then
expect(operations).toEqual([[], 0]);
expect(mockGetOperations).toHaveBeenCalledTimes(1);
});

it("should return 1 operation for a valid account", async () => {
const mockOperation = {
hash: "e035a56c32003e3b0e4c9c5499b0750d71d98233ae6ae94323ff0a458b05a30b",
address: "addr",
type: "Operation",
value: 200,
fee: 0.0291,
block: {
hash: "hash",
time: new Date("2024-03-20T10:00:00Z"),
height: 10,
},
senders: ["addr"],
recipients: ["recipient"],
date: new Date("2024-03-20T10:00:00Z"),
transactionSequenceNumber: 2,
};
mockGetOperations.mockResolvedValue([[mockOperation], 0]);

// When
const operations = await api.listOperations("addr", { limit: 100, start: 9 });

// Then
expect(operations).toEqual([[mockOperation], 0]);
expect(mockGetOperations).toHaveBeenCalledTimes(1);
});

it("should return 0 operations if start is greater than the last operation", async () => {
const mockOperation = {
hash: "e035a56c32003e3b0e4c9c5499b0750d71d98233ae6ae94323ff0a458b05a30b",
address: "addr",
type: "Operation",
value: 200,
fee: 0.0291,
block: {
hash: "hash",
time: new Date("2024-03-20T10:00:00Z"),
height: 10,
},
senders: ["addr"],
recipients: ["recipient"],
date: new Date("2024-03-20T10:00:00Z"),
transactionSequenceNumber: 2,
};
mockGetOperations.mockResolvedValue([[mockOperation], 0]);

// When
const operations = await api.listOperations("addr", { start: 100, limit: 100 });

// Then
expect(operations).toEqual([[], 0]);
});

it("should call multiple times listOperations", async () => {
const mockOperation = {
hash: "e035a56c32003e3b0e4c9c5499b0750d71d98233ae6ae94323ff0a458b05a30b",
address: "addr",
type: "Operation",
value: 200,
fee: 0.0291,
block: {
hash: "hash",
time: new Date("2024-03-20T10:00:00Z"),
height: 10,
},
senders: ["addr"],
recipients: ["recipient"],
date: new Date("2024-03-20T10:00:00Z"),
transactionSequenceNumber: 2,
};

mockGetOperations
.mockResolvedValueOnce([[mockOperation], 10])
.mockResolvedValueOnce([[mockOperation], 0]);

// When
const operations = await api.listOperations("addr", { start: 9, limit: 100 });

// Then
expect(operations).toEqual([[mockOperation, mockOperation], 0]);
expect(mockGetOperations).toHaveBeenCalledTimes(2);
});
});
41 changes: 39 additions & 2 deletions libs/coin-modules/coin-stellar/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,44 @@ function compose(tx: string, signature: string, pubkey?: string): string {
return combine(tx, signature, pubkey);
}

const operations = async (
async function operations(
address: string,
{ limit, start }: Pagination,
): Promise<[Operation[], number]> => listOperations(address, { limit, cursor: start });
): Promise<[Operation[], number]> {
return start || start === 0
? operationsFromHeight(address, start)
: listOperations(address, { limit });
}

type PaginationState = {
pageSize: number;
heightLimit: number;
continueIterations: boolean;
apiNextCursor?: number;
accumulator: Operation[];
};

async function operationsFromHeight(
address: string,
start: number,
): Promise<[Operation[], number]> {
const state: PaginationState = {
pageSize: 100,
heightLimit: start,
continueIterations: true,
accumulator: [],
};

while (state.continueIterations) {
const [operations, nextCursor] = await listOperations(address, {
limit: state.pageSize,
cursor: state.apiNextCursor,
});
const filteredOperations = operations.filter(op => op.block.height >= state.heightLimit);
state.accumulator.push(...filteredOperations);
state.apiNextCursor = nextCursor;
state.continueIterations = operations.length === filteredOperations.length;
}

return [state.accumulator, state.apiNextCursor ?? 0];
}
9 changes: 3 additions & 6 deletions libs/coin-modules/coin-stellar/src/logic/listOperations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,15 @@ export async function listOperations(
): Promise<[Operation[], number]> {
// Fake accountId
const accountId = "";
const operations = await fetchOperations({
const [operations, nextCursor] = await fetchOperations({
accountId,
addr: address,
order: "asc",
order: "desc",
limit,
cursor: cursor?.toString(),
});

return [
operations.map(convertToCoreOperation(address)),
parseInt(operations.slice(-1)[0].extra.pagingToken ?? "0"),
];
return [operations.map(convertToCoreOperation(address)), nextCursor];
}

const convertToCoreOperation = (address: string) => (operation: StellarOperation) => {
Expand Down
17 changes: 10 additions & 7 deletions libs/coin-modules/coin-stellar/src/network/horizon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,17 +269,17 @@ export async function fetchOperations({
accountId,
addr,
order,
cursor = "0",
cursor,
limit,
}: {
accountId: string;
addr: string;
order: "asc" | "desc";
cursor: string | undefined;
limit?: number | undefined;
}): Promise<StellarOperation[]> {
}): Promise<[StellarOperation[], number]> {
if (!addr) {
return [];
return [[], 0];
}

const defaultFetchLimit = coinConfig.getCoinConfig().explorer.fetchLimit ?? FETCH_LIMIT;
Expand All @@ -290,23 +290,26 @@ export async function fetchOperations({
.forAccount(addr)
.limit(limit ?? defaultFetchLimit)
.order(order)
.cursor(cursor)
.cursor(cursor ?? "")
.includeFailed(true)
.join("transactions")
.call();

if (!rawOperations || !rawOperations.records.length) {
return [];
return [[], 0];
}

return rawOperationsToOperations(rawOperations.records as RawOperation[], addr, accountId);
return [
await rawOperationsToOperations(rawOperations.records as RawOperation[], addr, accountId),
parseInt(rawOperations.records[rawOperations.records.length - 1].paging_token),
];
} catch (e: unknown) {
// FIXME: terrible hacks, because Stellar SDK fails to cast network failures to typed errors in react-native...
// (https://github.com/stellar/js-stellar-sdk/issues/638)
const errorMsg = e ? String(e) : "";

if (e instanceof NotFoundError || errorMsg.match(/status code 404/)) {
return [];
return [[], 0];
}

if (errorMsg.match(/status code 4[0-9]{2}/)) {
Expand Down
Loading