odin-connect 1.0.1 → 1.0.3

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