@monerium/sdk-react-provider 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.babelrc ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "presets": [
3
+ [
4
+ "@nx/react/babel",
5
+ {
6
+ "runtime": "automatic",
7
+ "useBuiltIns": "usage"
8
+ }
9
+ ]
10
+ ],
11
+ "plugins": []
12
+ }
package/.eslintrc.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "extends": ["plugin:@nx/react", "../../.eslintrc.json"],
3
+ "ignorePatterns": ["!**/*"],
4
+ "overrides": [
5
+ {
6
+ "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
7
+ "rules": {}
8
+ },
9
+ {
10
+ "files": ["*.ts", "*.tsx"],
11
+ "rules": {}
12
+ },
13
+ {
14
+ "files": ["*.js", "*.jsx"],
15
+ "rules": {}
16
+ }
17
+ ]
18
+ }
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # sdk-react-provider
2
+
3
+ This library was generated with [Nx](https://nx.dev).
4
+
5
+ ## Running unit tests
6
+
7
+ Run `nx test sdk-react-provider` to execute the unit tests via [Vitest](https://vitest.dev/).
package/jest.config.ts ADDED
@@ -0,0 +1,11 @@
1
+ /* eslint-disable */
2
+ export default {
3
+ displayName: 'sdk-react-provider',
4
+ preset: '../../jest.preset.js',
5
+ transform: {
6
+ '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nx/react/plugins/jest',
7
+ '^.+\\.[tj]sx?$': ['babel-jest', { presets: ['@nx/react/babel'] }],
8
+ },
9
+ moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
10
+ coverageDirectory: '../../coverage/libs/sdk-react-provider',
11
+ };
package/package.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@monerium/sdk-react-provider",
3
+ "version": "0.0.1",
4
+ "main": "./index.js",
5
+ "types": "./index.d.ts",
6
+ "exports": {
7
+ ".": {
8
+ "import": "./index.mjs",
9
+ "require": "./index.js"
10
+ }
11
+ }
12
+ }
package/project.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "sdk-react-provider",
3
+ "$schema": "../../node_modules/nx/schemas/project-schema.json",
4
+ "sourceRoot": "libs/sdk-react-provider/src",
5
+ "projectType": "library",
6
+ "tags": [],
7
+ "targets": {
8
+ "lint": {
9
+ "executor": "@nx/eslint:lint",
10
+ "outputs": ["{options.outputFile}"],
11
+ "options": {
12
+ "lintFilePatterns": ["libs/sdk-react-provider/**/*.{ts,tsx,js,jsx}"]
13
+ }
14
+ },
15
+ "build": {
16
+ "executor": "@nx/vite:build",
17
+ "outputs": ["{options.outputPath}"],
18
+ "defaultConfiguration": "production",
19
+ "options": {
20
+ "outputPath": "dist/libs/sdk-react-provider"
21
+ },
22
+ "configurations": {
23
+ "development": {
24
+ "mode": "development"
25
+ },
26
+ "production": {
27
+ "mode": "production"
28
+ }
29
+ }
30
+ },
31
+ "test": {
32
+ "executor": "@nx/jest:jest",
33
+ "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
34
+ "options": {
35
+ "jestConfig": "libs/sdk-react-provider/jest.config.ts",
36
+ "passWithNoTests": true
37
+ },
38
+ "configurations": {
39
+ "ci": {
40
+ "ci": true,
41
+ "codeCoverage": true
42
+ }
43
+ }
44
+ }
45
+ }
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './lib/provider';
2
+ export * from './lib/context';
3
+ export * from './lib/hook';
@@ -0,0 +1,31 @@
1
+ import { createContext } from 'react';
2
+ import {
3
+ Profile,
4
+ Balances,
5
+ LinkAddress,
6
+ Order,
7
+ NewOrder,
8
+ Token,
9
+ } from '@monerium/sdk';
10
+
11
+ interface MoneriumContextValue {
12
+ authorize: () => Promise<void>;
13
+ isAuthorized: boolean;
14
+ profile: Profile | null;
15
+ balances: Balances[] | null;
16
+ loading: boolean;
17
+ loadingPlaceOrder: boolean;
18
+ loadingLinkAddress: boolean;
19
+ loadingBalances: boolean;
20
+ getBalances: () => Promise<void>;
21
+ linkAddress: (addressDetails: LinkAddress) => Promise<unknown>;
22
+ placeOrder: (
23
+ orderDetails: NewOrder,
24
+ supportingDocument?: File
25
+ ) => Promise<void>;
26
+ orders: Order[];
27
+ tokens: Token[];
28
+ error: unknown;
29
+ }
30
+
31
+ export const MoneriumContext = createContext<MoneriumContextValue | null>(null);
@@ -0,0 +1,88 @@
1
+ import React from 'react';
2
+ import { render, screen, waitFor, act } from '@testing-library/react';
3
+ import '@testing-library/jest-dom';
4
+ import { useMonerium } from './hook';
5
+ import { MoneriumProvider } from './provider';
6
+ import { MoneriumClient } from '@monerium/sdk';
7
+
8
+ jest.mock('@monerium/sdk', () => {
9
+ const mockMoneriumClient = {
10
+ authorize: jest.fn().mockResolvedValue(true),
11
+ connect: jest.fn().mockResolvedValue(true),
12
+ disconnect: jest.fn(),
13
+ getAuthContext: jest
14
+ .fn()
15
+ .mockResolvedValue({ defaultProfile: 'defaultProfile' }),
16
+ getProfile: jest.fn().mockResolvedValue({
17
+ name: 'John Doe',
18
+ }),
19
+ getBalances: jest.fn().mockResolvedValue([
20
+ /* mock balance data */
21
+ ]),
22
+ getOrders: jest.fn().mockResolvedValue([
23
+ /* mock order data */
24
+ ]),
25
+ getTokens: jest.fn().mockResolvedValue([
26
+ /* mock token data */
27
+ ]),
28
+ };
29
+
30
+ return {
31
+ MoneriumClient: jest.fn(() => mockMoneriumClient),
32
+ MoneriumContext: jest.fn(() => null),
33
+ // mock other exports as needed
34
+ };
35
+ });
36
+
37
+ // Mock Test Consumer Component
38
+ const TestConsumerComponent = () => {
39
+ const context = useMonerium();
40
+
41
+ return (
42
+ <div>
43
+ <p data-testid="context">{JSON.stringify(context)}</p>
44
+ </div>
45
+ );
46
+ };
47
+
48
+ describe('useMonerium', () => {
49
+ test('returns the context value when used within a MoneriumProvider', async () => {
50
+ await act(async () => {
51
+ render(
52
+ <MoneriumProvider>
53
+ <TestConsumerComponent />
54
+ </MoneriumProvider>
55
+ );
56
+ });
57
+
58
+ await waitFor(() =>
59
+ expect(screen.getByTestId('context')).toHaveTextContent(
60
+ JSON.stringify({
61
+ isAuthorized: true,
62
+ profile: { name: 'John Doe' },
63
+ balances: [],
64
+ loading: false,
65
+ loadingPlaceOrder: false,
66
+ loadingLinkAddress: false,
67
+ loadingBalances: false,
68
+ orders: [],
69
+ tokens: [],
70
+ error: null,
71
+ })
72
+ )
73
+ );
74
+ });
75
+
76
+ test('throws an error when used outside a MoneriumProvider', () => {
77
+ // Suppress console error for this test
78
+ const consoleError = console.error;
79
+ console.error = jest.fn();
80
+
81
+ expect(() => render(<TestConsumerComponent />)).toThrow(
82
+ 'useMonerium must be used within a MoneriumProvider'
83
+ );
84
+
85
+ // Restore console error
86
+ console.error = consoleError;
87
+ });
88
+ });
@@ -0,0 +1,10 @@
1
+ import { useContext } from 'react';
2
+ import { MoneriumContext } from './context';
3
+
4
+ export function useMonerium() {
5
+ const context = useContext(MoneriumContext);
6
+ if (context === null) {
7
+ throw new Error('useMonerium must be used within a MoneriumProvider');
8
+ }
9
+ return context;
10
+ }
@@ -0,0 +1,82 @@
1
+ import React from 'react';
2
+ import { render, screen, waitFor } from '@testing-library/react';
3
+ import '@testing-library/jest-dom';
4
+ import { MoneriumProvider } from './provider';
5
+ import { useMonerium } from './hook';
6
+ import { MoneriumClient } from '@monerium/sdk';
7
+
8
+ jest.mock('@monerium/sdk', () => {
9
+ const mockMoneriumClient = {
10
+ authorize: jest.fn().mockResolvedValue(true),
11
+ connect: jest.fn().mockResolvedValue(true),
12
+ disconnect: jest.fn(),
13
+ getAuthContext: jest
14
+ .fn()
15
+ .mockResolvedValue({ defaultProfile: 'defaultProfile' }),
16
+ getProfile: jest.fn().mockResolvedValue({
17
+ name: 'John Doe',
18
+ }),
19
+ getBalances: jest.fn().mockResolvedValue([
20
+ /* mock balance data */
21
+ ]),
22
+ getOrders: jest.fn().mockResolvedValue([
23
+ /* mock order data */
24
+ ]),
25
+ getTokens: jest.fn().mockResolvedValue([
26
+ /* mock token data */
27
+ ]),
28
+ // mock other methods as needed
29
+ };
30
+
31
+ return {
32
+ MoneriumClient: jest.fn(() => mockMoneriumClient),
33
+ // mock other exports as needed
34
+ };
35
+ });
36
+ // Mock Test Consumer Component
37
+ const TestConsumerComponent = () => {
38
+ const {
39
+ authorize,
40
+ isAuthorized,
41
+ profile,
42
+ // include other pieces of context you want to test
43
+ } = useMonerium();
44
+
45
+ return (
46
+ <div>
47
+ <button onClick={authorize}>Authorize</button>
48
+ {isAuthorized && <p>Authorized!</p>}
49
+ {profile && <p data-testid="profile">{profile.name}</p>}
50
+ {/* You can add more elements for other context values */}
51
+ </div>
52
+ );
53
+ };
54
+
55
+ describe('MoneriumProvider', () => {
56
+ test('provides context to consumer and allows function calls', async () => {
57
+ render(
58
+ <MoneriumProvider>
59
+ <TestConsumerComponent />
60
+ </MoneriumProvider>
61
+ );
62
+
63
+ // Test initial state
64
+ expect(screen.queryByText('Authorized!')).toBeNull();
65
+
66
+ // Simulate button click to authorize
67
+ screen.getByRole('button', { name: /authorize/i }).click();
68
+
69
+ // Test if authorize function has been called
70
+ await waitFor(() =>
71
+ expect(screen.getByText('Authorized!')).toBeInTheDocument()
72
+ );
73
+
74
+ // Test if profile data is present
75
+ await waitFor(() => {
76
+ expect(screen.getByTestId('profile')).toBeInTheDocument();
77
+ expect(screen.getByTestId('profile')).toHaveTextContent('John Doe');
78
+ });
79
+ });
80
+
81
+ // Add more tests for other functions and state changes
82
+ });
@@ -0,0 +1,188 @@
1
+ import React, { useCallback, FC, useEffect, useState, ReactNode } from 'react';
2
+
3
+ import { MoneriumContext } from './context';
4
+
5
+ import {
6
+ MoneriumClient,
7
+ LinkAddress,
8
+ Profile,
9
+ Balances,
10
+ Order,
11
+ NewOrder,
12
+ Token,
13
+ } from '@monerium/sdk';
14
+
15
+ interface MoneriumProviderProps {
16
+ children: ReactNode;
17
+ clientId?: string;
18
+ redirectUrl?: string;
19
+ }
20
+
21
+ export const MoneriumProvider: FC<MoneriumProviderProps> = ({
22
+ children,
23
+ clientId = 'f99e629b-6dca-11ee-8aa6-5273f65ed05b',
24
+ redirectUrl = 'http://localhost:5173',
25
+ }) => {
26
+ const [monerium, setMonerium] = useState<MoneriumClient>();
27
+ const [isAuthorized, setIsAuthorized] = useState<boolean>(false);
28
+ const [profile, setProfile] = useState<Profile | null>(null);
29
+ const [balances, setBalances] = useState<Balances[] | null>(null);
30
+ const [loading, setLoading] = useState(false);
31
+ const [loadingPlaceOrder, setLoadingPlaceOrder] = useState(false);
32
+ const [loadingLinkAddress, setLoadingLinkAddress] = useState(false);
33
+ const [loadingBalances, setLoadingBalances] = useState(false);
34
+ const [error, setError] = useState<Error | unknown | null>(null);
35
+ const [orders, setOrders] = useState<Order[]>([]);
36
+ const [tokens, setTokens] = useState<Token[]>([]);
37
+
38
+ // Initialize the SDK
39
+ useEffect(() => {
40
+ const sdk = new MoneriumClient({
41
+ clientId,
42
+ redirectUrl,
43
+ });
44
+ setMonerium(sdk);
45
+ }, []);
46
+
47
+ useEffect(() => {
48
+ const connect = async () => {
49
+ if (monerium) {
50
+ setIsAuthorized(await monerium.connect());
51
+ }
52
+ };
53
+
54
+ connect();
55
+
56
+ return () => {
57
+ if (monerium) {
58
+ monerium.disconnect();
59
+ }
60
+ };
61
+ }, [monerium]);
62
+
63
+ useEffect(() => {
64
+ const fetchData = async () => {
65
+ if (monerium && isAuthorized) {
66
+ try {
67
+ setLoading(true);
68
+ const authCtx = await monerium.getAuthContext();
69
+ const profileData = await monerium.getProfile(authCtx.defaultProfile);
70
+ const balanceData = await monerium.getBalances();
71
+ const ordersData = await monerium.getOrders();
72
+ const tokensData = await monerium.getTokens();
73
+ setProfile(profileData);
74
+ setBalances(balanceData);
75
+ setOrders(ordersData);
76
+ setTokens(tokensData);
77
+ } catch (err) {
78
+ console.error('Error fetching data:', err);
79
+ setError(err);
80
+ } finally {
81
+ setLoading(false);
82
+ }
83
+ }
84
+ };
85
+
86
+ fetchData();
87
+ }, [monerium, isAuthorized]);
88
+
89
+ const authorize = useCallback(async () => {
90
+ try {
91
+ if (monerium) {
92
+ await monerium.authorize();
93
+ }
94
+ } catch (err) {
95
+ console.error('Error during authorization:', err);
96
+ setError(err);
97
+ }
98
+ }, [monerium]);
99
+
100
+ const getBalances = useCallback(async () => {
101
+ if (monerium && isAuthorized) {
102
+ try {
103
+ setLoadingBalances(true);
104
+ const balances = await monerium.getBalances();
105
+ setBalances(balances);
106
+ } catch (err) {
107
+ console.error('Error getting balances:', err);
108
+ setError(err);
109
+ } finally {
110
+ setLoadingBalances(false);
111
+ }
112
+ }
113
+ }, [monerium, isAuthorized]);
114
+
115
+ const placeOrder = useCallback(
116
+ async (orderDetails: NewOrder, supportingDocument?: File) => {
117
+ if (monerium && isAuthorized) {
118
+ try {
119
+ setLoadingPlaceOrder(true);
120
+
121
+ let documentId;
122
+ if (parseInt(orderDetails.amount) > 15000 && supportingDocument) {
123
+ const uploadedDocument = await monerium.uploadSupportingDocument(
124
+ supportingDocument
125
+ );
126
+ documentId = uploadedDocument.id;
127
+ }
128
+
129
+ const newOrderDetails = {
130
+ ...orderDetails,
131
+ documentId: documentId,
132
+ };
133
+
134
+ const newOrder = await monerium.placeOrder(newOrderDetails);
135
+ setOrders((prevOrders) => [...prevOrders, newOrder]);
136
+ } catch (err) {
137
+ console.error('Error placing order:', err);
138
+ setError(err);
139
+ } finally {
140
+ setLoadingPlaceOrder(false);
141
+ }
142
+ }
143
+ },
144
+ [monerium, isAuthorized]
145
+ );
146
+
147
+ const linkAddress = useCallback(
148
+ async (addressDetails: LinkAddress) => {
149
+ if (monerium && isAuthorized && profile) {
150
+ try {
151
+ setLoadingLinkAddress(true);
152
+ return await monerium.linkAddress(profile.id, addressDetails);
153
+
154
+ // Update your state or do something with linkedAddress
155
+ } catch (err) {
156
+ console.error('Error linking address:', err);
157
+ setError(err);
158
+ } finally {
159
+ setLoadingLinkAddress(false);
160
+ }
161
+ }
162
+ },
163
+ [monerium, isAuthorized, profile]
164
+ );
165
+
166
+ return (
167
+ <MoneriumContext.Provider
168
+ value={{
169
+ authorize,
170
+ isAuthorized,
171
+ profile,
172
+ balances,
173
+ loading,
174
+ loadingPlaceOrder,
175
+ loadingLinkAddress,
176
+ loadingBalances,
177
+ getBalances,
178
+ linkAddress,
179
+ placeOrder,
180
+ orders,
181
+ tokens,
182
+ error,
183
+ }}
184
+ >
185
+ {children}
186
+ </MoneriumContext.Provider>
187
+ );
188
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "jsx": "react-jsx",
4
+ "allowJs": false,
5
+ "esModuleInterop": false,
6
+ "allowSyntheticDefaultImports": true,
7
+ "strict": true,
8
+ "types": ["vite/client"]
9
+ },
10
+ "files": [],
11
+ "include": [],
12
+ "references": [
13
+ {
14
+ "path": "./tsconfig.lib.json"
15
+ },
16
+ {
17
+ "path": "./tsconfig.spec.json"
18
+ }
19
+ ],
20
+ "extends": "../../tsconfig.base.json"
21
+ }
@@ -0,0 +1,23 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "../../dist/out-tsc",
5
+ "types": [
6
+ "node",
7
+ "@nx/react/typings/cssmodule.d.ts",
8
+ "@nx/react/typings/image.d.ts",
9
+ "vite/client"
10
+ ]
11
+ },
12
+ "exclude": [
13
+ "**/*.spec.ts",
14
+ "**/*.test.ts",
15
+ "**/*.spec.tsx",
16
+ "**/*.test.tsx",
17
+ "**/*.spec.js",
18
+ "**/*.test.js",
19
+ "**/*.spec.jsx",
20
+ "**/*.test.jsx"
21
+ ],
22
+ "include": ["src/**/*.js", "src/**/*.jsx", "src/**/*.ts", "src/**/*.tsx"]
23
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "../../dist/out-tsc",
5
+ "module": "commonjs",
6
+ "types": ["jest", "node"]
7
+ },
8
+ "include": [
9
+ "jest.config.ts",
10
+ "src/**/*.test.ts",
11
+ "src/**/*.spec.ts",
12
+ "src/**/*.test.tsx",
13
+ "src/**/*.spec.tsx",
14
+ "src/**/*.test.js",
15
+ "src/**/*.spec.js",
16
+ "src/**/*.test.jsx",
17
+ "src/**/*.spec.jsx",
18
+ "src/**/*.d.ts"
19
+ ]
20
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,43 @@
1
+ /// <reference types='vitest' />
2
+ import { defineConfig } from 'vite';
3
+ import react from '@vitejs/plugin-react';
4
+ import dts from 'vite-plugin-dts';
5
+ import * as path from 'path';
6
+ import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
7
+
8
+ export default defineConfig({
9
+ cacheDir: '../../node_modules/.vite/sdk-react-provider',
10
+
11
+ plugins: [
12
+ react(),
13
+ nxViteTsPaths(),
14
+ dts({
15
+ entryRoot: 'src',
16
+ tsConfigFilePath: path.join(__dirname, 'tsconfig.lib.json'),
17
+ skipDiagnostics: true,
18
+ }),
19
+ ],
20
+
21
+ // Uncomment this if you are using workers.
22
+ // worker: {
23
+ // plugins: [ nxViteTsPaths() ],
24
+ // },
25
+
26
+ // Configuration for building your library.
27
+ // See: https://vitejs.dev/guide/build.html#library-mode
28
+ build: {
29
+ lib: {
30
+ // Could also be a dictionary or array of multiple entry points.
31
+ entry: 'src/index.ts',
32
+ name: 'sdk-react-provider',
33
+ fileName: 'index',
34
+ // Change this to the formats you want to support.
35
+ // Don't forget to update your package.json as well.
36
+ formats: ['es', 'cjs'],
37
+ },
38
+ rollupOptions: {
39
+ // External packages that should not be bundled into your library.
40
+ external: ['react', 'react-dom', 'react/jsx-runtime'],
41
+ },
42
+ },
43
+ });