Skip to content
Open
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
},
"packageManager": "yarn@4.17.0",
"engines": {
"node": ">= 20"
"node": ">= 22"
},
"lavamoat": {
"allowScripts": {
Expand Down
12 changes: 11 additions & 1 deletion packages/snap/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,18 @@ const config = {

preset: '@metamask/snaps-jest',
transform: {
'^.+\\.(t|j)sx?$': 'ts-jest',
'^.+\\.(t|j)sx?$': [
'ts-jest',
{
tsconfig: {
allowJs: true,
},
},
],
},
transformIgnorePatterns: [
'/node_modules/(?!(@noble/ed25519|@noble/hashes|@stellar/stellar-sdk|uint8array-extras)/)',
],
moduleNameMapper: {
'\\.svg$': 'jest-transform-stub',
},
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"@metamask/snaps-sdk": "^11.1.0",
"@metamask/superstruct": "^3.2.1",
"@metamask/utils": "^11.11.0",
"@stellar/stellar-sdk": "^15.0.1",
"@stellar/stellar-sdk": "^16.0.1",
"@types/jest": "^30.0.0",
"async-mutex": "^0.5.0",
"bignumber.js": "^9.3.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/MetaMask/snap-stellar-wallet.git"
},
"source": {
"shasum": "Inf8VxNlsHTyLYST3nsK1X0sdkSiAbkFciLrCTsYZNY=",
"shasum": "SVKNK5OF7tekFDnKaeS+aIitTtVULg/J9z4/N22oDTI=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
126 changes: 126 additions & 0 deletions packages/snap/src/services/network/HorizonClient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/* eslint-disable @typescript-eslint/naming-convention -- Horizon wire fields use snake_case */
import { HorizonClient, HorizonNotFoundError } from './HorizonClient';

describe('HorizonClient', () => {
const originalFetch = globalThis.fetch;
const fetchMock = jest.fn<
ReturnType<typeof fetch>,
Parameters<typeof fetch>
>();

beforeEach(() => {
fetchMock.mockReset();
globalThis.fetch = fetchMock;
});

afterAll(() => {
globalThis.fetch = originalFetch;
});

it('fetches the base fee from Horizon fee stats', async () => {
fetchMock.mockResolvedValue(jsonResponse({ last_ledger_base_fee: '123' }));
const client = new HorizonClient('https://horizon.example');

const result = await client.fetchBaseFee();

expect(result).toBe(123);
expect(fetchMock).toHaveBeenCalledWith(
'https://horizon.example/fee_stats',
{
method: 'GET',
headers: { Accept: 'application/json' },
},
);
});

it('loads account responses with SDK-compatible account helpers', async () => {
fetchMock.mockResolvedValue(
jsonResponse({
account_id: 'GB5QOHJZ6RACA26NFDIEHD7I7SLROLC5P4NATSG43OJV2C5WUR4VEUKG',
sequence: '42',
balances: [],
}),
);
const client = new HorizonClient('https://horizon.example');

const result = await client.loadAccount(
'GB5QOHJZ6RACA26NFDIEHD7I7SLROLC5P4NATSG43OJV2C5WUR4VEUKG',
);

expect(result.accountId()).toBe(
'GB5QOHJZ6RACA26NFDIEHD7I7SLROLC5P4NATSG43OJV2C5WUR4VEUKG',
);
expect(result.sequenceNumber()).toBe('42');
});

it('reads asset records from Horizon embedded collection responses', async () => {
const assetRecord = {
asset_code: 'USDC',
asset_issuer: 'GB5QOHJZ6RACA26NFDIEHD7I7SLROLC5P4NATSG43OJV2C5WUR4VEUKG',
};
fetchMock.mockResolvedValue(
jsonResponse({
_embedded: {
records: [assetRecord],
},
}),
);
const client = new HorizonClient('https://horizon.example');

const result = await client.getAssetRecords({
assetCode: 'USDC',
assetIssuer: 'GB5QOHJZ6RACA26NFDIEHD7I7SLROLC5P4NATSG43OJV2C5WUR4VEUKG',
});

expect(result.records).toStrictEqual([assetRecord]);
});

it('reads transaction records from Horizon embedded collection responses', async () => {
const transactionRecord = {
hash: 'transaction-hash',
source_account:
'GB5QOHJZ6RACA26NFDIEHD7I7SLROLC5P4NATSG43OJV2C5WUR4VEUKG',
};
fetchMock.mockResolvedValue(
jsonResponse({
_links: {
next: {
href: '',
},
},
_embedded: {
records: [transactionRecord],
},
}),
);
const client = new HorizonClient('https://horizon.example');

const result = await client.getTransactions({
accountAddress:
'GB5QOHJZ6RACA26NFDIEHD7I7SLROLC5P4NATSG43OJV2C5WUR4VEUKG',
cursor: '',
includeFailed: false,
limit: 10,
order: 'desc',
});

expect(result.records).toStrictEqual([transactionRecord]);
});

it('throws HorizonNotFoundError for 404 responses', async () => {
fetchMock.mockResolvedValue(jsonResponse({ title: 'Not Found' }, 404));
const client = new HorizonClient('https://horizon.example');

await expect(client.getTransaction('abc')).rejects.toThrow(
HorizonNotFoundError,
);
});
});

function jsonResponse(body: unknown, status: number = 200): Response {
return {
ok: status >= 200 && status < 300,
status,
text: async () => JSON.stringify(body),
} as Response;
}
221 changes: 221 additions & 0 deletions packages/snap/src/services/network/HorizonClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
/* eslint-disable @typescript-eslint/naming-convention -- Horizon wire fields use snake_case */
import type { Horizon } from '@stellar/stellar-sdk';

type HorizonAccountJson = Horizon.AccountResponse & {
account_id?: string;
id?: string;
sequence?: string;
};

type HorizonCollectionResponse<TRecord> = {
records?: TRecord[];
_embedded?: { records?: TRecord[] };
_links?: {
next?: {
href?: string;
};
};
};
Comment thread
Copilot marked this conversation as resolved.

export type HorizonAssetRecord = {
asset_code?: string;
asset_issuer?: string;
};

export type HorizonAssetRecordsResponse = {
records: HorizonAssetRecord[];
};

export type HorizonTransactionPage = {
records: Horizon.ServerApi.TransactionRecord[];
next: () => Promise<HorizonTransactionPage>;
};

/**
* Error thrown when Horizon returns HTTP 404.
*/
export class HorizonNotFoundError extends Error {
readonly status = 404;

constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'HorizonNotFoundError';
}
}

/**
* Small Snap-safe Horizon client using the platform `fetch` endowment directly.
*/
export class HorizonClient {
readonly #baseUrl: string;

constructor(baseUrl: string) {
this.#baseUrl = baseUrl.replace(/\/$/u, '');
}

async fetchBaseFee(): Promise<number> {
const feeStats = await this.#requestJson<{
last_ledger_base_fee?: string;
}>('/fee_stats');
return parseInt(feeStats.last_ledger_base_fee ?? '', 10) || 100;
}

async loadAccount(accountAddress: string): Promise<Horizon.AccountResponse> {
const account = await this.#requestJson<HorizonAccountJson>(
`/accounts/${encodeURIComponent(accountAddress)}`,
);
return this.#toAccountResponse(account);
}

async getAssetRecords(params: {
assetCode: string;
assetIssuer: string;
}): Promise<HorizonAssetRecordsResponse> {
const { assetCode, assetIssuer } = params;
const response = await this.#requestJson<
HorizonCollectionResponse<HorizonAssetRecord>
>(
`/assets?${encodeQuery({
asset_code: assetCode,
asset_issuer: assetIssuer,
})}`,
);

return {
records: response.records ?? response._embedded?.records ?? [],
};
}
Comment thread
Copilot marked this conversation as resolved.

async getTransaction(
transactionHash: string,
): Promise<Horizon.ServerApi.TransactionRecord> {
return this.#requestJson(
`/transactions/${encodeURIComponent(transactionHash)}`,
);
}

async getTransactions(params: {
accountAddress: string;
cursor: string;
includeFailed: boolean;
limit: number;
order: 'asc' | 'desc';
}): Promise<HorizonTransactionPage> {
const { accountAddress, cursor, includeFailed, limit, order } = params;
return this.#getTransactionPage(
`/accounts/${encodeURIComponent(accountAddress)}/transactions?${encodeQuery(
{
cursor,
include_failed: includeFailed,
limit,
order,
},
)}`,
);
}

async #getTransactionPage(url: string): Promise<HorizonTransactionPage> {
const response =
await this.#requestJson<
HorizonCollectionResponse<Horizon.ServerApi.TransactionRecord>
>(url);
const nextUrl = response._links?.next?.href;

const records = response.records ?? response._embedded?.records ?? [];

return {
records,
next: async (): Promise<HorizonTransactionPage> => {
if (nextUrl === undefined || nextUrl.length === 0) {
return emptyTransactionPage();
}
return this.#getTransactionPage(nextUrl);
},
};
}
Comment thread
Copilot marked this conversation as resolved.

#toAccountResponse(account: HorizonAccountJson): Horizon.AccountResponse {
const accountId = account.account_id ?? account.id;
const { sequence } = account;

return Object.assign(account, {
accountId(): string | undefined {
return accountId;
},
sequenceNumber(): string | undefined {
return sequence;
},
}) as Horizon.AccountResponse;
}

async #requestJson<TResponse>(pathOrUrl: string): Promise<TResponse> {
const url = pathOrUrl.startsWith('http')
? pathOrUrl
: `${this.#baseUrl}${pathOrUrl.startsWith('/') ? '' : '/'}${pathOrUrl}`;
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
},
});
const body = await response.text();
const data = parseJsonBody(body);

if (response.status === 404) {
throw new HorizonNotFoundError(`Horizon resource not found: ${url}`, {
cause: data,
});
}

if (!response.ok) {
throw new Error(`Horizon request failed with status ${response.status}`, {
cause: data,
});
}

return data as TResponse;
}
}

/**
* Encodes query parameters without relying on URLSearchParams, which is not guaranteed in SES.
*
* @param params - Query parameters.
* @returns Encoded query string.
*/
function encodeQuery(
params: Record<string, boolean | number | string | undefined>,
): string {
return Object.entries(params)
.filter(([, value]) => value !== undefined)
.map(
([key, value]) =>
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`,
)
.join('&');
}

/**
* Parses a JSON response body.
*
* @param body - Response text.
* @returns Parsed JSON, or null for empty responses.
*/
function parseJsonBody(body: string): unknown {
if (body.length === 0) {
return null;
}
return JSON.parse(body);
}

/**
* Builds an empty Horizon transaction page.
*
* @returns Empty transaction page.
*/
function emptyTransactionPage(): HorizonTransactionPage {
return {
records: [],
next: async () => emptyTransactionPage(),
};
}
Loading
Loading