odin-connect 1.0.2 → 1.1.0
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/.github/workflows/pr.yml +24 -0
- package/demo/package-lock.json +101 -2
- package/demo/package.json +2 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/models/achievement.d.ts +20 -0
- package/dist/models/achievement.d.ts.map +1 -0
- package/dist/models/achievement.js +1 -0
- package/dist/models/token.d.ts +5 -0
- package/dist/models/token.d.ts.map +1 -1
- package/dist/services/api.d.ts +26 -0
- package/dist/services/api.d.ts.map +1 -1
- package/dist/services/api.js +93 -0
- package/dist/services/api.test.d.ts +2 -0
- package/dist/services/api.test.d.ts.map +1 -0
- package/dist/services/api.test.js +70 -0
- package/dist/services/connect.d.ts +36 -4
- package/dist/services/connect.d.ts.map +1 -1
- package/dist/services/connect.js +82 -21
- package/dist/services/connect.test.d.ts +2 -0
- package/dist/services/connect.test.d.ts.map +1 -0
- package/dist/services/connect.test.js +323 -0
- package/dist/services/http.d.ts +6 -2
- package/dist/services/http.d.ts.map +1 -1
- package/dist/services/http.js +30 -0
- package/dist/services/http.test.d.ts +2 -0
- package/dist/services/http.test.d.ts.map +1 -0
- package/dist/services/http.test.js +37 -0
- package/dist/utils/conver-to-odin-amount.test.d.ts +2 -0
- package/dist/utils/conver-to-odin-amount.test.d.ts.map +1 -0
- package/dist/utils/conver-to-odin-amount.test.js +36 -0
- package/dist/utils/index.d.ts +4 -1
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +108 -0
- package/dist/utils/token-field-validators.test.d.ts +2 -0
- package/dist/utils/token-field-validators.test.d.ts.map +1 -0
- package/dist/utils/token-field-validators.test.js +31 -0
- package/package.json +9 -2
- package/readme.md +26 -3
- package/vitest.config.ts +7 -0
package/dist/services/connect.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { OdinApi } from "./api";
|
|
2
|
+
import { createTokenValidators } from "../utils";
|
|
3
|
+
import { DelegationChain, } from "@dfinity/identity";
|
|
2
4
|
const ORIGINS = {
|
|
3
5
|
local: "http://localhost:5173",
|
|
4
6
|
prod: "https://odin.fun",
|
|
@@ -26,6 +28,7 @@ export class Connect {
|
|
|
26
28
|
if (this._appInfo?.name) {
|
|
27
29
|
url.searchParams.append("app_name", this._appInfo.name);
|
|
28
30
|
}
|
|
31
|
+
url.searchParams.append("referrer", window.location.origin);
|
|
29
32
|
return url;
|
|
30
33
|
}
|
|
31
34
|
openWindow(url) {
|
|
@@ -34,25 +37,28 @@ export class Connect {
|
|
|
34
37
|
get origin() {
|
|
35
38
|
return ORIGINS[this._appInfo?.env || "prod"];
|
|
36
39
|
}
|
|
37
|
-
connect({ open, requires_api }) {
|
|
40
|
+
connect({ open, requires_api, requires_delegation, session_key, targets, }) {
|
|
38
41
|
return new Promise((resolve, reject) => {
|
|
39
42
|
if (open) {
|
|
40
43
|
this._windowSettings = open;
|
|
41
44
|
}
|
|
42
45
|
const handleMessage = async (event) => {
|
|
43
|
-
if (event.origin === this.origin
|
|
46
|
+
if (event.origin === this.origin &&
|
|
47
|
+
event.data.path === "/authorize/connect") {
|
|
44
48
|
window.removeEventListener("message", handleMessage);
|
|
45
|
-
if (event.data != "rejected") {
|
|
49
|
+
if (event.data.message != "rejected") {
|
|
46
50
|
// the user accepted the connection
|
|
47
|
-
if (requires_api) {
|
|
48
|
-
// issue a api key
|
|
49
|
-
this._api.apiKey = "some-api-key";
|
|
50
|
-
}
|
|
51
|
-
const userId = event.data;
|
|
52
51
|
try {
|
|
52
|
+
const eventData = event.data.message;
|
|
53
|
+
const { principal, jwt: jwtToken, delegationChain } = eventData;
|
|
54
|
+
if (requires_api) {
|
|
55
|
+
// issue a api key
|
|
56
|
+
// only using JWT for now, it will change in the real implementation
|
|
57
|
+
this._api.apiKey = jwtToken;
|
|
58
|
+
}
|
|
53
59
|
// we need to fetch user data from the api to get the full user object
|
|
54
|
-
const user = await this._api.getUser(
|
|
55
|
-
resolve(user);
|
|
60
|
+
const user = await this._api.getUser(principal);
|
|
61
|
+
resolve({ user, delegationChain: delegationChain ? DelegationChain.fromJSON(delegationChain) : null });
|
|
56
62
|
}
|
|
57
63
|
catch (error) {
|
|
58
64
|
reject(new Error("Failed to fetch user data"));
|
|
@@ -63,7 +69,15 @@ export class Connect {
|
|
|
63
69
|
}
|
|
64
70
|
}
|
|
65
71
|
};
|
|
66
|
-
this.
|
|
72
|
+
const url = this.createUrl("authorize/connect");
|
|
73
|
+
url.searchParams.append("requires_api", requires_api ? "1" : "0");
|
|
74
|
+
if (requires_delegation) {
|
|
75
|
+
url.searchParams.append("requires_delegation", "1");
|
|
76
|
+
const sessionString = btoa(JSON.stringify(session_key.toJSON()));
|
|
77
|
+
url.searchParams.append("session_key", sessionString);
|
|
78
|
+
url.searchParams.append("targets", targets.join(","));
|
|
79
|
+
}
|
|
80
|
+
this.openWindow(url);
|
|
67
81
|
window.addEventListener("message", handleMessage);
|
|
68
82
|
});
|
|
69
83
|
}
|
|
@@ -85,6 +99,10 @@ export class Connect {
|
|
|
85
99
|
getUserActivity({ principal, pagination }) {
|
|
86
100
|
return this._api.getUserActivity(principal, pagination);
|
|
87
101
|
}
|
|
102
|
+
// exposes the api client, not sure if this is a good idea
|
|
103
|
+
get apiClient() {
|
|
104
|
+
return this._api;
|
|
105
|
+
}
|
|
88
106
|
sell({ token, tokenAmount, principal }) {
|
|
89
107
|
return this.baseAction({
|
|
90
108
|
params: {
|
|
@@ -95,7 +113,7 @@ export class Connect {
|
|
|
95
113
|
odinPath: "authorize/sell",
|
|
96
114
|
receivedMessageFromOrigin: "sold",
|
|
97
115
|
resolve: {
|
|
98
|
-
success: true,
|
|
116
|
+
success: () => true,
|
|
99
117
|
failure: "Sell failed or was cancelled",
|
|
100
118
|
close: "User closed the window",
|
|
101
119
|
},
|
|
@@ -111,7 +129,7 @@ export class Connect {
|
|
|
111
129
|
odinPath: "authorize/buy",
|
|
112
130
|
receivedMessageFromOrigin: "purchased",
|
|
113
131
|
resolve: {
|
|
114
|
-
success: true,
|
|
132
|
+
success: () => true,
|
|
115
133
|
failure: "Purchase failed or was cancelled",
|
|
116
134
|
close: "User closed the window",
|
|
117
135
|
},
|
|
@@ -128,7 +146,7 @@ export class Connect {
|
|
|
128
146
|
odinPath: "authorize/transfer",
|
|
129
147
|
receivedMessageFromOrigin: "transferred",
|
|
130
148
|
resolve: {
|
|
131
|
-
success: true,
|
|
149
|
+
success: () => true,
|
|
132
150
|
failure: "Transfer failed or was cancelled",
|
|
133
151
|
close: "User closed the window",
|
|
134
152
|
},
|
|
@@ -144,7 +162,7 @@ export class Connect {
|
|
|
144
162
|
odinPath: "authorize/add_liquidity",
|
|
145
163
|
receivedMessageFromOrigin: "addedLiquidity",
|
|
146
164
|
resolve: {
|
|
147
|
-
success: true,
|
|
165
|
+
success: () => true,
|
|
148
166
|
failure: "Add liquidity failed or was cancelled",
|
|
149
167
|
close: "User closed the window",
|
|
150
168
|
},
|
|
@@ -160,7 +178,7 @@ export class Connect {
|
|
|
160
178
|
odinPath: "authorize/remove_liquidity",
|
|
161
179
|
receivedMessageFromOrigin: "removedLiquidity",
|
|
162
180
|
resolve: {
|
|
163
|
-
success: true,
|
|
181
|
+
success: () => true,
|
|
164
182
|
failure: "Remove liquidity failed or was cancelled",
|
|
165
183
|
close: "User closed the window",
|
|
166
184
|
},
|
|
@@ -177,22 +195,62 @@ export class Connect {
|
|
|
177
195
|
odinPath: "authorize/swap",
|
|
178
196
|
receivedMessageFromOrigin: "swapped",
|
|
179
197
|
resolve: {
|
|
180
|
-
success: true,
|
|
198
|
+
success: () => true,
|
|
181
199
|
failure: "Swap failed or was cancelled",
|
|
182
200
|
close: "User closed the window",
|
|
183
201
|
},
|
|
184
202
|
});
|
|
185
203
|
}
|
|
204
|
+
async createToken({ image, ...params }) {
|
|
205
|
+
// check if token field param validators exist and run them
|
|
206
|
+
for (const key in createTokenValidators) {
|
|
207
|
+
if (key in params) {
|
|
208
|
+
const field = key;
|
|
209
|
+
const errors = createTokenValidators[field]?.(params[key] || null);
|
|
210
|
+
if (errors) {
|
|
211
|
+
throw new Error(errors);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
// additional validations for discount code
|
|
216
|
+
if (params.discount) {
|
|
217
|
+
if (!/^[A-Za-z0-9]{10}$/.test(params.discount)) {
|
|
218
|
+
throw new Error("Discount code must be alphanumeric and exactly 10 characters long.");
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const imageUrl = await this._api.uploadImage(image);
|
|
222
|
+
const result = await this.baseAction({
|
|
223
|
+
params: {
|
|
224
|
+
...params,
|
|
225
|
+
image: imageUrl,
|
|
226
|
+
buy: params.buy?.toString(),
|
|
227
|
+
},
|
|
228
|
+
odinPath: "authorize/create_token",
|
|
229
|
+
receivedMessageFromOrigin: "tokenCreated",
|
|
230
|
+
resolve: {
|
|
231
|
+
success: () => true,
|
|
232
|
+
failure: "Token creation failed or was cancelled",
|
|
233
|
+
close: "User closed the window",
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
if (!result) {
|
|
237
|
+
throw new Error("Token creation failed. Please try again.");
|
|
238
|
+
}
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
186
241
|
hello() {
|
|
187
242
|
console.log("Hello from Odin Connect!");
|
|
188
243
|
}
|
|
189
244
|
baseAction({ params, odinPath, receivedMessageFromOrigin, resolve: resolveMessages, }) {
|
|
190
245
|
return new Promise((resolve, reject) => {
|
|
191
246
|
const handleMessage = async (event) => {
|
|
192
|
-
if (event.origin === this.origin
|
|
247
|
+
if (event.origin === this.origin &&
|
|
248
|
+
event.data.path === "/" + odinPath) {
|
|
193
249
|
window.removeEventListener("message", handleMessage);
|
|
194
|
-
if (
|
|
195
|
-
|
|
250
|
+
if (typeof receivedMessageFromOrigin === "function"
|
|
251
|
+
? receivedMessageFromOrigin(event.data.message)
|
|
252
|
+
: receivedMessageFromOrigin === event.data.message) {
|
|
253
|
+
resolve(resolveMessages.success(event.data.message));
|
|
196
254
|
}
|
|
197
255
|
else {
|
|
198
256
|
reject(new Error(resolveMessages.failure));
|
|
@@ -201,7 +259,10 @@ export class Connect {
|
|
|
201
259
|
};
|
|
202
260
|
const url = this.createUrl(odinPath);
|
|
203
261
|
for (const key in params) {
|
|
204
|
-
|
|
262
|
+
// exclude undefined params
|
|
263
|
+
if (params[key]) {
|
|
264
|
+
url.searchParams.append(key, params[key]);
|
|
265
|
+
}
|
|
205
266
|
}
|
|
206
267
|
this.openWindow(url);
|
|
207
268
|
window.addEventListener("message", handleMessage);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect.test.d.ts","sourceRoot":"","sources":["../../src/services/connect.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { describe, it, expect, beforeAll, vi, afterEach } from "vitest";
|
|
2
|
+
import { Connect } from "./connect";
|
|
3
|
+
const mockTokens = [
|
|
4
|
+
{
|
|
5
|
+
id: "2jjj",
|
|
6
|
+
ticker: "TEST",
|
|
7
|
+
},
|
|
8
|
+
];
|
|
9
|
+
describe("Connect", () => {
|
|
10
|
+
let connect;
|
|
11
|
+
beforeAll(() => {
|
|
12
|
+
connect = new Connect({ name: "TestApp", env: "local" });
|
|
13
|
+
connect["_api"].getUser = vi.fn().mockResolvedValue({
|
|
14
|
+
principal: "user-principal",
|
|
15
|
+
username: "username",
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
afterEach(() => {
|
|
19
|
+
vi.restoreAllMocks();
|
|
20
|
+
});
|
|
21
|
+
it("should initialize Connect instance", () => {
|
|
22
|
+
expect(connect).toBeDefined();
|
|
23
|
+
expect(connect).toBeInstanceOf(Connect);
|
|
24
|
+
expect(connect["_appInfo"]?.name).toBe("TestApp");
|
|
25
|
+
expect(connect["origin"])?.toBe("http://localhost:5173");
|
|
26
|
+
});
|
|
27
|
+
it("should say hello", () => {
|
|
28
|
+
const consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => { });
|
|
29
|
+
connect.hello();
|
|
30
|
+
expect(consoleLogSpy).toHaveBeenCalledWith("Hello from Odin Connect!");
|
|
31
|
+
consoleLogSpy.mockRestore();
|
|
32
|
+
});
|
|
33
|
+
it("should create authorization URL", () => {
|
|
34
|
+
const url = connect["createUrl"]("authorize/test");
|
|
35
|
+
expect(url).toBeInstanceOf(URL);
|
|
36
|
+
expect(url.pathname).toBe("/authorize/test");
|
|
37
|
+
expect(url.searchParams.get("app_name")).toBe("TestApp");
|
|
38
|
+
expect(url.searchParams.get("referrer")).toBeDefined();
|
|
39
|
+
});
|
|
40
|
+
it("should open the connect window", () => {
|
|
41
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
42
|
+
const getUserSpy = vi.spyOn(connect["_api"], "getUser").mockResolvedValue({
|
|
43
|
+
principal: "user-principal",
|
|
44
|
+
username: "username",
|
|
45
|
+
});
|
|
46
|
+
const connectPromise = connect.connect({ requires_api: false });
|
|
47
|
+
connectPromise.then((res) => {
|
|
48
|
+
expect(res).toBeDefined();
|
|
49
|
+
expect(res.user.username).toBe("username");
|
|
50
|
+
expect(res.user.principal).toBe("user-principal");
|
|
51
|
+
expect(connect.apiClient.apiKey).toBeNull();
|
|
52
|
+
}, (e) => {
|
|
53
|
+
expect(true).toBe(false);
|
|
54
|
+
});
|
|
55
|
+
const url = openSpy.mock.calls[0][0];
|
|
56
|
+
expect(url).toBeInstanceOf(URL);
|
|
57
|
+
expect(url?.toString()).toContain("http://localhost:5173/authorize/connect?");
|
|
58
|
+
const params = new URLSearchParams(url?.search);
|
|
59
|
+
expect(params.get("app_name")).toBe("TestApp");
|
|
60
|
+
expect(params.get("referrer")).toBeDefined();
|
|
61
|
+
expect(params.get("requires_api")).toBe("0");
|
|
62
|
+
simulateMessage("authorize/connect", {
|
|
63
|
+
principal: "user-principal",
|
|
64
|
+
jwt: null,
|
|
65
|
+
});
|
|
66
|
+
expect(getUserSpy).toHaveBeenCalledWith("user-principal");
|
|
67
|
+
});
|
|
68
|
+
it("should open connect window with API requirement", () => {
|
|
69
|
+
vi.spyOn(connect["_api"], "getUser").mockResolvedValue({
|
|
70
|
+
principal: "user-principal",
|
|
71
|
+
username: "username",
|
|
72
|
+
});
|
|
73
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
74
|
+
const connectPromise = connect.connect({ requires_api: true });
|
|
75
|
+
connectPromise.then((res) => {
|
|
76
|
+
console.log(res);
|
|
77
|
+
expect(res).toBeDefined();
|
|
78
|
+
expect(res.user.username).toBe("username");
|
|
79
|
+
expect(res.user.principal).toBe("user-principal");
|
|
80
|
+
expect(connect.apiClient.apiKey).toBe("test-jwt");
|
|
81
|
+
}, () => {
|
|
82
|
+
expect(true).toBe(false);
|
|
83
|
+
});
|
|
84
|
+
const url = openSpy.mock.calls[0][0];
|
|
85
|
+
expect(url).toBeInstanceOf(URL);
|
|
86
|
+
expect(url?.toString()).toContain("http://localhost:5173/authorize/connect?");
|
|
87
|
+
const params = new URLSearchParams(url?.search);
|
|
88
|
+
expect(params.get("app_name")).toBe("TestApp");
|
|
89
|
+
expect(params.get("referrer")).toBeDefined();
|
|
90
|
+
expect(params.get("requires_api")).toBe("1");
|
|
91
|
+
simulateMessage("authorize/connect", {
|
|
92
|
+
principal: "user-principal",
|
|
93
|
+
jwt: "test-jwt",
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
it("should handle rejected connection", () => {
|
|
97
|
+
const connectPromise = connect.connect({ requires_api: false });
|
|
98
|
+
connectPromise.then(() => expect(false).toBe(true), (e) => {
|
|
99
|
+
expect(e).toBeInstanceOf(Error);
|
|
100
|
+
expect(e.message).toContain("rejected");
|
|
101
|
+
});
|
|
102
|
+
simulateRejectMessage("authorize/connect");
|
|
103
|
+
});
|
|
104
|
+
it("should open the buy authorization window", () => {
|
|
105
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
106
|
+
const result = connect.buy({
|
|
107
|
+
token: "2jjj",
|
|
108
|
+
btcAmount: 20001n,
|
|
109
|
+
principal: "test-principal",
|
|
110
|
+
});
|
|
111
|
+
result.catch((e) => {
|
|
112
|
+
console.log(e);
|
|
113
|
+
expect(e).toBeInstanceOf(Error);
|
|
114
|
+
});
|
|
115
|
+
expect(openSpy).toHaveBeenCalled();
|
|
116
|
+
const url = openSpy.mock.calls[0][0];
|
|
117
|
+
expect(url).toBeInstanceOf(URL);
|
|
118
|
+
expect(url?.toString()).toContain("http://localhost:5173/authorize/buy?");
|
|
119
|
+
const params = new URLSearchParams(url?.search);
|
|
120
|
+
expect(params.get("app_name")).toBe("TestApp");
|
|
121
|
+
expect(params.get("token")).toBe("2jjj");
|
|
122
|
+
expect(params.get("amount")).toBe("20001");
|
|
123
|
+
expect(params.get("principal")).toBe("test-principal");
|
|
124
|
+
});
|
|
125
|
+
it("should open the sell authorization window", () => {
|
|
126
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
127
|
+
const sellPromise = connect.sell({
|
|
128
|
+
token: "2jjj",
|
|
129
|
+
tokenAmount: 32000n,
|
|
130
|
+
principal: "test-principal",
|
|
131
|
+
});
|
|
132
|
+
sellPromise.then((result) => {
|
|
133
|
+
expect(result).toBe(true);
|
|
134
|
+
});
|
|
135
|
+
expect(openSpy).toHaveBeenCalled();
|
|
136
|
+
const url = openSpy.mock.calls[0][0];
|
|
137
|
+
expect(url).toBeInstanceOf(URL);
|
|
138
|
+
expect(url?.toString()).toContain("http://localhost:5173/authorize/sell?");
|
|
139
|
+
const params = new URLSearchParams(url?.search);
|
|
140
|
+
expect(params.get("app_name")).toBe("TestApp");
|
|
141
|
+
expect(params.get("token")).toBe("2jjj");
|
|
142
|
+
expect(params.get("amount")).toBe("32000");
|
|
143
|
+
expect(params.get("principal")).toBe("test-principal");
|
|
144
|
+
simulateMessage("authorize/sell", "sold");
|
|
145
|
+
});
|
|
146
|
+
it("should handle rejected sell", () => {
|
|
147
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
148
|
+
const sellPromise = connect.sell({
|
|
149
|
+
token: "2jjj",
|
|
150
|
+
tokenAmount: 32000n,
|
|
151
|
+
principal: "test-principal",
|
|
152
|
+
});
|
|
153
|
+
sellPromise.then(() => {
|
|
154
|
+
expect(true).toBe(false); // should not be called
|
|
155
|
+
}, (e) => {
|
|
156
|
+
expect(e).toBeInstanceOf(Error);
|
|
157
|
+
expect(e.message).toContain("failed");
|
|
158
|
+
});
|
|
159
|
+
expect(openSpy).toHaveBeenCalled();
|
|
160
|
+
simulateRejectMessage("authorize/sell");
|
|
161
|
+
});
|
|
162
|
+
it("should open the transfer authorization window", () => {
|
|
163
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
164
|
+
const result = connect.transfer({
|
|
165
|
+
token: "2jjj",
|
|
166
|
+
amount: 45000n,
|
|
167
|
+
destination: "to-principal",
|
|
168
|
+
principal: "from-principal",
|
|
169
|
+
});
|
|
170
|
+
result.catch((e) => {
|
|
171
|
+
expect(e).toBeInstanceOf(Error);
|
|
172
|
+
});
|
|
173
|
+
expect(openSpy).toHaveBeenCalled();
|
|
174
|
+
const url = openSpy.mock.calls[0][0];
|
|
175
|
+
expect(url).toBeInstanceOf(URL);
|
|
176
|
+
expect(url?.toString()).toContain("http://localhost:5173/authorize/transfer?");
|
|
177
|
+
const params = new URLSearchParams(url?.search);
|
|
178
|
+
expect(params.get("app_name")).toBe("TestApp");
|
|
179
|
+
expect(params.get("token")).toBe("2jjj");
|
|
180
|
+
expect(params.get("amount")).toBe("45000");
|
|
181
|
+
expect(params.get("destination")).toBe("to-principal");
|
|
182
|
+
expect(params.get("principal")).toBe("from-principal");
|
|
183
|
+
});
|
|
184
|
+
it("should handle rejected transfer", () => {
|
|
185
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
186
|
+
const transferPromise = connect.transfer({
|
|
187
|
+
token: "2jjj",
|
|
188
|
+
amount: 45000n,
|
|
189
|
+
destination: "to-principal",
|
|
190
|
+
principal: "from-principal",
|
|
191
|
+
});
|
|
192
|
+
transferPromise.then(() => expect(true).toBe(false), // should not be called
|
|
193
|
+
(e) => {
|
|
194
|
+
expect(e).toBeInstanceOf(Error);
|
|
195
|
+
expect(e.message).toContain("failed");
|
|
196
|
+
});
|
|
197
|
+
expect(openSpy).toHaveBeenCalled();
|
|
198
|
+
simulateRejectMessage("authorize/transfer");
|
|
199
|
+
});
|
|
200
|
+
it("should open the add liquidity authorization window", () => {
|
|
201
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
202
|
+
const addLiquidityPromise = connect.addLiquidity({
|
|
203
|
+
token: "2jjj",
|
|
204
|
+
btcAmount: 10000n,
|
|
205
|
+
principal: "test-principal",
|
|
206
|
+
});
|
|
207
|
+
addLiquidityPromise.then((result) => expect(result).toBe(true), () => expect(true).toBe(false) // should not be called
|
|
208
|
+
);
|
|
209
|
+
expect(openSpy).toHaveBeenCalled();
|
|
210
|
+
const url = openSpy.mock.calls[0][0];
|
|
211
|
+
expect(url).toBeInstanceOf(URL);
|
|
212
|
+
expect(url?.toString()).toContain("http://localhost:5173/authorize/add_liquidity?");
|
|
213
|
+
const params = new URLSearchParams(url?.search);
|
|
214
|
+
expect(params.get("app_name")).toBe("TestApp");
|
|
215
|
+
expect(params.get("token")).toBe("2jjj");
|
|
216
|
+
expect(params.get("amount")).toBe("10000");
|
|
217
|
+
expect(params.get("principal")).toBe("test-principal");
|
|
218
|
+
simulateMessage("authorize/add_liquidity", "addedLiquidity");
|
|
219
|
+
});
|
|
220
|
+
it("should handle rejected add liquidity", () => {
|
|
221
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
222
|
+
const addLiquidityPromise = connect.addLiquidity({
|
|
223
|
+
token: "2jjj",
|
|
224
|
+
btcAmount: 10000n,
|
|
225
|
+
principal: "test-principal",
|
|
226
|
+
});
|
|
227
|
+
addLiquidityPromise.then(() => expect(true).toBe(false), // should not be called
|
|
228
|
+
(e) => {
|
|
229
|
+
expect(e).toBeInstanceOf(Error);
|
|
230
|
+
expect(e.message).toContain("failed");
|
|
231
|
+
});
|
|
232
|
+
expect(openSpy).toHaveBeenCalled();
|
|
233
|
+
simulateRejectMessage("authorize/add_liquidity");
|
|
234
|
+
});
|
|
235
|
+
it("should open the remove liquidity authorization window", () => {
|
|
236
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
237
|
+
const removeLiquidityPromise = connect.removeLiquidity({
|
|
238
|
+
token: "2jjj",
|
|
239
|
+
lpAmount: 15000n,
|
|
240
|
+
principal: "test-principal",
|
|
241
|
+
});
|
|
242
|
+
removeLiquidityPromise.then((result) => expect(result).toBe(true), () => expect(true).toBe(false) // should not be called
|
|
243
|
+
);
|
|
244
|
+
expect(openSpy).toHaveBeenCalled();
|
|
245
|
+
const url = openSpy.mock.calls[0][0];
|
|
246
|
+
expect(url).toBeInstanceOf(URL);
|
|
247
|
+
expect(url?.toString()).toContain("http://localhost:5173/authorize/remove_liquidity?");
|
|
248
|
+
const params = new URLSearchParams(url?.search);
|
|
249
|
+
expect(params.get("app_name")).toBe("TestApp");
|
|
250
|
+
expect(params.get("token")).toBe("2jjj");
|
|
251
|
+
expect(params.get("amount")).toBe("15000");
|
|
252
|
+
expect(params.get("principal")).toBe("test-principal");
|
|
253
|
+
simulateMessage("authorize/remove_liquidity", "removedLiquidity");
|
|
254
|
+
});
|
|
255
|
+
it("should handle rejected remove liquidity", () => {
|
|
256
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
257
|
+
const removeLiquidityPromise = connect.removeLiquidity({
|
|
258
|
+
token: "2jjj",
|
|
259
|
+
lpAmount: 15000n,
|
|
260
|
+
principal: "test-principal",
|
|
261
|
+
});
|
|
262
|
+
removeLiquidityPromise.then(() => expect(true).toBe(false), // should not be called
|
|
263
|
+
(e) => {
|
|
264
|
+
expect(e).toBeInstanceOf(Error);
|
|
265
|
+
expect(e.message).toContain("failed");
|
|
266
|
+
});
|
|
267
|
+
expect(openSpy).toHaveBeenCalled();
|
|
268
|
+
simulateRejectMessage("authorize/remove_liquidity");
|
|
269
|
+
});
|
|
270
|
+
it("should create a base action", async () => {
|
|
271
|
+
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
|
272
|
+
const action = () => connect["baseAction"]({
|
|
273
|
+
params: { test: "param" },
|
|
274
|
+
odinPath: "authorize/test_action",
|
|
275
|
+
receivedMessageFromOrigin(message) {
|
|
276
|
+
return message === "OK";
|
|
277
|
+
},
|
|
278
|
+
resolve: {
|
|
279
|
+
success: (message) => {
|
|
280
|
+
return message + "!";
|
|
281
|
+
},
|
|
282
|
+
failure: "test failed",
|
|
283
|
+
close: "rejected",
|
|
284
|
+
},
|
|
285
|
+
});
|
|
286
|
+
action().then((res) => {
|
|
287
|
+
expect(res).toBe("OK!");
|
|
288
|
+
});
|
|
289
|
+
expect(openSpy).toHaveBeenCalled();
|
|
290
|
+
const url = openSpy.mock.calls[0][0];
|
|
291
|
+
expect(url).toBeInstanceOf(URL);
|
|
292
|
+
expect(url?.toString()).toContain("http://localhost:5173/authorize/test_action?");
|
|
293
|
+
const params = new URLSearchParams(url?.search);
|
|
294
|
+
expect(params.get("app_name")).toBe("TestApp");
|
|
295
|
+
expect(params.get("test")).toBe("param");
|
|
296
|
+
simulateMessage("authorize/test_action", "OK");
|
|
297
|
+
action().then(() => expect(true).toBe(false), (e) => {
|
|
298
|
+
expect(e).toBeInstanceOf(Error);
|
|
299
|
+
expect(e.message).toBe("test failed");
|
|
300
|
+
});
|
|
301
|
+
simulateRejectMessage("authorize/test_action");
|
|
302
|
+
});
|
|
303
|
+
});
|
|
304
|
+
function simulateRejectMessage(path) {
|
|
305
|
+
const messageEvent = new MessageEvent("message", {
|
|
306
|
+
data: {
|
|
307
|
+
path: "/" + path,
|
|
308
|
+
message: "rejected",
|
|
309
|
+
},
|
|
310
|
+
origin: "http://localhost:5173",
|
|
311
|
+
});
|
|
312
|
+
window.dispatchEvent(messageEvent);
|
|
313
|
+
}
|
|
314
|
+
function simulateMessage(path, data) {
|
|
315
|
+
const messageEvent = new MessageEvent("message", {
|
|
316
|
+
data: {
|
|
317
|
+
path: "/" + path,
|
|
318
|
+
message: data,
|
|
319
|
+
},
|
|
320
|
+
origin: "http://localhost:5173",
|
|
321
|
+
});
|
|
322
|
+
window.dispatchEvent(messageEvent);
|
|
323
|
+
}
|
package/dist/services/http.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { AxiosRequestConfig } from "axios";
|
|
2
|
+
export declare const bigIntTransformer: (data: string) => any;
|
|
2
3
|
export declare class HttpClient {
|
|
3
|
-
get<
|
|
4
|
-
fetch<
|
|
4
|
+
get<ResponseType>(url: string, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
5
|
+
fetch<ResponseType>(url: string, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
6
|
+
post<ResponseType, DataType = string>(url: string, data?: DataType, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
7
|
+
put<DataType, ResponseType>(url: string, data?: DataType, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
8
|
+
delete<ResponseType>(url: string, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
5
9
|
}
|
|
6
10
|
//# sourceMappingURL=http.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/services/http.ts"],"names":[],"mappings":"AAAA,OAAc,EAAE,kBAAkB,
|
|
1
|
+
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/services/http.ts"],"names":[],"mappings":"AAAA,OAAc,EAAE,kBAAkB,EAA4B,MAAM,OAAO,CAAC;AAG5E,eAAO,MAAM,iBAAiB,GACzB,MAAK,MAAM,QAOX,CAAA;AACL,qBAAa,UAAU;IAEf,GAAG,CAAC,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,kBAAkB;IAI3D,KAAK,CAAC,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,kBAAkB;IAW7D,IAAI,CAAC,YAAY,EAAE,QAAQ,GAAG,MAAM,EACxC,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,QAAQ,EACf,OAAO,CAAC,EAAE,kBAAkB;IASxB,GAAG,CAAC,QAAQ,EAAE,YAAY,EAC9B,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,QAAQ,EACf,OAAO,CAAC,EAAE,kBAAkB;IASxB,MAAM,CAAC,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,kBAAkB;CAGrE"}
|
package/dist/services/http.js
CHANGED
|
@@ -1,13 +1,43 @@
|
|
|
1
1
|
import axios from "axios";
|
|
2
|
+
import JSONBigInt from "@apimatic/json-bigint";
|
|
3
|
+
export const bigIntTransformer = (data) => {
|
|
4
|
+
try {
|
|
5
|
+
return JSONBigInt.parse(data);
|
|
6
|
+
}
|
|
7
|
+
catch (e) {
|
|
8
|
+
console.error("Error parsing response:", e);
|
|
9
|
+
return data;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
2
12
|
export class HttpClient {
|
|
3
13
|
async get(url, options) {
|
|
4
14
|
return this.fetch(url, { method: "GET", ...options });
|
|
5
15
|
}
|
|
6
16
|
async fetch(url, options) {
|
|
17
|
+
// for any custom headers or other axios options in the future
|
|
18
|
+
// should we add Auth bearer token here if available?
|
|
7
19
|
const overrides = {
|
|
20
|
+
transformResponse: [bigIntTransformer],
|
|
8
21
|
...options,
|
|
9
22
|
};
|
|
10
23
|
const response = await axios(url, overrides);
|
|
11
24
|
return response.data;
|
|
12
25
|
}
|
|
26
|
+
async post(url, data, options) {
|
|
27
|
+
return this.fetch(url, {
|
|
28
|
+
method: "POST",
|
|
29
|
+
data,
|
|
30
|
+
...options,
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
async put(url, data, options) {
|
|
34
|
+
return this.fetch(url, {
|
|
35
|
+
method: "PUT",
|
|
36
|
+
data,
|
|
37
|
+
...options,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
async delete(url, options) {
|
|
41
|
+
return this.fetch(url, { method: "DELETE", ...options });
|
|
42
|
+
}
|
|
13
43
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.test.d.ts","sourceRoot":"","sources":["../../src/services/http.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { it, beforeAll, describe, expect, vi } from "vitest";
|
|
2
|
+
import { bigIntTransformer, HttpClient } from "./http";
|
|
3
|
+
import axios from "axios";
|
|
4
|
+
import { afterEach } from "node:test";
|
|
5
|
+
describe("HttpClient", () => {
|
|
6
|
+
let http;
|
|
7
|
+
let mockedAxios = axios;
|
|
8
|
+
vi.mock("axios");
|
|
9
|
+
beforeAll(() => {
|
|
10
|
+
http = new HttpClient();
|
|
11
|
+
});
|
|
12
|
+
afterEach(() => {
|
|
13
|
+
mockedAxios.mockClear();
|
|
14
|
+
});
|
|
15
|
+
it("should create http instance", () => {
|
|
16
|
+
expect(http).toBeDefined();
|
|
17
|
+
expect(http).toBeInstanceOf(HttpClient);
|
|
18
|
+
});
|
|
19
|
+
it("should send GET request", async () => {
|
|
20
|
+
const url = "http://localhost:3000";
|
|
21
|
+
mockedAxios.mockResolvedValue({ data: true });
|
|
22
|
+
const data = await http.get(url);
|
|
23
|
+
expect(mockedAxios).toHaveBeenCalledWith(url, expect.objectContaining({ method: "GET" }));
|
|
24
|
+
expect(data).toBe(true);
|
|
25
|
+
});
|
|
26
|
+
it("should send POST request", async () => {
|
|
27
|
+
const url = "http://localhost:3000";
|
|
28
|
+
mockedAxios.mockResolvedValue({ data: "success" });
|
|
29
|
+
const data = await http.post(url);
|
|
30
|
+
expect(mockedAxios).toHaveBeenCalledWith(url, expect.objectContaining({ method: "POST" }));
|
|
31
|
+
expect(data).toBe("success");
|
|
32
|
+
});
|
|
33
|
+
it("should transform", () => {
|
|
34
|
+
expect(bigIntTransformer(`{"bigInt":200000000000000023}`)["bigInt"]).toBeTypeOf("bigint");
|
|
35
|
+
expect(bigIntTransformer(`{"num":200}`)["num"]).toBeTypeOf("number");
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conver-to-odin-amount.test.d.ts","sourceRoot":"","sources":["../../src/utils/conver-to-odin-amount.test.ts"],"names":[],"mappings":""}
|