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: support Explorer Asset API #3648

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
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
5 changes: 5 additions & 0 deletions .changeset/rich-items-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fuel-ts/account": patch
---

feat: support Explorer Asset API
4 changes: 4 additions & 0 deletions apps/docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,10 @@ export default defineConfig({
text: 'Optimized React Example',
link: '/guide/cookbook/optimized-react-example',
},
{
text: 'Querying the Asset API',
link: '/guide/cookbook/querying-the-asset-api',
},
],
},
{
Expand Down
3 changes: 2 additions & 1 deletion apps/docs/spell-check-custom-words.txt
Original file line number Diff line number Diff line change
Expand Up @@ -343,4 +343,5 @@ Workspaces
WSL
XOR
XORs
YAML
YAML
RESTful
30 changes: 30 additions & 0 deletions apps/docs/src/guide/cookbook/querying-the-asset-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Querying the Asset API

The Asset API is a RESTful API that allows you to query the assets on the Fuel blockchain. We allow for querying the Asset API on both the Mainnet and Testnet.

| | Endpoint |
| ------- | --------------------------------------------- |
| Mainnet | https://mainnet-explorer.fuel.network |
| Testnet | https://explorer-indexer-testnet.fuel.network |

For more information about the API, please refer to the [Wiki](https://github.com/FuelLabs/fuel-explorer/wiki/Assets-API#) page.

## Asset by ID

We can request information about an asset by its asset ID, using the `getAssetById` function. This will leverage the endpoint `/assets/<assetId>` to fetch the asset information.

<<< @./snippets/asset-api/asset-by-id.ts#full{ts:line-numbers}

By default, we will request the asset information for Mainnet. If you want to request the asset information for Testnet, you can pass the `url` parameter (this is the same for the [`getAssetsByOwner`](#assets-by-owner) function).

<<< @./snippets/asset-api/asset-by-id.ts#testnet{ts:line-numbers}

## Assets by Owner

We can request information about an asset by its owner, using the `getAssetsByOwner` function. This will leverage the endpoint `/accounts/<owner>/assets` to fetch the asset information.

<<< @./snippets/asset-api/assets-by-owner.ts#full{ts:line-numbers}

You can change the pagination parameters to fetch more assets (up to 100 assets per request).

<<< @./snippets/asset-api/assets-by-owner.ts#pagination{ts:line-numbers}
18 changes: 18 additions & 0 deletions apps/docs/src/guide/cookbook/snippets/asset-api/asset-by-id.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// #region full
import type { AssetInfo } from 'fuels';
import { getAssetById, TESTNET_ASSET_API_URL } from 'fuels';

const asset: AssetInfo | null = await getAssetById({
assetId: '0xf8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad07',
});

console.log('AssetInfo', asset);
// AssetInfo { ... }
// #endregion full

// #region testnet
await getAssetById({
assetId: '0xf8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad07',
url: TESTNET_ASSET_API_URL,
});
// #endregion testnet
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// #region full
import type { AssetsByOwner } from 'fuels';
import { getAssetsByOwner } from 'fuels';

const assets: AssetsByOwner = await getAssetsByOwner({
owner: '0x0000000000000000000000000000000000000000000000000000000000000000',
});

console.log('AssetsByOwner', assets);
// AssetsByOwner { data: [], pageInfo: { count: 0 } }
// #endregion full

// #region pagination
await getAssetsByOwner({
owner: '0x0000000000000000000000000000000000000000000000000000000000000000',
pagination: { last: 100 },
});
// #endregion pagination
4 changes: 2 additions & 2 deletions link-check.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
"pattern": "^http://localhost:3000"
},
{
"pattern": "https://docs.fuel.network/docs/fuels-ts/getting-started/connecting-to-the-network"
"pattern": "https://mainnet-explorer.fuel.network"
},
{
"pattern": "https://docs.fuel.network/docs/fuels-ts/getting-started/running-a-local-fuel-node"
"pattern": "https://explorer-indexer-testnet.fuel.network"
}
]
}
157 changes: 157 additions & 0 deletions packages/account/src/assets/asset-api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import { MOCK_ASSET_INFO_BY_OWNER, MOCK_BASE_ASSET, MOCK_FUEL_ASSET, MOCK_NFT_ASSET } from "../../test/fixtures/assets";
import { getAssetById, getAssetsByOwner, AssetInfo } from "./asset-api";

const mockFetch = () => {
const jsonResponse = vi.fn();
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValueOnce({
json: jsonResponse
} as unknown as Response);

return {
fetch: fetchSpy,
json: jsonResponse
}
}

/**
* @group node
* @group browser
*/
describe('Asset API', () => {
describe('getAssetById', () => {
it('should get an asset by id [Base Asset - Verified]', async () => {
const expected = {
assetId: expect.any(String),
name: expect.any(String),
symbol: expect.any(String),
decimals: expect.any(Number),
rate: expect.any(Number),
icon: expect.any(String),
suspicious: expect.any(Boolean),
verified: expect.any(Boolean),
networks: expect.any(Array),
}
const { fetch, json } = mockFetch();
json.mockResolvedValueOnce(MOCK_BASE_ASSET);

const response = await getAssetById({
assetId: MOCK_BASE_ASSET.assetId
});

const assetInfo = response as AssetInfo;
expect(assetInfo).toEqual(MOCK_BASE_ASSET)
expect(assetInfo).toMatchObject(expected)
expect(Object.keys(assetInfo).sort()).toEqual(Object.keys(expected).sort())
})

it('should get an asset by id [Fuel - Verified]', async () => {
const expected = {
assetId: expect.any(String),
contractId: expect.any(String),
subId: expect.any(String),
icon: expect.any(String),
name: expect.any(String),
symbol: expect.any(String),
decimals: expect.any(Number),
rate: expect.any(Number),
suspicious: expect.any(Boolean),
verified: expect.any(Boolean),
networks: expect.any(Array),
metadata: expect.any(Object),
totalSupply: expect.any(String),
}
const { json } = mockFetch();
json.mockResolvedValueOnce(MOCK_FUEL_ASSET);

const response = await getAssetById({
assetId: MOCK_FUEL_ASSET.assetId
});

const assetInfo = response as AssetInfo;
expect(response).toEqual(MOCK_FUEL_ASSET)
expect(assetInfo).toMatchObject(expected)
expect(Object.keys(assetInfo).sort()).toEqual(Object.keys(expected).sort())
})

it('should get an asset by id [NFT]', async () => {
const expected = {
assetId: expect.any(String),
contractId: expect.any(String),
subId: expect.any(String),

name: expect.any(String),
symbol: expect.any(String),
decimals: expect.any(Number),
totalSupply: expect.any(String),

suspicious: expect.any(Boolean),
verified: expect.any(Boolean),
isNFT: expect.any(Boolean),

metadata: expect.any(Object),
collection: expect.any(String),

owner: expect.any(String),
amount: expect.any(String),
amountInUsd: null,
uri: expect.any(String),
}

const { json } = mockFetch();
json.mockResolvedValueOnce(MOCK_NFT_ASSET);

const response = await getAssetById({
assetId: MOCK_NFT_ASSET.assetId
});

const assetInfo = response as AssetInfo;
expect(response).toEqual(MOCK_NFT_ASSET)
expect(assetInfo).toMatchObject(expected)
expect(Object.keys(assetInfo).sort()).toEqual(Object.keys(expected).sort())
});

it('should return null if asset not found', async () => {
const { json } = mockFetch();
// The API returns a 200 status code but the response is not valid JSON
json.mockRejectedValueOnce(null);

const response = await getAssetById({
assetId: '0x0000000000000000000000000000000000000000000000000000000000000000'
});

expect(response).toBeNull();
});
});

describe('getAssetByOwner', () => {
it('should get assets by owner', async () => {
const { json } = mockFetch();
json.mockResolvedValueOnce(MOCK_ASSET_INFO_BY_OWNER);

const response = await getAssetsByOwner({
owner: MOCK_NFT_ASSET.owner,
});

expect(response.data).toEqual([MOCK_NFT_ASSET]);
expect(response.pageInfo).toEqual({
count: 1,
})
});

it('should return response if no owner is found', async () => {
const { json } = mockFetch();
// The API returns a 200 status code but the response is not valid JSON
json.mockRejectedValueOnce(null);

const response = await getAssetsByOwner({
owner: '0x0000000000000000000000000000000000000000000000000000000000000000'
});

expect(response.data).toEqual([]);
expect(response.pageInfo).toEqual({
count: 0,
})
});
})
});

111 changes: 111 additions & 0 deletions packages/account/src/assets/asset-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { B256Address } from "@fuel-ts/address";
import { NetworkEthereum, NetworkFuel } from "./types";

export const MAINNET_ASSET_API_URL = 'https://mainnet-explorer.fuel.network'
export const TESTNET_ASSET_API_URL = 'https://testnet-explorer.fuel.network'

export interface AssetPaginationOptions {
last: number;
}

export interface AssetPageInfo {
count: number;
}

const request = async <TResponse>(url: string, slug: string): Promise<TResponse | null> => {
const response = await fetch(`${url}${slug}`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
});

try {
return await response.json() satisfies TResponse;
} catch (error) {
// The API returns a 200 status code but the response is not valid JSON
return null;
}
};

const buildQueryString = (parameters: Record<string, string | { toString: () => string }>) => {
const query = new URLSearchParams();
Object.entries(parameters).forEach(([key, value]) => {
query.set(key, value.toString());
});
return query.size > 0 ? `?${query.toString()}` : '';
};

export interface AssetInfo {
assetId: string;
contractId?: string;
subId?: string;
name: string;
symbol: string;
decimals: number;
suspicious: boolean;
verified: boolean;
totalSupply?: string;
networks?: (NetworkEthereum | NetworkFuel)[];
rate?: number;
icon?: string;
owner?: string;
amount?: string;
amountInUsd?: string;
uri?: string;
metadata: Record<string, string>;
collection?: string;
isNFT?: boolean;
}

/**
* Get information about any asset (including NFTs)
*
* @param opts - The options for the request
* @param opts.url {string} - The Base URL of the explorer API (default: `MAINNET_ASSET_API_URL`)
* @param opts.assetId {string} - The ID of the asset to get information about
* @returns {Promise<AssetInfo>} - The information about the asset
*
* @see {@link https://github.com/FuelLabs/fuel-explorer/wiki/Assets-API#instructions-for-consuming-assets-data-from-indexer-api}
*/
export const getAssetById = (opts: {
assetId: B256Address;
url?: string;
}): Promise<AssetInfo | null> => {
const { url = MAINNET_ASSET_API_URL, assetId } = opts;
return request<AssetInfo>(url, `/assets/${assetId}`);
};

export interface AssetsByOwner {
data: AssetInfo[];
pageInfo: AssetPageInfo;
}

/**
* Get assets by owner
*
* @param opts - The options for the request
* @param opts.owner {B256Address} - The owner of the assets
* @param opts.url {string} - The Base URL of the explorer API (default: `MAINNET_ASSET_API_URL`)
* @param opts.pagination {AssetPaginationOptions} - The pagination options (default: 10)
* @returns {Promise<AssetsByOwnerResponse>} - The assets by owner
*
* @see {@link https://github.com/FuelLabs/fuel-explorer/wiki/Assets-API#instructions-for-consuming-assets-data-owned-by-an-account-from-indexer-api}
*/
export const getAssetsByOwner = async (opts: {
owner: B256Address;
url?: string;
pagination?: AssetPaginationOptions;
}): Promise<AssetsByOwner> => {
const { url = MAINNET_ASSET_API_URL, owner, pagination = { last: 10 } } = opts;
const { last } = pagination;
const queryString = buildQueryString({ last });
const response = await request<AssetsByOwner>(url, `/accounts/${owner}/assets${queryString}`);

// If the response is not valid JSON, return an empty array
if (!response) {
return { data: [], pageInfo: { count: 0 } };
}

return response;
};
1 change: 1 addition & 0 deletions packages/account/src/assets/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './assets'
export * from './asset-api'
export * from './utils';
export * from './types';
Loading