@imtbl/sdk 0.45.4 → 0.45.6

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/dist/x.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ImmutableX, Config, TransfersApi, OrdersApi, UsersApi, Contracts, TradesApi, ExchangesApi, WithdrawalsApi, MintsApi, DepositsApi, EncodingApi, TokensApi } from '@imtbl/core-sdk';
2
2
  export { IMXError, createStarkSigner as imxClientCreateStarkSigner, generateLegacyStarkPrivateKey as imxClientGenerateLegacyStarkPrivateKey } from '@imtbl/core-sdk';
3
- import { AxiosError } from 'axios';
3
+ import axios, { AxiosError } from 'axios';
4
4
  import BN from 'bn.js';
5
5
  import * as encUtils from 'enc-utils';
6
6
  import { parseUnits } from '@ethersproject/units';
@@ -8,6 +8,266 @@ import { BigNumber } from '@ethersproject/bignumber';
8
8
  import { ethers } from 'ethers';
9
9
  import detectEthereumProvider from '@metamask/detect-provider';
10
10
 
11
+ const isNode = () => typeof window === 'undefined';
12
+ const isBrowser = () => !isNode();
13
+
14
+ var Detail;
15
+ (function (Detail) {
16
+ Detail["RUNTIME_ID"] = "rid";
17
+ Detail["PASSPORT_CLIENT_ID"] = "passportClientId";
18
+ Detail["ENVIRONMENT"] = "env";
19
+ Detail["PUBLISHABLE_API_KEY"] = "pak";
20
+ Detail["IDENTITY"] = "uid";
21
+ Detail["DOMAIN"] = "domain";
22
+ })(Detail || (Detail = {}));
23
+ var Store;
24
+ (function (Store) {
25
+ Store["EVENTS"] = "events";
26
+ Store["RUNTIME"] = "runtime";
27
+ })(Store || (Store = {}));
28
+ const POLLING_FREQUENCY = 5000;
29
+
30
+ const IMTBL_API = 'https://api.x.immutable.com';
31
+ async function post(path, data) {
32
+ const client = axios.create({
33
+ baseURL: IMTBL_API,
34
+ });
35
+ const payload = JSON.stringify(data);
36
+ const body = {
37
+ payload: btoa(payload),
38
+ };
39
+ const response = await client.post(path, body);
40
+ return response.data;
41
+ }
42
+
43
+ /**
44
+ * Abstraction on localstorage
45
+ */
46
+ const localStoragePrefix = '__IMX-';
47
+ const hasLocalstorage = () => isBrowser() && window.localStorage;
48
+ const parseItem = (payload) => {
49
+ // Try to parse, if can't be parsed assume string
50
+ // and return string
51
+ if (payload === null)
52
+ return undefined;
53
+ try {
54
+ return JSON.parse(payload);
55
+ }
56
+ catch (error) {
57
+ // Assumes it's a string.
58
+ return payload;
59
+ }
60
+ };
61
+ const serialiseItem = (payload) => {
62
+ if (typeof payload === 'string') {
63
+ return payload;
64
+ }
65
+ return JSON.stringify(payload);
66
+ };
67
+ /**
68
+ * GenKey will take into account the namespace
69
+ * as well as if being run in the Link, it will tap into the link
70
+ * @param {string} key
71
+ * @returns key
72
+ */
73
+ const genKey = (key) => `${localStoragePrefix}${key}`;
74
+ function getItem(key) {
75
+ if (hasLocalstorage()) {
76
+ return parseItem(window.localStorage.getItem(genKey(key)));
77
+ }
78
+ return undefined;
79
+ }
80
+ const setItem = (key, payload) => {
81
+ if (hasLocalstorage()) {
82
+ window.localStorage.setItem(genKey(key), serialiseItem(payload));
83
+ return true;
84
+ }
85
+ return false;
86
+ };
87
+
88
+ // In memory storage for events and other data
89
+ let EVENT_STORE;
90
+ let RUNTIME_DETAILS;
91
+ // Initialise store and runtime
92
+ const initialise$1 = () => {
93
+ EVENT_STORE = getItem(Store.EVENTS) || [];
94
+ RUNTIME_DETAILS = getItem(Store.RUNTIME) || {};
95
+ };
96
+ initialise$1();
97
+ // Runtime Details
98
+ const storeDetail = (key, value) => {
99
+ RUNTIME_DETAILS = {
100
+ ...RUNTIME_DETAILS,
101
+ [key]: value,
102
+ };
103
+ setItem(Store.RUNTIME, RUNTIME_DETAILS);
104
+ };
105
+ const getDetail = (key) => {
106
+ // Handle the scenario where detail is a falsy value
107
+ if (RUNTIME_DETAILS[key] === undefined) {
108
+ return undefined;
109
+ }
110
+ return RUNTIME_DETAILS[key];
111
+ };
112
+ const getAllDetails = () => RUNTIME_DETAILS;
113
+ // Events
114
+ const getEvents = () => EVENT_STORE;
115
+ const addEvent = (event) => {
116
+ EVENT_STORE.push(event);
117
+ setItem(Store.EVENTS, EVENT_STORE);
118
+ };
119
+ const removeSentEvents = (numberOfEvents) => {
120
+ EVENT_STORE = EVENT_STORE.slice(numberOfEvents);
121
+ setItem(Store.EVENTS, EVENT_STORE);
122
+ };
123
+ const flattenProperties = (properties) => {
124
+ const propertyMap = [];
125
+ Object.entries(properties).forEach(([key, value]) => {
126
+ if (typeof key === 'string'
127
+ || typeof value === 'string'
128
+ || typeof value === 'number'
129
+ || typeof value === 'boolean') {
130
+ propertyMap.push([key, value.toString()]);
131
+ }
132
+ });
133
+ return propertyMap;
134
+ };
135
+
136
+ let initialised = false;
137
+ const isInitialised = () => initialised;
138
+ const getReferrer = () => {
139
+ if (isNode()) {
140
+ return '';
141
+ }
142
+ if (window.location.ancestorOrigins
143
+ && window.location.ancestorOrigins.length > 0) {
144
+ return new URL(window.location.ancestorOrigins[0]).hostname;
145
+ }
146
+ return document.referrer ? new URL(window.document.referrer).hostname : '';
147
+ };
148
+ const runtimeHost = () => {
149
+ if (isNode()) {
150
+ return '';
151
+ }
152
+ if (window.opener || window.parent !== window) {
153
+ return getReferrer();
154
+ }
155
+ return new URL(window.location.href).hostname;
156
+ };
157
+ const getRuntimeDetails = () => {
158
+ if (isNode()) {
159
+ return { browser: 'nodejs' };
160
+ }
161
+ const domain = runtimeHost();
162
+ if (domain) {
163
+ storeDetail(Detail.DOMAIN, domain);
164
+ }
165
+ return {
166
+ browser: window.navigator.userAgent,
167
+ domain,
168
+ tz: Intl.DateTimeFormat().resolvedOptions().timeZone,
169
+ screen: `${window.screen.width}x${window.screen.height}`,
170
+ };
171
+ };
172
+ const initialise = async () => {
173
+ const runtimeDetails = flattenProperties(getRuntimeDetails());
174
+ // Get any existing runtimeId and send it along with the initialise
175
+ const existingRuntimeId = getDetail(Detail.RUNTIME_ID);
176
+ const body = {
177
+ version: 1,
178
+ data: {
179
+ runtimeDetails,
180
+ runtimeId: existingRuntimeId,
181
+ },
182
+ };
183
+ const response = await post('/v1/sdk/initialise', body);
184
+ // Get runtimeId and store it
185
+ const { runtimeId } = response;
186
+ storeDetail(Detail.RUNTIME_ID, runtimeId);
187
+ initialised = true;
188
+ };
189
+
190
+ function errorBoundary(fn) {
191
+ const wrappedFunction = ((...args) => {
192
+ try {
193
+ // Execute the original function
194
+ const result = fn(...args);
195
+ if (result instanceof Promise) {
196
+ // Silent fail for now, in future
197
+ // we can send errors to a logging service
198
+ return result.catch(() => undefined);
199
+ }
200
+ return result;
201
+ }
202
+ catch (error) {
203
+ // As above, fail silently for now
204
+ return undefined;
205
+ }
206
+ });
207
+ return wrappedFunction;
208
+ }
209
+
210
+ function isTestEnvironment() {
211
+ if (typeof process === 'undefined') {
212
+ return false;
213
+ }
214
+ return process.env.JEST_WORKER_ID !== undefined;
215
+ }
216
+
217
+ // Store the event in the event store
218
+ const trackFn = (moduleName, eventName, properties) => {
219
+ const event = {
220
+ event: `${moduleName}.${eventName}`,
221
+ time: new Date().toISOString(),
222
+ ...(properties && { properties: flattenProperties(properties) }),
223
+ };
224
+ addEvent(event);
225
+ };
226
+ const track = errorBoundary(trackFn);
227
+ // Sending events to the server
228
+ const flushFn = async () => {
229
+ // Don't flush if not initialised
230
+ if (isInitialised() === false) {
231
+ await initialise();
232
+ return;
233
+ }
234
+ const events = getEvents();
235
+ if (events.length === 0) {
236
+ return;
237
+ }
238
+ // Track events length here, incase
239
+ const numEvents = events.length;
240
+ // Get details and send it with the track request
241
+ const details = getAllDetails();
242
+ const metricsPayload = {
243
+ version: 1,
244
+ data: {
245
+ events,
246
+ details,
247
+ },
248
+ };
249
+ const response = await post('/v1/sdk/metrics', metricsPayload);
250
+ if (response instanceof Error) {
251
+ return;
252
+ }
253
+ // Clear events if successfully posted
254
+ removeSentEvents(numEvents);
255
+ };
256
+ const flush = errorBoundary(flushFn);
257
+ // Flush events every 5 seconds
258
+ const flushPoll = async () => {
259
+ await flush();
260
+ setTimeout(flushPoll, POLLING_FREQUENCY);
261
+ };
262
+ // This will get initialised when module is imported.
263
+ if (!isTestEnvironment()) {
264
+ errorBoundary(flushPoll)();
265
+ }
266
+
267
+ track('metrics', 'sdk_version', {
268
+ version: '0.45.6',
269
+ });
270
+
11
271
  var Environment;
12
272
  (function (Environment) {
13
273
  Environment["PRODUCTION"] = "production";
@@ -23,7 +283,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
23
283
  chainID,
24
284
  coreContractAddress,
25
285
  registrationContractAddress,
26
- sdkVersion: 'ts-immutable-sdk-0.45.4',
286
+ sdkVersion: 'ts-immutable-sdk-0.45.6',
27
287
  });
28
288
  /**
29
289
  * Sets `sdkVersion` at the time of build
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@imtbl/sdk",
3
3
  "description": "Immutable Unified SDK",
4
- "version": "0.45.4",
4
+ "version": "0.45.6",
5
5
  "author": "Immutable",
6
6
  "browser": "./dist/index.browser.js",
7
7
  "bugs": "https://github.com/immutable/ts-immutable-sdk/issues",