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

Use a single spritesheet instead of individual image requests for network logos #1141

Open
wants to merge 4 commits into
base: dev
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ This repository contains implementation of Layerswap UI
NEXT_PUBLIC_LS_API = https://api-dev.layerswap.cloud/
NEXT_PUBLIC_API_KEY = mainnet #sandbox for testnets
NEXT_PUBLIC_IDENTITY_API = https://identity-api-dev.layerswap.cloud/
NEXT_PUBLIC_IMAGE_STORAGE = https://layerswap-images.s3.eu-north-1.amazonaws.com/logos/
```

35 changes: 31 additions & 4 deletions components/Input/NetworkFormField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useFormikContext } from "formik";
import { forwardRef, useCallback, useEffect, useState } from "react";
import { useSettingsState } from "../../context/settings";
import { SwapDirection, SwapFormValues } from "../DTOs/SwapFormValues";
import { ISelectMenuItem, SelectMenuItem } from "../Select/Shared/Props/selectMenuItem";
import { ILogoCoordinates, ILogoMetadata, ISelectMenuItem, SelectMenuItem } from "../Select/Shared/Props/selectMenuItem";
import CommandSelectWrapper from "../Select/Command/CommandSelectWrapper";
import { ResolveExchangeOrder, ResolveNetworkOrder, SortAscending } from "../../lib/sorting"
import NetworkSettings from "../../lib/NetworkSettings";
Expand All @@ -18,6 +18,8 @@ import CurrencyGroupFormField from "./CEXCurrencyFormField";
import { QueryParams } from "../../Models/QueryParams";
import { resolveExchangesURLForSelectedToken, resolveNetworkRoutesURL } from "../../helpers/routes";
import RouteIcon from "./RouteIcon";
import AppSettings from "../../lib/AppSettings";
import NetworkLogo from "./NetworkLogo";

type Props = {
direction: SwapDirection,
Expand Down Expand Up @@ -60,6 +62,15 @@ const NetworkFormField = forwardRef(function NetworkFormField({ direction, label

const networkRoutesURL = resolveNetworkRoutesURL(direction, values)
const apiClient = new LayerSwapApiClient()

const metadataURL = `${AppSettings.ImageStorage}metadata.json`
const {
data: metadata,
isLoading: metadataLoading,
} = useSWR<ApiResponse<ILogoMetadata[]> | ILogoMetadata[]>(`${metadataURL}`, apiClient.outboundFetcher, { keepPreviousData: true })

const [logoMetadata, setLogoMetadata] = useState<ILogoMetadata[]>([])

const {
data: routes,
isLoading,
Expand All @@ -76,6 +87,10 @@ const NetworkFormField = forwardRef(function NetworkFormField({ direction, label

const [exchangesData, setExchangesData] = useState<Exchange[]>(direction === 'from' ? sourceExchanges : destinationExchanges)

useEffect(() => {
if (!metadataLoading && metadata) setLogoMetadata(metadata as ILogoMetadata[])
}, [metadata])

useEffect(() => {
if (!exchnagesDataLoading && exchanges?.data) setExchangesData(exchanges.data)
}, [exchanges])
Expand All @@ -89,12 +104,12 @@ const NetworkFormField = forwardRef(function NetworkFormField({ direction, label
if (direction === "from") {
placeholder = "Source";
searchHint = "Swap from";
menuItems = GenerateMenuItems(routesData, toExchange || disableExchanges ? [] : exchangesData, direction, !!(from && lockFrom), query);
menuItems = GenerateMenuItems(routesData, toExchange || disableExchanges ? [] : exchangesData, direction, !!(from && lockFrom), query, logoMetadata);
}
else {
placeholder = "Destination";
searchHint = "Swap to";
menuItems = GenerateMenuItems(routesData, fromExchange || disableExchanges ? [] : exchangesData, direction, !!(to && lockTo), query);
menuItems = GenerateMenuItems(routesData, fromExchange || disableExchanges ? [] : exchangesData, direction, !!(to && lockTo), query, logoMetadata);
}

const value = menuItems.find(x => !x.isExchange ?
Expand Down Expand Up @@ -169,7 +184,16 @@ function groupByType(values: ISelectMenuItem[]) {
return groups;
}

function GenerateMenuItems(routes: RouteNetwork[] | undefined, exchanges: Exchange[], direction: SwapDirection, lock: boolean, query: QueryParams): (SelectMenuItem<RouteNetwork | Exchange> & { isExchange: boolean })[] {
function getLogoCoords(logoMetadata: ILogoMetadata[], url: string): ILogoCoordinates {
const name = url.split('/').pop();
const metadata = logoMetadata?.find(l => l.filename === name);
return {
x: metadata?.x || 0,
y: metadata?.y || 0
}
}

function GenerateMenuItems(routes: RouteNetwork[] | undefined, exchanges: Exchange[], direction: SwapDirection, lock: boolean, query: QueryParams, logoMetadata: ILogoMetadata[]): (SelectMenuItem<RouteNetwork | Exchange> & { isExchange: boolean })[] {
const mappedLayers = routes?.map(r => {
const isNewlyListed = r?.tokens?.every(t => new Date(t?.listing_date)?.getTime() >= new Date().getTime() - ONE_WEEK);
const badge = isNewlyListed ? (
Expand All @@ -185,6 +209,8 @@ function GenerateMenuItems(routes: RouteNetwork[] | undefined, exchanges: Exchan
const order = ResolveNetworkOrder(r, direction, isNewlyListed)
const routeNotFound = isAvailable && !r.tokens?.some(r => r.status === 'active');

const logoCoords = getLogoCoords(logoMetadata, r.logo)

const res: SelectMenuItem<RouteNetwork> & { isExchange: boolean } = {
baseObject: r,
id: r.name,
Expand All @@ -196,6 +222,7 @@ function GenerateMenuItems(routes: RouteNetwork[] | undefined, exchanges: Exchan
isExchange: false,
badge,
leftIcon: <RouteIcon direction={direction} isAvailable={isAvailable} routeNotFound={routeNotFound} type="network" />,
logo: <NetworkLogo x={logoCoords.x} y={logoCoords.y} />
}
return res;
}).sort(SortAscending) || [];
Expand Down
35 changes: 35 additions & 0 deletions components/Input/NetworkLogo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { FC } from "react";

import AppSettings from "../../lib/AppSettings";

type Props = {
x?: number;
y?: number;
width?: number;
height?: number;
className?: string;
};

const NetworkLogo: FC<Props> = (props) => {
const {
x = 0,
y = 0,
width = 24,
height = 24,
className = "rounded-md",
} = props;
const url = `${AppSettings.ImageStorage}spritesheet.png`;

return (
<div
className={className}
style={{
background: `url('${url}') -${x}px -${y}px`,
width: `${width}px`,
height: `${height}px`,
}}
></div>
);
};

export default NetworkLogo;
21 changes: 13 additions & 8 deletions components/Select/Command/CommandSelectWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,20 @@ export default function CommandSelectWrapper<T>({
{
value?.imgSrc && <div className="flex items-center">
<div className="flex-shrink-0 h-6 w-6 relative">
<Image
src={value.imgSrc}
alt="Project Logo"
height="40"
width="40"
loading="eager"
priority
className="rounded-md object-contain"
{value.logo ? (
value.logo
) : (
// TODO: Clarify if the logo should be loaded like network logo
<Image
src={value.imgSrc}
alt="Project Logo"
height="40"
width="40"
loading="eager"
priority
className="rounded-md object-contain"
/>
)}
</div>
</div>
}
Expand Down
15 changes: 15 additions & 0 deletions components/Select/Shared/Props/selectMenuItem.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
export interface ILogoMetadata {
filename: string;
x: number;
y: number;
width: number;
height: number;
}

export interface ILogoCoordinates {
x?: number;
y?: number;
}

export class SelectMenuItem<T> implements ISelectMenuItem {
id: string;
name: string;
Expand All @@ -8,6 +21,7 @@ export class SelectMenuItem<T> implements ISelectMenuItem {
group?: string;
details?: JSX.Element | JSX.Element[];
badge?: JSX.Element | JSX.Element[];
logo?: JSX.Element | JSX.Element[];
leftIcon?: JSX.Element | JSX.Element[];
baseObject: T;
constructor(baseObject: T, id: string, name: string, order: number, imgSrc: string, isAvailable: boolean, group?: string, details?: JSX.Element | JSX.Element[]) {
Expand All @@ -33,4 +47,5 @@ export interface ISelectMenuItem {
badge?: JSX.Element | JSX.Element[];
leftIcon?: JSX.Element | JSX.Element[];
order?: number;
logo?: JSX.Element | JSX.Element[];
}
25 changes: 15 additions & 10 deletions components/Select/Shared/SelectItem.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ISelectMenuItem } from "./Props/selectMenuItem";
import Image from 'next/image';

export default function SelectItem({ item }: { item: ISelectMenuItem }) {
import { ISelectMenuItem } from "./Props/selectMenuItem";

export default function SelectItem({ item }: { item: ISelectMenuItem }) {
return (
<div className={`${item?.displayName ? "px-3" : "px-1.5"} flex items-center justify-between gap-3 w-full overflow-hidden`}>
<div className={`${item?.displayName ? "gap-2.5" : "gap-3"} relative flex items-center pl-1 w-full`}>
Expand All @@ -13,14 +13,19 @@ export default function SelectItem({ item }: { item: ISelectMenuItem }) {
}
<div className={`${item?.displayName ? "h-9 w-9" : "h-6 w-6"} flex-shrink-0 relative`}>
{item.imgSrc && (
<Image
src={item.imgSrc}
alt="Project Logo"
height="40"
width="40"
loading="eager"
className="rounded-md object-contain"
/>
item.logo ? (
item.logo
) : (
// TODO: Clarify if the logo should be loaded like network logo
<Image
src={item.imgSrc}
alt="Project Logo"
height="40"
width="40"
loading="eager"
className="rounded-md object-contain"
/>
)
)}
</div>
<div className="flex justify-between w-full">
Expand Down
1 change: 1 addition & 0 deletions lib/AppSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export default class AppSettings {
static LayerswapApiUri?: string = process.env.NEXT_PUBLIC_LS_API
static ExplorerURl: string = `https://www.layerswap.io/explorer/`
static ApiVersion?: string = process.env.NEXT_PUBLIC_API_VERSION
static ImageStorage?: string = process.env.NEXT_PUBLIC_IMAGE_STORAGE
}
17 changes: 17 additions & 0 deletions lib/layerSwapApiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export default class LayerSwapApiClient {

fetcher = (url: string) => this.AuthenticatedRequest<ApiResponse<any>>("GET", url)

outboundFetcher = (url: string) => this.OutboundRequest<ApiResponse<any>>("GET", url)

async GetRoutesAsync(direction: 'sources' | 'destinations'): Promise<ApiResponse<NetworkWithTokens[]>> {
return await this.UnauthenticatedRequest<ApiResponse<NetworkWithTokens[]>>("GET", `/${direction}?include_unmatched=true&include_swaps=true&include_unavailable=true`)
}
Expand Down Expand Up @@ -112,6 +114,21 @@ export default class LayerSwapApiClient {
}
});
}

private async OutboundRequest<T extends EmptyApiResponse>(method: Method, uri: string, data?: any, header?: {}): Promise<T> {
return await this._unauthInterceptor(uri, { method: method, data: data, headers: { 'Access-Control-Allow-Origin': '*', ...(header ? header : {}) } })
.then(res => {
return res?.data;
})
.catch(async reason => {
if (reason instanceof AuthRefreshFailedError) {
return Promise.resolve(new EmptyApiResponse());
}
else {
return Promise.reject(reason);
}
});
}
}

export type DepositAddress = {
Expand Down