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: init @ledgerhq/crypto-icons library #3

Merged
merged 2 commits into from
Aug 7, 2024
Merged
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
42 changes: 42 additions & 0 deletions .github/workflows/lib.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: Run Tests

on:
pull_request:
branches: ["main"]
paths: ["lib/**"]

jobs:
lint-and-test:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./lib/

strategy:
matrix:
node-version: [20]

steps:
- name: Checkout Repository
uses: actions/checkout@v4

- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 9.6.0

- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
cache-dependency-path: "./lib/pnpm-lock.yaml"

- name: Install dependencies
run: pnpm install

- name: Lint
run: pnpm lint

- name: Run Jest tests
run: pnpm test
5 changes: 5 additions & 0 deletions lib/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/

dist/

**/*.stories.tsx
53 changes: 53 additions & 0 deletions lib/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended",
"plugin:import/errors",
"plugin:import/warnings",
"plugin:import/typescript",
"plugin:react-hooks/recommended",
"plugin:prettier/recommended"
],
"parser": "@typescript-eslint/parser",
"plugins": [
"react",
"react-hooks",
"@typescript-eslint",
"import",
"prettier"
],
"rules": {
"prettier/prettier": "warn",
"react/react-in-jsx-scope": "off",
"react/prop-types": "off",
"@typescript-eslint/no-explicit-any": "warn",
"react-hooks/exhaustive-deps": "warn",
"import/no-named-as-default": 0,
"@typescript-eslint/no-unused-vars": [
"warn",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_"
}
],
"import/order": [
"warn",
{
"groups": [
"builtin",
"external",
"internal",
"parent",
"sibling",
"index"
]
}
]
},
"settings": {
"react": {
"version": "detect"
}
}
}
8 changes: 8 additions & 0 deletions lib/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*storybook.log
storybook-static

node_modules

dist

*.tgz
5 changes: 5 additions & 0 deletions lib/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/

dist/

**/*.stories.tsx
9 changes: 9 additions & 0 deletions lib/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "always",
"tabWidth": 2,
"printWidth": 100,
"semi": true,
"plugins": ["prettier-plugin-organize-imports"]
}
11 changes: 11 additions & 0 deletions lib/.storybook/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { StorybookConfig } from '@storybook/react-webpack5';

const config: StorybookConfig = {
stories: ['../__stories__/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
addons: ['@storybook/addon-webpack5-compiler-swc'],
framework: {
name: '@storybook/react-webpack5',
options: {},
},
};
export default config;
21 changes: 21 additions & 0 deletions lib/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Ledger

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions lib/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
TODO
46 changes: 46 additions & 0 deletions lib/__mocks__/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { rest } from 'msw';
import { COINGECKO_MAPPED_ASSETS_URL, CRYPTO_ICONS_CDN_BASE } from '../src/constants';
import { CoinGeckoMapping, LedgerMapping } from '../src/iconMapping';

export const ledgerCDNMock: LedgerMapping = {
bitcoin: {
icon: 'BTC.png',
},
arbitrum: {
icon: 'ETH.png',
},
base: {
icon: 'ETH.png',
},
};

export const coinGeckoMock: CoinGeckoMapping = [
{
ledgerId: 'bitcoin',
data: {
img: 'https://proxycgassets.api.live.ledger.com/coins/images/1/large/bitcoin.png',
},
},
{
ledgerId: 'arbitrum',
data: {
img: 'https://proxycgassets.api.live.ledger.com/coins/images/279/large/ethereum.png',
},
},
{
ledgerId: 'decred',
data: {
img: 'https://proxycgassets.api.live.ledger.com/coins/images/329/large/decred.png',
},
},
];

export const handlers = [
rest.get(`${CRYPTO_ICONS_CDN_BASE}/index.json`, (_, res, ctx) => {
return res(ctx.status(200), ctx.json(ledgerCDNMock));
}),

rest.get(COINGECKO_MAPPED_ASSETS_URL, (_, res, ctx) => {
return res(ctx.status(200), ctx.json(coinGeckoMock));
}),
];
4 changes: 4 additions & 0 deletions lib/__mocks__/node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server = setupServer(...handlers);
59 changes: 59 additions & 0 deletions lib/__stories__/CryptoIcon.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Meta, StoryFn } from '@storybook/react';
import React from 'react';
import iconsObj from '../../assets/index.json';
import CryptoIcon from '../src/components/CryptoIcon';

const meta = {
title: 'CryptoIcon',
component: CryptoIcon,
} satisfies Meta<typeof CryptoIcon>;

export default meta;

const Template: StoryFn = () => (
<div>
{Object.entries(iconsObj).map(([key, value]) => (
<div key={key}>
<p>{key}</p>
<div
style={{
marginBottom: '20px',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '10px',
marginBottom: '10px',
}}
>
<CryptoIcon ledgerId={key} ticker={value.icon} size="56px" />
<CryptoIcon ledgerId={key} ticker={value.icon} size="48px" />
<CryptoIcon ledgerId={key} ticker={value.icon} size="40px" />
<CryptoIcon ledgerId={key} ticker={value.icon} size="32px" />
<CryptoIcon ledgerId={key} ticker={value.icon} size="24px" />
<CryptoIcon ledgerId={key} ticker={value.icon} />
</div>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '10px',
marginBottom: '10px',
}}
>
<CryptoIcon ledgerId={'none'} ticker={value.icon} size="56px" />
<CryptoIcon ledgerId={'none'} ticker={value.icon} size="48px" />
<CryptoIcon ledgerId={'none'} ticker={value.icon} size="40px" />
<CryptoIcon ledgerId={'none'} ticker={value.icon} size="32px" />
<CryptoIcon ledgerId={'none'} ticker={value.icon} size="24px" />
<CryptoIcon ledgerId={'none'} ticker={value.icon} />
</div>
</div>
</div>
))}
</div>
);

export const AllLedgerIcons: StoryFn = Template.bind({});
86 changes: 86 additions & 0 deletions lib/__tests__/CryptoIcon.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { render, screen, waitFor } from '@testing-library/react';
import { rest } from 'msw';
import React from 'react';
import { coinGeckoMock } from '../__mocks__/handlers';
import { server } from '../__mocks__/node';
import CryptoIcon from '../src/components/CryptoIcon';
import { COINGECKO_MAPPED_ASSETS_URL, CRYPTO_ICONS_CDN_BASE } from '../src/constants';
import { resetIconCacheForTesting } from '../src/iconMapping';

console.error = jest.fn();

describe('CryptoIcon', () => {
beforeEach(() => {
resetIconCacheForTesting();
});

describe('Ledger icon', () => {
it('should fetch index.json containing icon mapping and render icon from CDN', async () => {
render(<CryptoIcon ledgerId="bitcoin" ticker="BTC" />);

await waitFor(() => {
expect(screen.getByRole('img')).toBeInTheDocument();
});

expect(screen.getByRole('img')).toHaveAttribute('src', `${CRYPTO_ICONS_CDN_BASE}/BTC.png`);
});
});

describe('CoinGecko fallback', () => {
it('should fetch from CoinGecko and render fallback icon if request to Ledger CDN fails', async () => {
server.use(
rest.get(`${CRYPTO_ICONS_CDN_BASE}/index.json`, (_, res, ctx) => {
return res(ctx.status(500));
})
);

render(<CryptoIcon ledgerId="bitcoin" ticker="BTC" />);

await waitFor(() => {
expect(screen.getByRole('img')).toBeInTheDocument();
});

expect(screen.getByRole('img')).toHaveAttribute(
'src',
coinGeckoMock?.find((i) => i.ledgerId === 'bitcoin')?.data.img
);
});

it('should fetch from CoinGecko and render fallback icon if not found in Ledger CDN', async () => {
render(<CryptoIcon ledgerId="decred" ticker="DCR" />);

await waitFor(() => {
expect(screen.getByRole('img')).toBeInTheDocument();
});

expect(screen.getByRole('img')).toHaveAttribute(
'src',
coinGeckoMock?.find((i) => i.ledgerId === 'decred')?.data.img
);
});
});

describe('ticker icon fallback', () => {
it('should use ticker icon fallback if both Ledger and CoinGecko icons are not available', async () => {
server.use(
rest.get(`${CRYPTO_ICONS_CDN_BASE}/index.json`, (_, res, ctx) => {
return res(ctx.status(500));
})
);

server.use(
rest.get(COINGECKO_MAPPED_ASSETS_URL, (_, res, ctx) => {
return res(ctx.status(500));
})
);

render(<CryptoIcon ledgerId="bitcoin" ticker="BTC" />);

await waitFor(() => {
expect(screen.getByRole('img')).toBeInTheDocument();
});

expect(screen.getByRole('img')).toHaveTextContent('B');
});
});
});
3 changes: 3 additions & 0 deletions lib/__tests__/iconMapping.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
describe('iconMapping', () => {
it.todo('test caching logic');
});
16 changes: 16 additions & 0 deletions lib/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// eslint-disable-next-line no-undef
module.exports = {
roots: ['<rootDir>/__tests__'],
moduleFileExtensions: ['ts', 'tsx', 'js'],
transform: {
'^.+\\.tsx?$': [
'ts-jest',
{
tsconfig: '<rootDir>/tsconfig.spec.json',
},
],
},
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
testEnvironment: 'jsdom',
testMatch: ['**/*.test.(ts|tsx)'],
};
6 changes: 6 additions & 0 deletions lib/jest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import '@testing-library/jest-dom';
import { server } from './__mocks__/node';

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Loading