@pooflabs/web 0.0.3 → 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.
package/dist/index.js CHANGED
@@ -1,343 +1,31 @@
1
1
  'use strict';
2
2
 
3
- var axios = require('axios');
4
3
  var web3_js = require('@solana/web3.js');
5
4
  var anchor = require('@coral-xyz/anchor');
5
+ var axios = require('axios');
6
6
  var jsxRuntime = require('react/jsx-runtime');
7
7
  var React$1 = require('react');
8
8
 
9
9
  function _interopNamespaceDefault(e) {
10
- var n = Object.create(null);
11
- if (e) {
12
- Object.keys(e).forEach(function (k) {
13
- if (k !== 'default') {
14
- var d = Object.getOwnPropertyDescriptor(e, k);
15
- Object.defineProperty(n, k, d.get ? d : {
16
- enumerable: true,
17
- get: function () { return e[k]; }
18
- });
19
- }
10
+ var n = Object.create(null);
11
+ if (e) {
12
+ Object.keys(e).forEach(function (k) {
13
+ if (k !== 'default') {
14
+ var d = Object.getOwnPropertyDescriptor(e, k);
15
+ Object.defineProperty(n, k, d.get ? d : {
16
+ enumerable: true,
17
+ get: function () { return e[k]; }
20
18
  });
21
- }
22
- n.default = e;
23
- return Object.freeze(n);
19
+ }
20
+ });
21
+ }
22
+ n.default = e;
23
+ return Object.freeze(n);
24
24
  }
25
25
 
26
26
  var anchor__namespace = /*#__PURE__*/_interopNamespaceDefault(anchor);
27
27
  var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React$1);
28
28
 
29
- let axiosClient;
30
- async function getAxiosAuthClient() {
31
- if (!axiosClient) {
32
- const config = await getConfig();
33
- axiosClient = axios.create({
34
- baseURL: config.authApiUrl,
35
- headers: {
36
- 'Content-Type': 'application/json',
37
- },
38
- });
39
- }
40
- return axiosClient;
41
- }
42
- async function createSessionWithSignature(address, message, signature) {
43
- const client = await getAxiosAuthClient();
44
- const config = await getConfig();
45
- const appId = config.appId;
46
- const response = await client.post('/session', {
47
- appId,
48
- address,
49
- message,
50
- signature,
51
- authMethod: config.authMethod
52
- });
53
- return response.data;
54
- }
55
- async function createSessionWithPrivy(authToken, address, idToken) {
56
- if (typeof window === 'undefined')
57
- return;
58
- const client = await getAxiosAuthClient();
59
- const config = await getConfig();
60
- const appId = config.appId;
61
- const response = await client.post('/session', {
62
- appId,
63
- authMethod: config.authMethod,
64
- authToken,
65
- idToken: idToken,
66
- address
67
- });
68
- return response.data;
69
- }
70
- async function refreshSession(refreshToken) {
71
- const client = await getAxiosAuthClient();
72
- const config = await getConfig();
73
- const appId = config.appId;
74
- const response = await client.post('/session/refresh', {
75
- refreshToken,
76
- appId
77
- });
78
- return response.data;
79
- }
80
-
81
- class SessionManager {
82
- //private static EXPIRATION_TIME: number = 60 * 60 * 1000; // 1 hour
83
- static async storeSession(address, accessToken, idToken, refreshToken) {
84
- if (typeof window === 'undefined') {
85
- return;
86
- }
87
- // Store the current appId along with the session data
88
- const config = await getConfig();
89
- const currentAppId = config.appId;
90
- localStorage.setItem(this.TAROBASE_SESSION_STORAGE_KEY, JSON.stringify({
91
- address,
92
- accessToken,
93
- idToken,
94
- refreshToken,
95
- appId: currentAppId
96
- }));
97
- }
98
- static async getSession() {
99
- if (typeof window === 'undefined')
100
- return null;
101
- const session = localStorage.getItem(this.TAROBASE_SESSION_STORAGE_KEY);
102
- if (!session)
103
- return null;
104
- const sessionObj = JSON.parse(session);
105
- // Check for appId mismatch
106
- const config = await getConfig();
107
- const currentAppId = config.appId;
108
- const sessionAppId = sessionObj.appId;
109
- // If the stored session has a different appId than the current one, invalidate the session
110
- if (sessionAppId && sessionAppId !== currentAppId) {
111
- console.warn('Session appId mismatch. Stored session belongs to a different app. Logging out.');
112
- this.clearSession();
113
- return null;
114
- }
115
- const accessToken = sessionObj.accessToken;
116
- try {
117
- const accessTokenPayload = JSON.parse(atob(accessToken.split('.')[1]));
118
- const expirationTime = accessTokenPayload.exp * 1000; // Convert to milliseconds
119
- const currentTime = Date.now();
120
- if (currentTime > expirationTime) {
121
- const refreshToken = sessionObj.refreshToken;
122
- if (!refreshToken) {
123
- return null;
124
- }
125
- const refreshDataSession = await refreshSession(refreshToken);
126
- if (refreshDataSession && refreshDataSession.idToken && refreshDataSession.accessToken) {
127
- this.updateIdTokenAndAccessToken(refreshDataSession.idToken, refreshDataSession.accessToken);
128
- const newSession = localStorage.getItem(this.TAROBASE_SESSION_STORAGE_KEY);
129
- if (!newSession)
130
- return null;
131
- const newSessionObj = JSON.parse(newSession);
132
- return { address: newSessionObj.address, session: newSessionObj };
133
- }
134
- return null;
135
- }
136
- }
137
- catch (error) {
138
- console.error('Error decoding access token:', error);
139
- return null;
140
- }
141
- return { address: sessionObj.address, session: sessionObj };
142
- }
143
- static clearSession() {
144
- if (typeof window === 'undefined')
145
- return;
146
- localStorage.removeItem(this.TAROBASE_SESSION_STORAGE_KEY);
147
- }
148
- static isAuthenticated() {
149
- return !!this.getSession();
150
- }
151
- static getIdToken() {
152
- if (typeof window === 'undefined')
153
- return null;
154
- const session = localStorage.getItem(this.TAROBASE_SESSION_STORAGE_KEY);
155
- if (!session)
156
- return null;
157
- const sessionObj = JSON.parse(session);
158
- const idToken = sessionObj.idToken;
159
- return idToken;
160
- }
161
- static getRefreshToken() {
162
- if (typeof window === 'undefined')
163
- return null;
164
- const session = localStorage.getItem(this.TAROBASE_SESSION_STORAGE_KEY);
165
- if (!session)
166
- return null;
167
- const sessionObj = JSON.parse(session);
168
- return sessionObj.refreshToken;
169
- }
170
- static async updateIdTokenAndAccessToken(idToken, accessToken) {
171
- if (typeof window === 'undefined')
172
- return;
173
- const session = localStorage.getItem(this.TAROBASE_SESSION_STORAGE_KEY);
174
- if (!session)
175
- return;
176
- const sessionObj = JSON.parse(session);
177
- // Check for appId mismatch before updating
178
- const config = await getConfig();
179
- const currentAppId = config.appId;
180
- const sessionAppId = sessionObj.appId;
181
- // If the stored session has a different appId than the current one, invalidate the session
182
- if (sessionAppId && sessionAppId !== currentAppId) {
183
- console.warn('Session appId mismatch during token refresh. Stored session belongs to a different app. Logging out.');
184
- this.clearSession();
185
- return;
186
- }
187
- sessionObj.idToken = idToken;
188
- sessionObj.accessToken = accessToken;
189
- // Ensure appId is stored with the updated session
190
- if (!sessionObj.appId) {
191
- sessionObj.appId = currentAppId;
192
- }
193
- localStorage.setItem(this.TAROBASE_SESSION_STORAGE_KEY, JSON.stringify(sessionObj));
194
- }
195
- }
196
- SessionManager.TAROBASE_SESSION_STORAGE_KEY = 'tarobase_session_storage';
197
-
198
- async function createBearerToken() {
199
- const idToken = SessionManager.getIdToken();
200
- if (!idToken) {
201
- return null;
202
- }
203
- return `Bearer ${idToken}`;
204
- }
205
- async function createAuthHeader() {
206
- const bearerToken = await createBearerToken();
207
- if (!bearerToken) {
208
- return null;
209
- }
210
- return {
211
- Authorization: bearerToken
212
- };
213
- }
214
- function getIdToken() {
215
- return SessionManager.getIdToken();
216
- }
217
- function getRefreshToken() {
218
- return SessionManager.getRefreshToken();
219
- }
220
- function updateIdTokenAndAccessToken(idToken, accessToken) {
221
- SessionManager.updateIdTokenAndAccessToken(idToken, accessToken);
222
- }
223
-
224
- async function makeApiRequest(method, urlPath, data, _overrides) {
225
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
226
- const config = await getConfig();
227
- async function executeRequest() {
228
- const authHeader = await createAuthHeader();
229
- const headers = Object.assign({ 'Content-Type': 'application/json', "X-Public-App-Id": config.appId, "X-App-Id": config.appId }, authHeader);
230
- if (typeof window !== 'undefined' && window.CUSTOM_TAROBASE_APP_ID_HEADER) {
231
- const customAppId = window.CUSTOM_TAROBASE_APP_ID_HEADER;
232
- if (customAppId) {
233
- headers["X-App-Id"] = customAppId;
234
- }
235
- }
236
- // Apply custom headers from _overrides
237
- if (_overrides === null || _overrides === void 0 ? void 0 : _overrides.headers) {
238
- Object.assign(headers, _overrides.headers);
239
- }
240
- const requestConfig = {
241
- method,
242
- url: `${config.apiUrl}${urlPath.startsWith('/') ? urlPath : `/${urlPath}`}`,
243
- headers,
244
- };
245
- if (method !== 'GET' && method !== 'get') {
246
- requestConfig.data = data ? JSON.stringify(data) : {};
247
- }
248
- const response = await axios(requestConfig);
249
- return { data: response.data, status: response.status };
250
- }
251
- try {
252
- return await executeRequest();
253
- }
254
- catch (error) {
255
- if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 401) {
256
- try {
257
- const refreshToken = getRefreshToken();
258
- if (!refreshToken) {
259
- throw new Error("No refresh token found");
260
- }
261
- const refreshData = await refreshSession(refreshToken);
262
- if (refreshData && refreshData.idToken && refreshData.accessToken) {
263
- updateIdTokenAndAccessToken(refreshData.idToken, refreshData.accessToken);
264
- }
265
- return await executeRequest();
266
- }
267
- catch (refreshError) {
268
- throw error;
269
- }
270
- }
271
- if (((_b = error.response) === null || _b === void 0 ? void 0 : _b.status) == 404) {
272
- return { data: null, status: 404 };
273
- }
274
- if ((_d = (_c = error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.message) {
275
- console.error(`Error in set call with code ${(_e = error.response) === null || _e === void 0 ? void 0 : _e.status} and message ${(_g = (_f = error.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.message}`);
276
- throw new Error((_j = (_h = error.response) === null || _h === void 0 ? void 0 : _h.data) === null || _j === void 0 ? void 0 : _j.message);
277
- }
278
- throw error;
279
- }
280
- }
281
-
282
- let clientConfig = {
283
- // User configured settings
284
- name: '',
285
- logoUrl: '',
286
- apiKey: '',
287
- wsApiUrl: 'wss://ws.tarobase.com',
288
- apiUrl: 'https://api.tarobase.com',
289
- authApiUrl: 'https://auth.tarobase.com',
290
- appId: '',
291
- // Custom data from server
292
- authMethod: 'phantom',
293
- chain: 'solana_devnet',
294
- rpcUrl: '',
295
- skipBackendInit: false,
296
- };
297
- let isInitialized = false;
298
- function init$2(newConfig) {
299
- return new Promise((resolve, reject) => {
300
- if (!newConfig.apiKey && !newConfig.appId) {
301
- reject(new Error('No API key or app ID provided.'));
302
- }
303
- clientConfig = Object.assign(Object.assign({}, clientConfig), newConfig);
304
- if (newConfig.skipBackendInit) {
305
- isInitialized = true;
306
- resolve();
307
- return;
308
- }
309
- isInitialized = true;
310
- makeApiRequest('GET', '/config').then((data) => {
311
- clientConfig = Object.assign(Object.assign(Object.assign({}, clientConfig), data.data), newConfig);
312
- isInitialized = true;
313
- resolve();
314
- }).catch((error) => {
315
- console.error('Failed to authenticate with API key or fetch config for this app:', error);
316
- console.error('Please check your API key and try again.');
317
- reject(new Error("Failed to initialize Tarobase app."));
318
- });
319
- });
320
- }
321
- function waitForInitialization() {
322
- return new Promise((resolve) => {
323
- if (isInitialized) {
324
- resolve();
325
- }
326
- else {
327
- const interval = setInterval(() => {
328
- if (isInitialized) {
329
- clearInterval(interval);
330
- resolve();
331
- }
332
- }, 50);
333
- }
334
- });
335
- }
336
- async function getConfig() {
337
- await waitForInitialization();
338
- return clientConfig;
339
- }
340
-
341
29
  // base-x encoding / decoding
342
30
  // Copyright (c) 2018 base-x contributors
343
31
  // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
@@ -542,8 +230,8 @@ var bn$1 = {exports: {}};
542
230
  var _nodeResolve_empty = {};
543
231
 
544
232
  var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
545
- __proto__: null,
546
- default: _nodeResolve_empty
233
+ __proto__: null,
234
+ default: _nodeResolve_empty
547
235
  });
548
236
 
549
237
  var require$$0 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1);
@@ -4008,47 +3696,230 @@ async function buildSetDocumentsTransaction(connection, idl, anchorProvider, pay
4008
3696
  .remainingAccounts(remainingAccounts)
4009
3697
  .transaction();
4010
3698
  }
4011
- else if (idl.address === "poof4b5pk1L9tmThvBmaABjcyjfhFGbMbQP5BXk2QZp") {
4012
- const program = new anchor.Program(idl, anchorProvider);
4013
- tx = await program.methods
4014
- .setDocuments(args.app_id, prepareAnchorArgs(args.documents), args.delete_paths, args.txData, simulate)
4015
- .preInstructions(instructions)
4016
- .accounts({
4017
- payer: payerPublicKey
4018
- })
4019
- .remainingAccounts(remainingAccounts)
4020
- .transaction();
3699
+ else if (idl.address === "poof4b5pk1L9tmThvBmaABjcyjfhFGbMbQP5BXk2QZp") {
3700
+ const program = new anchor.Program(idl, anchorProvider);
3701
+ tx = await program.methods
3702
+ .setDocuments(args.app_id, prepareAnchorArgs(args.documents), args.delete_paths, args.txData, simulate)
3703
+ .preInstructions(instructions)
3704
+ .accounts({
3705
+ payer: payerPublicKey
3706
+ })
3707
+ .remainingAccounts(remainingAccounts)
3708
+ .transaction();
3709
+ }
3710
+ else {
3711
+ throw new Error(`Invalid program id: ${idl.address}`);
3712
+ }
3713
+ tx.feePayer = payerPublicKey;
3714
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash("confirmed");
3715
+ tx.recentBlockhash = blockhash;
3716
+ if (lutKey == null) {
3717
+ const isSurfnet = anchorProvider.connection.rpcEndpoint == SURFNET_RPC_URL;
3718
+ const computeUnits = isSurfnet ? 1400000 : await getSimulationComputeUnits(connection, tx.instructions, payerPublicKey, []);
3719
+ const computeBudgetIxOptimized = web3_js.ComputeBudgetProgram.setComputeUnitLimit({
3720
+ units: computeUnits ? computeUnits * 1.2 : 1400000,
3721
+ }); // 20% buffer
3722
+ tx.instructions[0] = computeBudgetIxOptimized;
3723
+ return { tx, blockhash, lastValidBlockHeight };
3724
+ }
3725
+ const { value: table } = await connection.getAddressLookupTable(new web3_js.PublicKey(lutKey));
3726
+ if (!table)
3727
+ throw new Error('LUT not found after creation/extend');
3728
+ const isSurfnet = anchorProvider.connection.rpcEndpoint == SURFNET_RPC_URL;
3729
+ const computeUnits = isSurfnet ? 1400000 : await getSimulationComputeUnits(connection, tx.instructions, payerPublicKey, [table]);
3730
+ const computeBudgetIxOptimized = web3_js.ComputeBudgetProgram.setComputeUnitLimit({
3731
+ units: computeUnits ? computeUnits * 1.2 : 1400000,
3732
+ }); // 20% buffer
3733
+ tx.instructions[0] = computeBudgetIxOptimized;
3734
+ const msgV0 = new anchor__namespace.web3.TransactionMessage({
3735
+ payerKey: payerPublicKey,
3736
+ recentBlockhash: blockhash,
3737
+ instructions: tx.instructions,
3738
+ }).compileToV0Message([table]);
3739
+ const vTx = new anchor__namespace.web3.VersionedTransaction(msgV0);
3740
+ return { tx: vTx, blockhash, lastValidBlockHeight };
3741
+ }
3742
+ async function deserializeTransaction(tx) {
3743
+ const buf = Buffer.isBuffer(tx)
3744
+ ? tx
3745
+ : Buffer.from(tx, 'base64');
3746
+ // High bit (0x80) indicates versioned tx
3747
+ if ((buf[0] & 0x80) !== 0) {
3748
+ return web3_js.VersionedTransaction.deserialize(buf);
3749
+ }
3750
+ else {
3751
+ return web3_js.Transaction.from(buf);
3752
+ }
3753
+ }
3754
+
3755
+ let axiosClient;
3756
+ async function getAxiosAuthClient() {
3757
+ if (!axiosClient) {
3758
+ const config = await getConfig();
3759
+ axiosClient = axios.create({
3760
+ baseURL: config.authApiUrl,
3761
+ headers: {
3762
+ 'Content-Type': 'application/json',
3763
+ },
3764
+ });
3765
+ }
3766
+ return axiosClient;
3767
+ }
3768
+ async function createSessionWithSignature(address, message, signature) {
3769
+ const client = await getAxiosAuthClient();
3770
+ const config = await getConfig();
3771
+ const appId = config.appId;
3772
+ const response = await client.post('/session', {
3773
+ appId,
3774
+ address,
3775
+ message,
3776
+ signature,
3777
+ authMethod: config.authMethod
3778
+ });
3779
+ return response.data;
3780
+ }
3781
+ async function createSessionWithPrivy(authToken, address, idToken) {
3782
+ if (typeof window === 'undefined')
3783
+ return;
3784
+ const client = await getAxiosAuthClient();
3785
+ const config = await getConfig();
3786
+ const appId = config.appId;
3787
+ const response = await client.post('/session', {
3788
+ appId,
3789
+ authMethod: config.authMethod,
3790
+ authToken,
3791
+ idToken: idToken,
3792
+ address
3793
+ });
3794
+ return response.data;
3795
+ }
3796
+ async function refreshSession(refreshToken) {
3797
+ const client = await getAxiosAuthClient();
3798
+ const config = await getConfig();
3799
+ const appId = config.appId;
3800
+ const response = await client.post('/session/refresh', {
3801
+ refreshToken,
3802
+ appId
3803
+ });
3804
+ return response.data;
3805
+ }
3806
+
3807
+ class SessionManager {
3808
+ //private static EXPIRATION_TIME: number = 60 * 60 * 1000; // 1 hour
3809
+ static async storeSession(address, accessToken, idToken, refreshToken) {
3810
+ if (typeof window === 'undefined') {
3811
+ return;
3812
+ }
3813
+ // Store the current appId along with the session data
3814
+ const config = await getConfig();
3815
+ const currentAppId = config.appId;
3816
+ localStorage.setItem(this.TAROBASE_SESSION_STORAGE_KEY, JSON.stringify({
3817
+ address,
3818
+ accessToken,
3819
+ idToken,
3820
+ refreshToken,
3821
+ appId: currentAppId
3822
+ }));
3823
+ }
3824
+ static async getSession() {
3825
+ if (typeof window === 'undefined')
3826
+ return null;
3827
+ const session = localStorage.getItem(this.TAROBASE_SESSION_STORAGE_KEY);
3828
+ if (!session)
3829
+ return null;
3830
+ const sessionObj = JSON.parse(session);
3831
+ // Check for appId mismatch
3832
+ const config = await getConfig();
3833
+ const currentAppId = config.appId;
3834
+ const sessionAppId = sessionObj.appId;
3835
+ // If the stored session has a different appId than the current one, invalidate the session
3836
+ if (sessionAppId && sessionAppId !== currentAppId) {
3837
+ console.warn('Session appId mismatch. Stored session belongs to a different app. Logging out.');
3838
+ this.clearSession();
3839
+ return null;
3840
+ }
3841
+ const accessToken = sessionObj.accessToken;
3842
+ try {
3843
+ const accessTokenPayload = JSON.parse(atob(accessToken.split('.')[1]));
3844
+ const expirationTime = accessTokenPayload.exp * 1000; // Convert to milliseconds
3845
+ const currentTime = Date.now();
3846
+ if (currentTime > expirationTime) {
3847
+ const refreshToken = sessionObj.refreshToken;
3848
+ if (!refreshToken) {
3849
+ return null;
3850
+ }
3851
+ const refreshDataSession = await refreshSession(refreshToken);
3852
+ if (refreshDataSession && refreshDataSession.idToken && refreshDataSession.accessToken) {
3853
+ this.updateIdTokenAndAccessToken(refreshDataSession.idToken, refreshDataSession.accessToken);
3854
+ const newSession = localStorage.getItem(this.TAROBASE_SESSION_STORAGE_KEY);
3855
+ if (!newSession)
3856
+ return null;
3857
+ const newSessionObj = JSON.parse(newSession);
3858
+ return { address: newSessionObj.address, session: newSessionObj };
3859
+ }
3860
+ return null;
3861
+ }
3862
+ }
3863
+ catch (error) {
3864
+ console.error('Error decoding access token:', error);
3865
+ return null;
3866
+ }
3867
+ return { address: sessionObj.address, session: sessionObj };
3868
+ }
3869
+ static clearSession() {
3870
+ if (typeof window === 'undefined')
3871
+ return;
3872
+ localStorage.removeItem(this.TAROBASE_SESSION_STORAGE_KEY);
3873
+ }
3874
+ static isAuthenticated() {
3875
+ return !!this.getSession();
4021
3876
  }
4022
- else {
4023
- throw new Error(`Invalid program id: ${idl.address}`);
3877
+ static getIdToken() {
3878
+ if (typeof window === 'undefined')
3879
+ return null;
3880
+ const session = localStorage.getItem(this.TAROBASE_SESSION_STORAGE_KEY);
3881
+ if (!session)
3882
+ return null;
3883
+ const sessionObj = JSON.parse(session);
3884
+ const idToken = sessionObj.idToken;
3885
+ return idToken;
4024
3886
  }
4025
- tx.feePayer = payerPublicKey;
4026
- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash("confirmed");
4027
- tx.recentBlockhash = blockhash;
4028
- if (lutKey == null) {
4029
- const computeUnits = await getSimulationComputeUnits(connection, tx.instructions, payerPublicKey, []);
4030
- const computeBudgetIxOptimized = web3_js.ComputeBudgetProgram.setComputeUnitLimit({
4031
- units: computeUnits ? computeUnits * 1.2 : 1400000,
4032
- }); // 20% buffer
4033
- tx.instructions[0] = computeBudgetIxOptimized;
4034
- return { tx, blockhash, lastValidBlockHeight };
3887
+ static getRefreshToken() {
3888
+ if (typeof window === 'undefined')
3889
+ return null;
3890
+ const session = localStorage.getItem(this.TAROBASE_SESSION_STORAGE_KEY);
3891
+ if (!session)
3892
+ return null;
3893
+ const sessionObj = JSON.parse(session);
3894
+ return sessionObj.refreshToken;
3895
+ }
3896
+ static async updateIdTokenAndAccessToken(idToken, accessToken) {
3897
+ if (typeof window === 'undefined')
3898
+ return;
3899
+ const session = localStorage.getItem(this.TAROBASE_SESSION_STORAGE_KEY);
3900
+ if (!session)
3901
+ return;
3902
+ const sessionObj = JSON.parse(session);
3903
+ // Check for appId mismatch before updating
3904
+ const config = await getConfig();
3905
+ const currentAppId = config.appId;
3906
+ const sessionAppId = sessionObj.appId;
3907
+ // If the stored session has a different appId than the current one, invalidate the session
3908
+ if (sessionAppId && sessionAppId !== currentAppId) {
3909
+ console.warn('Session appId mismatch during token refresh. Stored session belongs to a different app. Logging out.');
3910
+ this.clearSession();
3911
+ return;
3912
+ }
3913
+ sessionObj.idToken = idToken;
3914
+ sessionObj.accessToken = accessToken;
3915
+ // Ensure appId is stored with the updated session
3916
+ if (!sessionObj.appId) {
3917
+ sessionObj.appId = currentAppId;
3918
+ }
3919
+ localStorage.setItem(this.TAROBASE_SESSION_STORAGE_KEY, JSON.stringify(sessionObj));
4035
3920
  }
4036
- const { value: table } = await connection.getAddressLookupTable(new web3_js.PublicKey(lutKey));
4037
- if (!table)
4038
- throw new Error('LUT not found after creation/extend');
4039
- const computeUnits = await getSimulationComputeUnits(connection, tx.instructions, payerPublicKey, [table]);
4040
- const computeBudgetIxOptimized = web3_js.ComputeBudgetProgram.setComputeUnitLimit({
4041
- units: computeUnits ? computeUnits * 1.2 : 1400000,
4042
- }); // 20% buffer
4043
- tx.instructions[0] = computeBudgetIxOptimized;
4044
- const msgV0 = new anchor__namespace.web3.TransactionMessage({
4045
- payerKey: payerPublicKey,
4046
- recentBlockhash: blockhash,
4047
- instructions: tx.instructions,
4048
- }).compileToV0Message([table]);
4049
- const vTx = new anchor__namespace.web3.VersionedTransaction(msgV0);
4050
- return { tx: vTx, blockhash, lastValidBlockHeight };
4051
3921
  }
3922
+ SessionManager.TAROBASE_SESSION_STORAGE_KEY = 'tarobase_session_storage';
4052
3923
 
4053
3924
  const SDK_URL = "https://embedded-wallet.phantom.app/sdk.js";
4054
3925
  const PHANTOM_INITIALIZED_EVENT_NAME = "phantom#embedded#initialized";
@@ -4396,6 +4267,23 @@ class PhantomWalletProvider {
4396
4267
  throw new Error(`Failed to execute transaction: ${error.message}`);
4397
4268
  }
4398
4269
  }
4270
+ async signTransaction(transaction) {
4271
+ try {
4272
+ await this.initialized;
4273
+ if (!this.connection) {
4274
+ throw new Error('Connection not initialized');
4275
+ }
4276
+ const provider = await this.ensureConnected();
4277
+ if (!provider) {
4278
+ throw new Error('Failed to connect to Phantom wallet');
4279
+ }
4280
+ const signedTx = await provider.signTransaction(transaction);
4281
+ return signedTx;
4282
+ }
4283
+ catch (error) {
4284
+ throw new Error(`Failed to sign transaction: ${error.message}`);
4285
+ }
4286
+ }
4399
4287
  async signMessage(message) {
4400
4288
  try {
4401
4289
  // Use ensureConnected to auto-connect if needed
@@ -7114,7 +7002,7 @@ var defaultConverter = {
7114
7002
 
7115
7003
  /* eslint-disable no-var */
7116
7004
 
7117
- function init$1 (converter, defaultAttributes) {
7005
+ function init$2 (converter, defaultAttributes) {
7118
7006
  function set (name, value, attributes) {
7119
7007
  if (typeof document === 'undefined') {
7120
7008
  return
@@ -7199,10 +7087,10 @@ function init$1 (converter, defaultAttributes) {
7199
7087
  );
7200
7088
  },
7201
7089
  withAttributes: function (attributes) {
7202
- return init$1(this.converter, assign({}, this.attributes, attributes))
7090
+ return init$2(this.converter, assign({}, this.attributes, attributes))
7203
7091
  },
7204
7092
  withConverter: function (converter) {
7205
- return init$1(assign({}, this.converter, converter), this.attributes)
7093
+ return init$2(assign({}, this.converter, converter), this.attributes)
7206
7094
  }
7207
7095
  },
7208
7096
  {
@@ -7212,7 +7100,7 @@ function init$1 (converter, defaultAttributes) {
7212
7100
  )
7213
7101
  }
7214
7102
 
7215
- init$1(defaultConverter, { path: '/' });
7103
+ init$2(defaultConverter, { path: '/' });
7216
7104
 
7217
7105
  var t;class i extends Error{toString(){return `${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:""}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}constructor(a,e,s){super(a),e instanceof Error&&(this.cause=e),this.privyErrorCode=s;}}class o extends i{constructor(a,e,s){super(a,e,s),this.type="connector_error";}}((t={}).OAUTH_ACCOUNT_SUSPENDED="oauth_account_suspended",t.MISSING_OR_INVALID_PRIVY_APP_ID="missing_or_invalid_privy_app_id",t.MISSING_OR_INVALID_PRIVY_ACCOUNT_ID="missing_or_invalid_privy_account_id",t.MISSING_OR_INVALID_TOKEN="missing_or_invalid_token",t.INVALID_DATA="invalid_data",t.INVALID_CAPTCHA="invalid_captcha",t.LINKED_TO_ANOTHER_USER="linked_to_another_user",t.CANNOT_LINK_MORE_OF_TYPE="cannot_link_more_of_type",t.FAILED_TO_LINK_ACCOUNT="failed_to_link_account",t.FAILED_TO_UPDATE_ACCOUNT="failed_to_update_account",t.USER_EXITED_UPDATE_FLOW="exited_update_flow",t.ALLOWLIST_REJECTED="allowlist_rejected",t.OAUTH_USER_DENIED="oauth_user_denied",t.OAUTH_UNEXPECTED="oauth_unexpected",t.UNKNOWN_AUTH_ERROR="unknown_auth_error",t.USER_EXITED_AUTH_FLOW="exited_auth_flow",t.USER_EXITED_LINK_FLOW="exited_link_flow",t.USER_EXITED_SET_PASSWORD_FLOW="user_exited_set_password_flow",t.MUST_BE_AUTHENTICATED="must_be_authenticated",t.UNKNOWN_CONNECT_WALLET_ERROR="unknown_connect_wallet_error",t.GENERIC_CONNECT_WALLET_ERROR="generic_connect_wallet_error",t.CLIENT_REQUEST_TIMEOUT="client_request_timeout",t.INVALID_CREDENTIALS="invalid_credentials",t.MISSING_MFA_CREDENTIALS="missing_or_invalid_mfa",t.UNKNOWN_MFA_ERROR="unknown_mfa_error",t.EMBEDDED_WALLET_ALREADY_EXISTS="embedded_wallet_already_exists",t.EMBEDDED_WALLET_NOT_FOUND="embedded_wallet_not_found",t.EMBEDDED_WALLET_CREATE_ERROR="embedded_wallet_create_error",t.UNKNOWN_EMBEDDED_WALLET_ERROR="unknown_embedded_wallet_error",t.EMBEDDED_WALLET_PASSWORD_UNCONFIRMED="embedded_wallet_password_unconfirmed",t.EMBEDDED_WALLET_PASSWORD_ALREADY_EXISTS="embedded_wallet_password_already_exists",t.EMBEDDED_WALLET_RECOVERY_ALREADY_EXISTS="embedded_wallet_recovery_already_exists",t.TRANSACTION_FAILURE="transaction_failure",t.UNSUPPORTED_CHAIN_ID="unsupported_chain_id",t.NOT_SUPPORTED="not_supported",t.CAPTCHA_TIMEOUT="captcha_timeout",t.INVALID_MESSAGE="invalid_message",t.UNABLE_TO_SIGN="unable_to_sign",t.CAPTCHA_FAILURE="captcha_failure",t.CAPTCHA_DISABLED="captcha_disabled",t.SESSION_STORAGE_UNAVAILABLE="session_storage_unavailable",t.TOO_MANY_REQUESTS="too_many_requests",t.USER_LIMIT_REACHED="max_accounts_reached",t.DISALLOWED_LOGIN_METHOD="disallowed_login_method",t.DISALLOWED_PLUS_EMAIL="disallowed_plus_email",t.PASSKEY_NOT_ALLOWED="passkey_not_allowed",t.USER_DOES_NOT_EXIST="user_does_not_exist",t.INSUFFICIENT_BALANCE="insufficient_balance",t.ACCOUNT_TRANSFER_REQUIRED="account_transfer_required",t.BUFFER_NOT_DEFINED="buffer_not_defined",t.UNSUPPORTED_WALLET_TYPE="unsupported_wallet_type",t);const La=a=>()=>{throw Error(a.trim())};
7218
7106
 
@@ -19581,6 +19469,7 @@ class PrivyWalletProvider {
19581
19469
  const useOAuthTokens = privyImports.useOAuthTokens();
19582
19470
  const useFundWalletSolana = privySolana.useFundWallet();
19583
19471
  const useSendTransactionSolana = privySolana.useSendTransaction();
19472
+ const { signTransaction } = privySolana.useSignTransaction();
19584
19473
  const useSolanaWallets = privySolana.useSolanaWallets();
19585
19474
  const useIdentityToken = privyImports.useIdentityToken();
19586
19475
  const { createWallet, wallets, ready: walletReady } = privySolana.useSolanaWallets();
@@ -19676,6 +19565,7 @@ class PrivyWalletProvider {
19676
19565
  useFundWalletSolana: useFundWalletSolana,
19677
19566
  useSendTransactionSolana: useSendTransactionSolana,
19678
19567
  useSolanaWallets: useSolanaWallets,
19568
+ signTransaction: signTransaction,
19679
19569
  };
19680
19570
  }
19681
19571
  }, [privy.ready, privy.authenticated, wallets, login, logout, walletReady]);
@@ -19740,7 +19630,7 @@ class PrivyWalletProvider {
19740
19630
  await this.privyMethods.logout();
19741
19631
  }
19742
19632
  async runTransaction(_evmTransactionData, solTransactionData, options) {
19743
- var _a;
19633
+ var _a, _b, _c;
19744
19634
  await this.ensureReady();
19745
19635
  let session = await SessionManager.getSession();
19746
19636
  let sessionAddress = session === null || session === void 0 ? void 0 : session.address;
@@ -19809,7 +19699,11 @@ class PrivyWalletProvider {
19809
19699
  }
19810
19700
  try {
19811
19701
  if ((options === null || options === void 0 ? void 0 : options.shouldSubmitTx) === false) {
19812
- const signedTx = await wallet.signTransaction(tx);
19702
+ const signedTx = await ((_b = this.privyMethods) === null || _b === void 0 ? void 0 : _b.signTransaction({
19703
+ transaction: tx,
19704
+ connection,
19705
+ address: wallet.address.toString(),
19706
+ }));
19813
19707
  return {
19814
19708
  signedTransaction: signedTx,
19815
19709
  blockNumber: 0,
@@ -19817,7 +19711,19 @@ class PrivyWalletProvider {
19817
19711
  data: ""
19818
19712
  };
19819
19713
  }
19820
- const txSignature = await wallet.sendTransaction(tx, connection);
19714
+ const isSurfnet = connection.rpcEndpoint === SURFNET_RPC_URL;
19715
+ let txSignature;
19716
+ if (isSurfnet) {
19717
+ const signedTx = await ((_c = this.privyMethods) === null || _c === void 0 ? void 0 : _c.signTransaction({
19718
+ transaction: tx,
19719
+ connection,
19720
+ address: wallet.address.toString(),
19721
+ }));
19722
+ txSignature = await connection.sendRawTransaction(signedTx.serialize());
19723
+ }
19724
+ else {
19725
+ txSignature = await privyWallet.sendTransaction(tx, connection);
19726
+ }
19821
19727
  return {
19822
19728
  transactionSignature: txSignature,
19823
19729
  blockNumber: 0,
@@ -19830,6 +19736,27 @@ class PrivyWalletProvider {
19830
19736
  throw err;
19831
19737
  }
19832
19738
  }
19739
+ async signTransaction(transaction) {
19740
+ var _a;
19741
+ try {
19742
+ await this.ensureReady();
19743
+ let privyWallets = (_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.wallets;
19744
+ let session = await SessionManager.getSession();
19745
+ let sessionAddress = session === null || session === void 0 ? void 0 : session.address;
19746
+ let privyWallet = privyWallets === null || privyWallets === void 0 ? void 0 : privyWallets.find((wallet) => wallet.address === sessionAddress);
19747
+ // If there's already a pending transaction, throw an error to prevent overlapping calls
19748
+ if (this.pendingTransaction) {
19749
+ throw new Error("Oops... something went wrong. Please try again.");
19750
+ }
19751
+ if (!privyWallet) {
19752
+ throw new Error("Wallet is not connected");
19753
+ }
19754
+ return await privyWallet.signTransaction(transaction);
19755
+ }
19756
+ catch (error) {
19757
+ throw new Error(`Failed to sign and send serialized transaction: ${error.message}`);
19758
+ }
19759
+ }
19833
19760
  async signMessage(message) {
19834
19761
  var _a;
19835
19762
  await this.ensureReady();
@@ -19895,6 +19822,7 @@ class PrivyWalletProvider {
19895
19822
  PrivyWalletProvider.instance = null;
19896
19823
 
19897
19824
  let currentAuthProvider = null;
19825
+ const SURFNET_RPC_URL = "https://surfpool.fly.dev";
19898
19826
  const SOLANA_DEVNET_RPC_URL = "https://api.devnet.solana.com";
19899
19827
  const SOLANA_MAINNET_RPC_URL = "https://celestia-cegncv-fast-mainnet.helius-rpc.com";
19900
19828
  async function getAuthProvider() {
@@ -19918,6 +19846,9 @@ async function getAuthProvider() {
19918
19846
  else if (config.chain === 'solana_mainnet') {
19919
19847
  defaultPrivyRpcUrl = SOLANA_MAINNET_RPC_URL;
19920
19848
  }
19849
+ else if (config.chain === 'surfnet') {
19850
+ defaultPrivyRpcUrl = SURFNET_RPC_URL;
19851
+ }
19921
19852
  else {
19922
19853
  throw new Error(`Invalid chain: ${config.chain}`);
19923
19854
  }
@@ -19931,6 +19862,9 @@ async function getAuthProvider() {
19931
19862
  else if (config.chain === 'solana_mainnet') {
19932
19863
  defaultPhantomRpcUrl = SOLANA_MAINNET_RPC_URL;
19933
19864
  }
19865
+ else if (config.chain === 'surfnet') {
19866
+ defaultPhantomRpcUrl = SURFNET_RPC_URL;
19867
+ }
19934
19868
  else {
19935
19869
  throw new Error(`Invalid chain: ${config.chain}`);
19936
19870
  }
@@ -19958,6 +19892,149 @@ async function logout$1() {
19958
19892
  await authProvider.logout();
19959
19893
  }
19960
19894
 
19895
+ async function createBearerToken() {
19896
+ const idToken = SessionManager.getIdToken();
19897
+ if (!idToken) {
19898
+ return null;
19899
+ }
19900
+ return `Bearer ${idToken}`;
19901
+ }
19902
+ async function createAuthHeader() {
19903
+ const bearerToken = await createBearerToken();
19904
+ if (!bearerToken) {
19905
+ return null;
19906
+ }
19907
+ return {
19908
+ Authorization: bearerToken
19909
+ };
19910
+ }
19911
+ function getIdToken() {
19912
+ return SessionManager.getIdToken();
19913
+ }
19914
+ function getRefreshToken() {
19915
+ return SessionManager.getRefreshToken();
19916
+ }
19917
+ function updateIdTokenAndAccessToken(idToken, accessToken) {
19918
+ SessionManager.updateIdTokenAndAccessToken(idToken, accessToken);
19919
+ }
19920
+
19921
+ async function makeApiRequest(method, urlPath, data, _overrides) {
19922
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
19923
+ const config = await getConfig();
19924
+ async function executeRequest() {
19925
+ const authHeader = await createAuthHeader();
19926
+ const headers = Object.assign({ 'Content-Type': 'application/json', "X-Public-App-Id": config.appId, "X-App-Id": config.appId }, authHeader);
19927
+ if (typeof window !== 'undefined' && window.CUSTOM_TAROBASE_APP_ID_HEADER) {
19928
+ const customAppId = window.CUSTOM_TAROBASE_APP_ID_HEADER;
19929
+ if (customAppId) {
19930
+ headers["X-App-Id"] = customAppId;
19931
+ }
19932
+ }
19933
+ // Apply custom headers from _overrides
19934
+ if (_overrides === null || _overrides === void 0 ? void 0 : _overrides.headers) {
19935
+ Object.assign(headers, _overrides.headers);
19936
+ }
19937
+ const requestConfig = {
19938
+ method,
19939
+ url: `${config.apiUrl}${urlPath.startsWith('/') ? urlPath : `/${urlPath}`}`,
19940
+ headers,
19941
+ };
19942
+ if (method !== 'GET' && method !== 'get') {
19943
+ requestConfig.data = data ? JSON.stringify(data) : {};
19944
+ }
19945
+ const response = await axios(requestConfig);
19946
+ return { data: response.data, status: response.status };
19947
+ }
19948
+ try {
19949
+ return await executeRequest();
19950
+ }
19951
+ catch (error) {
19952
+ if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 401) {
19953
+ try {
19954
+ const refreshToken = getRefreshToken();
19955
+ if (!refreshToken) {
19956
+ throw new Error("No refresh token found");
19957
+ }
19958
+ const refreshData = await refreshSession(refreshToken);
19959
+ if (refreshData && refreshData.idToken && refreshData.accessToken) {
19960
+ updateIdTokenAndAccessToken(refreshData.idToken, refreshData.accessToken);
19961
+ }
19962
+ return await executeRequest();
19963
+ }
19964
+ catch (refreshError) {
19965
+ throw error;
19966
+ }
19967
+ }
19968
+ if (((_b = error.response) === null || _b === void 0 ? void 0 : _b.status) == 404) {
19969
+ return { data: null, status: 404 };
19970
+ }
19971
+ if ((_d = (_c = error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.message) {
19972
+ console.error(`Error in set call with code ${(_e = error.response) === null || _e === void 0 ? void 0 : _e.status} and message ${(_g = (_f = error.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.message}`);
19973
+ throw new Error((_j = (_h = error.response) === null || _h === void 0 ? void 0 : _h.data) === null || _j === void 0 ? void 0 : _j.message);
19974
+ }
19975
+ throw error;
19976
+ }
19977
+ }
19978
+
19979
+ let clientConfig = {
19980
+ // User configured settings
19981
+ name: '',
19982
+ logoUrl: '',
19983
+ apiKey: '',
19984
+ wsApiUrl: 'wss://ws.tarobase.com',
19985
+ apiUrl: 'https://api.tarobase.com',
19986
+ authApiUrl: 'https://auth.tarobase.com',
19987
+ appId: '',
19988
+ // Custom data from server
19989
+ authMethod: 'phantom',
19990
+ chain: 'surfnet',
19991
+ rpcUrl: SURFNET_RPC_URL,
19992
+ skipBackendInit: false,
19993
+ };
19994
+ let isInitialized = false;
19995
+ function init$1(newConfig) {
19996
+ return new Promise((resolve, reject) => {
19997
+ if (!newConfig.apiKey && !newConfig.appId) {
19998
+ reject(new Error('No API key or app ID provided.'));
19999
+ }
20000
+ clientConfig = Object.assign(Object.assign({}, clientConfig), newConfig);
20001
+ if (newConfig.skipBackendInit) {
20002
+ isInitialized = true;
20003
+ resolve();
20004
+ return;
20005
+ }
20006
+ isInitialized = true;
20007
+ makeApiRequest('GET', '/config').then((data) => {
20008
+ clientConfig = Object.assign(Object.assign(Object.assign({}, clientConfig), data.data), newConfig);
20009
+ isInitialized = true;
20010
+ resolve();
20011
+ }).catch((error) => {
20012
+ console.error('Failed to authenticate with API key or fetch config for this app:', error);
20013
+ console.error('Please check your API key and try again.');
20014
+ reject(new Error("Failed to initialize Tarobase app."));
20015
+ });
20016
+ });
20017
+ }
20018
+ function waitForInitialization() {
20019
+ return new Promise((resolve) => {
20020
+ if (isInitialized) {
20021
+ resolve();
20022
+ }
20023
+ else {
20024
+ const interval = setInterval(() => {
20025
+ if (isInitialized) {
20026
+ clearInterval(interval);
20027
+ resolve();
20028
+ }
20029
+ }, 50);
20030
+ }
20031
+ });
20032
+ }
20033
+ async function getConfig() {
20034
+ await waitForInitialization();
20035
+ return clientConfig;
20036
+ }
20037
+
19961
20038
  let authProviderInstance = null;
19962
20039
  let currentUser = null;
19963
20040
  let authStateListeners = [];
@@ -19965,7 +20042,7 @@ let initCompleted = false;
19965
20042
  // This file acts as a middleware for the global state of the SDK
19966
20043
  // This mostly involves setting up the AuthProvider and managing the current user
19967
20044
  async function init(newConfig) {
19968
- await init$2(newConfig);
20045
+ await init$1(newConfig);
19969
20046
  // Initialize the AuthProvider
19970
20047
  authProviderInstance = await getAuthProvider();
19971
20048
  if (!authProviderInstance) {
@@ -20184,6 +20261,8 @@ async function setMany(many, options) {
20184
20261
  lastTxSignature = transactionResult.transactionSignature;
20185
20262
  signedTransaction = transactionResult.signedTransaction;
20186
20263
  }
20264
+ // Sync items after all transactions are confirmed
20265
+ await syncItems(many.map(m => m.path));
20187
20266
  // TODO: Should we wait here or do the optimistic subscription updates like below?
20188
20267
  return Object.assign(Object.assign({}, document), { transactionId: lastTxSignature, signedTransaction: signedTransaction });
20189
20268
  }
@@ -20329,6 +20408,16 @@ async function setFile(path, file) {
20329
20408
  // Optionally return the file's public URL or some confirmation
20330
20409
  return true;
20331
20410
  }
20411
+ async function syncItems(paths) {
20412
+ try {
20413
+ console.log('Syncing items', paths);
20414
+ const response = await makeApiRequest('PUT', 'items/sync', { paths }, undefined);
20415
+ return response.data;
20416
+ }
20417
+ catch (error) {
20418
+ throw error;
20419
+ }
20420
+ }
20332
20421
 
20333
20422
  /*! *****************************************************************************
20334
20423
  Copyright (c) Microsoft Corporation. All rights reserved.
@@ -21120,6 +21209,7 @@ function useAuth() {
21120
21209
  };
21121
21210
  }
21122
21211
 
21212
+ exports.deserializeTransaction = deserializeTransaction;
21123
21213
  exports.get = get;
21124
21214
  exports.getAuthProvider = getAuthProvider;
21125
21215
  exports.getConfig = getConfig;
@@ -21136,5 +21226,6 @@ exports.set = set;
21136
21226
  exports.setFile = setFile;
21137
21227
  exports.setMany = setMany;
21138
21228
  exports.subscribe = subscribe;
21229
+ exports.syncItems = syncItems;
21139
21230
  exports.useAuth = useAuth;
21140
21231
  //# sourceMappingURL=index.js.map