@ultraos/wallet-sdk 0.0.4 → 0.0.5

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.
Files changed (37) hide show
  1. package/package.json +4 -3
  2. package/LICENSE +0 -165
  3. package/README.md +0 -74
  4. package/dist/libs/wallet-sdk/libs/wallet-sdk/README.md +0 -74
  5. package/eslint.config.js +0 -5
  6. package/jest.config.ts +0 -11
  7. package/karma.conf.js +0 -16
  8. package/project.json +0 -33
  9. package/src/index.ts +0 -2
  10. package/src/lib/common/client-error.ts +0 -14
  11. package/src/lib/common/client-messenger.spec.ts +0 -118
  12. package/src/lib/common/client-messenger.ts +0 -109
  13. package/src/lib/common/window-manager.spec.ts +0 -65
  14. package/src/lib/common/window-manager.ts +0 -34
  15. package/src/lib/config/ultra-wallet-sdk.config.ts +0 -37
  16. package/src/lib/interfaces/blockchain-transaction.interface.ts +0 -21
  17. package/src/lib/interfaces/connect-params.interface.ts +0 -13
  18. package/src/lib/interfaces/error-enum.ts +0 -15
  19. package/src/lib/interfaces/index.ts +0 -8
  20. package/src/lib/interfaces/json-rpc-message.interface.ts +0 -7
  21. package/src/lib/interfaces/purchase-item.interface.ts +0 -7
  22. package/src/lib/interfaces/wallet-provider-response.interface.ts +0 -157
  23. package/src/lib/interfaces/wallet-provider.interface.ts +0 -55
  24. package/src/lib/interfaces/wallet-sdk-options.interface.ts +0 -9
  25. package/src/lib/providers/extension-provider/extension.provider.spec.ts +0 -121
  26. package/src/lib/providers/extension-provider/extension.provider.ts +0 -55
  27. package/src/lib/providers/index.ts +0 -2
  28. package/src/lib/providers/web-provider/web.provider.spec.ts +0 -76
  29. package/src/lib/providers/web-provider/web.provider.ts +0 -59
  30. package/src/lib/ultra-wallet-sdk.spec.ts +0 -90
  31. package/src/lib/ultra-wallet-sdk.ts +0 -67
  32. package/src/lib/utils/chain-validator.ts +0 -6
  33. package/src/lib/utils/detection.ts +0 -3
  34. package/tsconfig.json +0 -28
  35. package/tsconfig.lib.json +0 -12
  36. package/tsconfig.lib.prod.json +0 -9
  37. package/tsconfig.spec.json +0 -8
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "@ultraos/wallet-sdk",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "homepage": "https://developers.ultra.io",
5
5
  "dependencies": {
6
6
  "tslib": "^2.3.0"
7
7
  },
8
- "type": "commonjs",
8
+ "type": "module",
9
9
  "main": "./src/index.js",
10
10
  "typings": "./src/index.d.ts",
11
11
  "publishConfig": {
12
12
  "access": "public"
13
- }
13
+ },
14
+ "module": "./src/index.js"
14
15
  }
package/LICENSE DELETED
@@ -1,165 +0,0 @@
1
- GNU LESSER GENERAL PUBLIC LICENSE
2
- Version 3, 29 June 2007
3
-
4
- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
- Everyone is permitted to copy and distribute verbatim copies
6
- of this license document, but changing it is not allowed.
7
-
8
-
9
- This version of the GNU Lesser General Public License incorporates
10
- the terms and conditions of version 3 of the GNU General Public
11
- License, supplemented by the additional permissions listed below.
12
-
13
- 0. Additional Definitions.
14
-
15
- As used herein, "this License" refers to version 3 of the GNU Lesser
16
- General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
- General Public License.
18
-
19
- "The Library" refers to a covered work governed by this License,
20
- other than an Application or a Combined Work as defined below.
21
-
22
- An "Application" is any work that makes use of an interface provided
23
- by the Library, but which is not otherwise based on the Library.
24
- Defining a subclass of a class defined by the Library is deemed a mode
25
- of using an interface provided by the Library.
26
-
27
- A "Combined Work" is a work produced by combining or linking an
28
- Application with the Library. The particular version of the Library
29
- with which the Combined Work was made is also called the "Linked
30
- Version".
31
-
32
- The "Minimal Corresponding Source" for a Combined Work means the
33
- Corresponding Source for the Combined Work, excluding any source code
34
- for portions of the Combined Work that, considered in isolation, are
35
- based on the Application, and not on the Linked Version.
36
-
37
- The "Corresponding Application Code" for a Combined Work means the
38
- object code and/or source code for the Application, including any data
39
- and utility programs needed for reproducing the Combined Work from the
40
- Application, but excluding the System Libraries of the Combined Work.
41
-
42
- 1. Exception to Section 3 of the GNU GPL.
43
-
44
- You may convey a covered work under sections 3 and 4 of this License
45
- without being bound by section 3 of the GNU GPL.
46
-
47
- 2. Conveying Modified Versions.
48
-
49
- If you modify a copy of the Library, and, in your modifications, a
50
- facility refers to a function or data to be supplied by an Application
51
- that uses the facility (other than as an argument passed when the
52
- facility is invoked), then you may convey a copy of the modified
53
- version:
54
-
55
- a) under this License, provided that you make a good faith effort to
56
- ensure that, in the event an Application does not supply the
57
- function or data, the facility still operates, and performs
58
- whatever part of its purpose remains meaningful, or
59
-
60
- b) under the GNU GPL, with none of the additional permissions of
61
- this License applicable to that copy.
62
-
63
- 3. Object Code Incorporating Material from Library Header Files.
64
-
65
- The object code form of an Application may incorporate material from
66
- a header file that is part of the Library. You may convey such object
67
- code under terms of your choice, provided that, if the incorporated
68
- material is not limited to numerical parameters, data structure
69
- layouts and accessors, or small macros, inline functions and templates
70
- (ten or fewer lines in length), you do both of the following:
71
-
72
- a) Give prominent notice with each copy of the object code that the
73
- Library is used in it and that the Library and its use are
74
- covered by this License.
75
-
76
- b) Accompany the object code with a copy of the GNU GPL and this license
77
- document.
78
-
79
- 4. Combined Works.
80
-
81
- You may convey a Combined Work under terms of your choice that,
82
- taken together, effectively do not restrict modification of the
83
- portions of the Library contained in the Combined Work and reverse
84
- engineering for debugging such modifications, if you also do each of
85
- the following:
86
-
87
- a) Give prominent notice with each copy of the Combined Work that
88
- the Library is used in it and that the Library and its use are
89
- covered by this License.
90
-
91
- b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
- document.
93
-
94
- c) For a Combined Work that displays copyright notices during
95
- execution, include the copyright notice for the Library among
96
- these notices, as well as a reference directing the user to the
97
- copies of the GNU GPL and this license document.
98
-
99
- d) Do one of the following:
100
-
101
- 0) Convey the Minimal Corresponding Source under the terms of this
102
- License, and the Corresponding Application Code in a form
103
- suitable for, and under terms that permit, the user to
104
- recombine or relink the Application with a modified version of
105
- the Linked Version to produce a modified Combined Work, in the
106
- manner specified by section 6 of the GNU GPL for conveying
107
- Corresponding Source.
108
-
109
- 1) Use a suitable shared library mechanism for linking with the
110
- Library. A suitable mechanism is one that (a) uses at run time
111
- a copy of the Library already present on the user's computer
112
- system, and (b) will operate properly with a modified version
113
- of the Library that is interface-compatible with the Linked
114
- Version.
115
-
116
- e) Provide Installation Information, but only if you would otherwise
117
- be required to provide such information under section 6 of the
118
- GNU GPL, and only to the extent that such information is
119
- necessary to install and execute a modified version of the
120
- Combined Work produced by recombining or relinking the
121
- Application with a modified version of the Linked Version. (If
122
- you use option 4d0, the Installation Information must accompany
123
- the Minimal Corresponding Source and Corresponding Application
124
- Code. If you use option 4d1, you must provide the Installation
125
- Information in the manner specified by section 6 of the GNU GPL
126
- for conveying Corresponding Source.)
127
-
128
- 5. Combined Libraries.
129
-
130
- You may place library facilities that are a work based on the
131
- Library side by side in a single library together with other library
132
- facilities that are not Applications and are not covered by this
133
- License, and convey such a combined library under terms of your
134
- choice, if you do both of the following:
135
-
136
- a) Accompany the combined library with a copy of the same work based
137
- on the Library, uncombined with any other library facilities,
138
- conveyed under the terms of this License.
139
-
140
- b) Give prominent notice with the combined library that part of it
141
- is a work based on the Library, and explaining where to find the
142
- accompanying uncombined form of the same work.
143
-
144
- 6. Revised Versions of the GNU Lesser General Public License.
145
-
146
- The Free Software Foundation may publish revised and/or new versions
147
- of the GNU Lesser General Public License from time to time. Such new
148
- versions will be similar in spirit to the present version, but may
149
- differ in detail to address new problems or concerns.
150
-
151
- Each version is given a distinguishing version number. If the
152
- Library as you received it specifies that a certain numbered version
153
- of the GNU Lesser General Public License "or any later version"
154
- applies to it, you have the option of following the terms and
155
- conditions either of that published version or of any later version
156
- published by the Free Software Foundation. If the Library as you
157
- received it does not specify a version number of the GNU Lesser
158
- General Public License, you may choose any version of the GNU Lesser
159
- General Public License ever published by the Free Software Foundation.
160
-
161
- If the Library as you received it specifies that a proxy can decide
162
- whether future versions of the GNU Lesser General Public License shall
163
- apply, that proxy's public statement of acceptance of any version is
164
- permanent authorization for you to choose that version for the
165
- Library.
package/README.md DELETED
@@ -1,74 +0,0 @@
1
- # Ultra Wallet SDK
2
-
3
- Ultra Wallet SDK provides an easy-to-use client for interacting with the Ultra blockchain wallet, either through the
4
- browser extension or via a web fallback.
5
-
6
- ## ✨ Features
7
-
8
- - Automatically detects and uses the Ultra Wallet Extension if available.
9
- - Falls back to a Web Wallet if the extension is not installed.
10
- - Connect, sign messages, sign transactions, and initiate purchases with a simple API.
11
- - Environment support: `mainnet`, `testnet`, or custom wallet URLs.
12
-
13
- ## 📦 Installation
14
-
15
- ```bash
16
- npm install @ultraos/wallet-sdk
17
- ```
18
-
19
- or
20
-
21
- ```bash
22
- yarn add @ultraos/wallet-sdk
23
- ```
24
-
25
- ## 🚀 Usage
26
-
27
- ```ts
28
- import { UltraWalletSDK } from '@ultraos/wallet-sdk';
29
-
30
- // Basic initialization (auto-detect extension or fallback to mainnet Web Wallet)
31
- const ultra = new UltraWalletSDK();
32
-
33
- // Optionally initialize with environment configuration
34
- const ultraTestnet = new UltraWalletSDK({ environment: 'testnet' });
35
-
36
- // Connect
37
- await ultra.connect();
38
-
39
- // Sign a message
40
- const signature = await ultra.signMessage('message: Hello, Ultra!');
41
-
42
- // Sign a transaction
43
- await ultra.signTransaction({
44
- contract: 'eosio.token',
45
- action: 'transfer',
46
- data: { from: 'user', to: 'receiver', quantity: '1.00000000 UOS', memo: '' },
47
- authorizations: ['user@active'],
48
- });
49
- ```
50
-
51
- ## ⚙️ Configuration
52
-
53
- You can pass options during initialization:
54
-
55
- ```ts
56
- new UltraWalletSDK({
57
- environment: 'testnet', // or 'mainnet', or provide custom URL
58
- });
59
- ```
60
-
61
- ## 📚 API
62
-
63
- ### Methods
64
-
65
- - `connect(): Promise<ConnectResult>`
66
- - `disconnect(): Promise<void>`
67
- - `signMessage(message: string): Promise<string>`
68
- - `signTransaction(transaction: BlockchainTransaction | BlockchainTransaction[]): Promise<SignTransactionResult>`
69
- - `getChainId(): Promise<string>`
70
- - `purchaseItem(itemType: PurchaseItemType, itemId: string): Promise<PurchaseItemResult>`
71
-
72
- ---
73
-
74
- Tests are run with [Jest](https://jestjs.io).
@@ -1,74 +0,0 @@
1
- # Ultra Wallet SDK
2
-
3
- Ultra Wallet SDK provides an easy-to-use client for interacting with the Ultra blockchain wallet, either through the
4
- browser extension or via a web fallback.
5
-
6
- ## ✨ Features
7
-
8
- - Automatically detects and uses the Ultra Wallet Extension if available.
9
- - Falls back to a Web Wallet if the extension is not installed.
10
- - Connect, sign messages, sign transactions, and initiate purchases with a simple API.
11
- - Environment support: `mainnet`, `testnet`, or custom wallet URLs.
12
-
13
- ## 📦 Installation
14
-
15
- ```bash
16
- npm install @ultraos/wallet-sdk
17
- ```
18
-
19
- or
20
-
21
- ```bash
22
- yarn add @ultraos/wallet-sdk
23
- ```
24
-
25
- ## 🚀 Usage
26
-
27
- ```ts
28
- import { UltraWalletSDK } from '@ultraos/wallet-sdk';
29
-
30
- // Basic initialization (auto-detect extension or fallback to mainnet Web Wallet)
31
- const ultra = new UltraWalletSDK();
32
-
33
- // Optionally initialize with environment configuration
34
- const ultraTestnet = new UltraWalletSDK({ environment: 'testnet' });
35
-
36
- // Connect
37
- await ultra.connect();
38
-
39
- // Sign a message
40
- const signature = await ultra.signMessage('message: Hello, Ultra!');
41
-
42
- // Sign a transaction
43
- await ultra.signTransaction({
44
- contract: 'eosio.token',
45
- action: 'transfer',
46
- data: { from: 'user', to: 'receiver', quantity: '1.00000000 UOS', memo: '' },
47
- authorizations: ['user@active'],
48
- });
49
- ```
50
-
51
- ## ⚙️ Configuration
52
-
53
- You can pass options during initialization:
54
-
55
- ```ts
56
- new UltraWalletSDK({
57
- environment: 'testnet', // or 'mainnet', or provide custom URL
58
- });
59
- ```
60
-
61
- ## 📚 API
62
-
63
- ### Methods
64
-
65
- - `connect(): Promise<ConnectResult>`
66
- - `disconnect(): Promise<void>`
67
- - `signMessage(message: string): Promise<string>`
68
- - `signTransaction(transaction: BlockchainTransaction | BlockchainTransaction[]): Promise<SignTransactionResult>`
69
- - `getChainId(): Promise<string>`
70
- - `purchaseItem(itemType: PurchaseItemType, itemId: string): Promise<PurchaseItemResult>`
71
-
72
- ---
73
-
74
- Tests are run with [Jest](https://jestjs.io).
package/eslint.config.js DELETED
@@ -1,5 +0,0 @@
1
- const eslintrcOverrides = require('../../eslintrc-overrides.config.js');
2
-
3
- const baseConfig = require('../../eslint.config.js');
4
-
5
- module.exports = [...baseConfig, ...eslintrcOverrides];
package/jest.config.ts DELETED
@@ -1,11 +0,0 @@
1
- /* eslint-disable */
2
- export default {
3
- displayName: 'wallet-sdk',
4
- preset: '../../jest.preset.js',
5
- testEnvironment: 'jsdom',
6
- transform: {
7
- '^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
8
- },
9
- moduleFileExtensions: ['ts', 'js', 'html'],
10
- coverageDirectory: '../../coverage/libs/wallet-sdk',
11
- };
package/karma.conf.js DELETED
@@ -1,16 +0,0 @@
1
- // Karma configuration file, see link for more information
2
- // https://karma-runner.github.io/6.4/config/configuration-file.html
3
-
4
- const { join } = require('path');
5
- const getBaseKarmaConfig = require('../../karma.conf');
6
-
7
- module.exports = function (config) {
8
- const baseConfig = getBaseKarmaConfig();
9
- config.set({
10
- ...baseConfig,
11
- coverageReporter: {
12
- ...baseConfig.coverageReporter,
13
- dir: join(__dirname, '../../coverage/libs/wallet-sdk'),
14
- },
15
- });
16
- };
package/project.json DELETED
@@ -1,33 +0,0 @@
1
- {
2
- "name": "wallet-sdk",
3
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
4
- "sourceRoot": "libs/wallet-sdk/src",
5
- "projectType": "library",
6
- "targets": {
7
- "build": {
8
- "executor": "@nx/js:tsc",
9
- "outputs": ["{options.outputPath}"],
10
- "options": {
11
- "outputPath": "dist/libs/wallet-sdk",
12
- "main": "libs/wallet-sdk/src/index.ts",
13
- "tsConfig": "libs/wallet-sdk/tsconfig.lib.json",
14
- "assets": ["libs/wallet-sdk/*.md"]
15
- }
16
- },
17
- "publish": {
18
- "command": "node tools/scripts/publish.mjs wallet-sdk {args.ver} {args.tag}",
19
- "dependsOn": ["build"]
20
- },
21
- "lint": {
22
- "executor": "@nx/eslint:lint"
23
- },
24
- "test": {
25
- "executor": "@nx/jest:jest",
26
- "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
27
- "options": {
28
- "jestConfig": "libs/wallet-sdk/jest.config.ts"
29
- }
30
- }
31
- },
32
- "tags": ["type:lib", "type:sdk"]
33
- }
package/src/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './lib/interfaces';
2
- export * from './lib/ultra-wallet-sdk';
@@ -1,14 +0,0 @@
1
- import { SDK_ERROR_MESSAGE, SdkErrorCode } from '../interfaces';
2
-
3
- export class ClientError extends Error {
4
- override message: string;
5
-
6
- constructor(
7
- public code: SdkErrorCode,
8
- public data?,
9
- ) {
10
- super();
11
- this.message = SDK_ERROR_MESSAGE[code];
12
- this.name = this.constructor.name;
13
- }
14
- }
@@ -1,118 +0,0 @@
1
- import { ClientMessenger } from './client-messenger';
2
- import { WindowManager } from './window-manager';
3
- import { ResponseStatus, SdkErrorCode } from '../interfaces';
4
-
5
- jest.mock('./window-manager');
6
-
7
- describe('ClientMessenger', () => {
8
- let messenger: ClientMessenger;
9
- let windowManager: jest.Mocked<WindowManager>;
10
- let walletWindow: jest.Mocked<Window>;
11
-
12
- beforeEach(() => {
13
- walletWindow = {
14
- closed: false,
15
- postMessage: jest.fn(),
16
- close: jest.fn(),
17
- } as unknown as jest.Mocked<Window>;
18
-
19
- windowManager = new WindowManager('https://wallet.ultra.io') as jest.Mocked<WindowManager>;
20
- windowManager.getWalletWindow.mockReturnValue(walletWindow);
21
- windowManager.openOrReuseWallet.mockImplementation(() => {});
22
-
23
- messenger = new ClientMessenger(windowManager);
24
- });
25
-
26
- afterEach(() => {
27
- jest.clearAllMocks();
28
- });
29
-
30
- function fireWalletReady() {
31
- window.dispatchEvent(
32
- new MessageEvent('message', {
33
- origin: 'https://wallet.ultra.io',
34
- data: { jsonrpc: '2.0', method: 'ready' },
35
- }),
36
- );
37
- }
38
-
39
- function fireWalletResponse(id: string, result: any) {
40
- window.dispatchEvent(
41
- new MessageEvent('message', {
42
- origin: 'https://wallet.ultra.io',
43
- data: { jsonrpc: '2.0', id, result },
44
- }),
45
- );
46
- }
47
-
48
- it('resolves request after wallet ready and response received', async () => {
49
- Object.defineProperty(windowManager, 'walletUrl', { get: () => 'https://wallet.ultra.io' });
50
- const requestPromise = messenger.sendRequest('connect', {});
51
- fireWalletReady();
52
-
53
- // Wait one event loop tick to allow postMessage to be called
54
- await new Promise((resolve) => setTimeout(resolve, 0));
55
-
56
- // Extract the actual ID sent
57
- const [[message]] = (walletWindow.postMessage as jest.Mock).mock.calls;
58
- const requestId = message.id;
59
- fireWalletResponse(requestId, { status: ResponseStatus.SUCCESS, data: { address: 'abc' } });
60
-
61
- await expect(requestPromise).resolves.toEqual({
62
- status: ResponseStatus.SUCCESS,
63
- data: { address: 'abc' },
64
- });
65
- });
66
-
67
- it('rejects if window is closed before ready', async () => {
68
- Object.defineProperty(walletWindow, 'closed', { get: () => true });
69
- const requestPromise = messenger.sendRequest('connect', {});
70
- await expect(requestPromise).rejects.toEqual({
71
- status: ResponseStatus.ERROR,
72
- code: SdkErrorCode.USER_REJECTED_REQUEST,
73
- message: expect.any(String),
74
- });
75
- });
76
-
77
- it('rejects if wallet window is not available', async () => {
78
- windowManager.getWalletWindow.mockReturnValue(null);
79
- await expect(messenger.sendRequest('connect', {})).rejects.toEqual({
80
- status: ResponseStatus.ERROR,
81
- code: SdkErrorCode.WALLET_WINDOW_UNAVAILABLE,
82
- message: expect.any(String),
83
- });
84
- });
85
-
86
- it('rejects if wallet does not become ready before timeout', async () => {
87
- jest.useFakeTimers();
88
- const promise = messenger.sendRequest('connect', {});
89
- jest.advanceTimersByTime(10000); // simulate timeout
90
- await expect(promise).rejects.toEqual({
91
- status: ResponseStatus.ERROR,
92
- code: SdkErrorCode.WALLET_HANDSHAKE_TIMEOUT,
93
- message: expect.any(String),
94
- });
95
- jest.useRealTimers();
96
- });
97
-
98
- it('rejects on rpcClient.request failure', async () => {
99
- Object.defineProperty(windowManager, 'walletUrl', { get: () => 'https://wallet.ultra.io' });
100
- const promise = messenger.sendRequest('connect', {});
101
- fireWalletReady();
102
-
103
- // Extract the actual ID sent
104
- const [[message]] = (walletWindow.postMessage as jest.Mock).mock.calls;
105
- const requestId = message.id;
106
- fireWalletResponse(requestId, {
107
- status: ResponseStatus.ERROR,
108
- code: SdkErrorCode.UNKNOWN_ERROR,
109
- message: 'error',
110
- });
111
-
112
- await expect(promise).rejects.toEqual({
113
- status: ResponseStatus.ERROR,
114
- code: SdkErrorCode.UNKNOWN_ERROR,
115
- message: expect.any(String),
116
- });
117
- });
118
- });
@@ -1,109 +0,0 @@
1
- import { JSONRPCClient } from 'json-rpc-2.0';
2
-
3
- import UltraWalletSdkConfig from '../config/ultra-wallet-sdk.config';
4
- import { JsonRpcMessage, ResponseStatus, SdkErrorCode, UltraResponse } from '../interfaces';
5
-
6
- import { ClientError } from './client-error';
7
- import { WindowManager } from './window-manager';
8
-
9
- export class ClientMessenger {
10
- private windowManager: WindowManager;
11
- private rpcClient: JSONRPCClient;
12
- private pendingRequest = false;
13
-
14
- constructor(windowManager: WindowManager) {
15
- this.windowManager = windowManager;
16
-
17
- this.rpcClient = new JSONRPCClient((request) => {
18
- const walletWindow = this.windowManager.getWalletWindow();
19
- if (!walletWindow) {
20
- return Promise.reject(new ClientError(SdkErrorCode.WALLET_WINDOW_UNAVAILABLE));
21
- }
22
- walletWindow.postMessage(request, this.windowManager.walletUrl);
23
- return Promise.resolve();
24
- });
25
-
26
- window.addEventListener('message', (event) => {
27
- if (event.origin === this.windowManager.walletUrl && event.data?.jsonrpc === '2.0') {
28
- this.rpcClient.receive(event.data);
29
- }
30
- });
31
- }
32
-
33
- async sendRequest<T>(requestMethod: string, requestParams: object): Promise<UltraResponse<T>> {
34
- if (this.pendingRequest && this.windowManager.getWalletWindow()?.closed === false) {
35
- const { code, message } = new ClientError(SdkErrorCode.REQUESTED_RESOURCE_NOT_AVAILABLE);
36
- return Promise.reject({ status: ResponseStatus.ERROR, code, message });
37
- }
38
-
39
- this.pendingRequest = true;
40
-
41
- this.windowManager.openOrReuseWallet();
42
-
43
- const walletWindow = this.windowManager.getWalletWindow();
44
- if (!walletWindow) {
45
- const { code, message } = new ClientError(SdkErrorCode.WALLET_WINDOW_UNAVAILABLE);
46
- return Promise.reject({ status: ResponseStatus.ERROR, code, message });
47
- }
48
-
49
- let ready = false;
50
- let cleanupCalled = false;
51
-
52
- return new Promise<UltraResponse<T>>((resolve, reject) => {
53
- const cleanup = () => {
54
- if (cleanupCalled) return;
55
- cleanupCalled = true;
56
- this.pendingRequest = false;
57
- clearTimeout(timeout);
58
- clearInterval(checkWindowClose);
59
- window.removeEventListener('message', handleReady);
60
- walletWindow.close();
61
- };
62
-
63
- const handleReady = (event: MessageEvent) => {
64
- if (event.origin !== this.windowManager.walletUrl) return;
65
- const msg: JsonRpcMessage = event.data;
66
- if (msg?.jsonrpc === '2.0' && msg.method === 'ready') {
67
- ready = true;
68
- window.removeEventListener('message', handleReady);
69
-
70
- Promise.resolve(this.rpcClient.request(requestMethod, requestParams))
71
- .then((result) => {
72
- cleanup();
73
- if (result.status === ResponseStatus.SUCCESS) {
74
- resolve(result);
75
- } else {
76
- reject(result);
77
- }
78
- })
79
- .catch((error) => {
80
- cleanup();
81
- const clientError = new ClientError(SdkErrorCode.UNKNOWN_ERROR, error);
82
- reject({
83
- status: ResponseStatus.ERROR,
84
- ...clientError,
85
- });
86
- });
87
- }
88
- };
89
-
90
- const timeout = setTimeout(() => {
91
- if (!ready) {
92
- cleanup();
93
- const { code, message } = new ClientError(SdkErrorCode.WALLET_HANDSHAKE_TIMEOUT);
94
- reject({ status: ResponseStatus.ERROR, code, message });
95
- }
96
- }, UltraWalletSdkConfig.handshakeTimeout);
97
-
98
- const checkWindowClose = setInterval(() => {
99
- if (walletWindow.closed) {
100
- cleanup();
101
- const { code, message } = new ClientError(SdkErrorCode.USER_REJECTED_REQUEST);
102
- reject({ status: ResponseStatus.ERROR, code, message });
103
- }
104
- }, UltraWalletSdkConfig.checkWindowInterval);
105
-
106
- window.addEventListener('message', handleReady);
107
- });
108
- }
109
- }