@explorins/pers-sdk 1.2.1 → 1.2.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 (39) hide show
  1. package/dist/auth-admin/api/auth-admin-api.d.ts.map +1 -1
  2. package/dist/auth-admin/index.d.ts +2 -2
  3. package/dist/auth-admin.cjs +2 -1
  4. package/dist/auth-admin.cjs.map +1 -1
  5. package/dist/auth-admin.js +2 -1
  6. package/dist/auth-admin.js.map +1 -1
  7. package/dist/business/index.d.ts +9 -9
  8. package/dist/campaign/index.d.ts +19 -19
  9. package/dist/donation/index.d.ts +1 -1
  10. package/dist/donation.cjs +1 -1
  11. package/dist/donation.cjs.map +1 -1
  12. package/dist/donation.js +1 -1
  13. package/dist/donation.js.map +1 -1
  14. package/dist/index.cjs +287 -43
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.js +287 -43
  17. package/dist/index.js.map +1 -1
  18. package/dist/package.json +129 -129
  19. package/dist/payment/index.d.ts +6 -6
  20. package/dist/redemption/index.d.ts +10 -10
  21. package/dist/tenant/index.d.ts +4 -4
  22. package/dist/transaction/index.d.ts +8 -8
  23. package/dist/web3/index.d.ts +1 -2
  24. package/dist/web3/index.d.ts.map +1 -1
  25. package/dist/web3-chain/services/getWeb3FCD.service.d.ts +9 -0
  26. package/dist/web3-chain/services/getWeb3FCD.service.d.ts.map +1 -1
  27. package/dist/web3-chain/services/provider.service.d.ts +3 -5
  28. package/dist/web3-chain/services/provider.service.d.ts.map +1 -1
  29. package/dist/web3-chain/services/public-http-provider.service.d.ts +0 -7
  30. package/dist/web3-chain/services/public-http-provider.service.d.ts.map +1 -1
  31. package/dist/web3-chain.cjs +279 -40
  32. package/dist/web3-chain.cjs.map +1 -1
  33. package/dist/web3-chain.js +279 -40
  34. package/dist/web3-chain.js.map +1 -1
  35. package/dist/web3.cjs +371 -3
  36. package/dist/web3.cjs.map +1 -1
  37. package/dist/web3.js +371 -3
  38. package/dist/web3.js.map +1 -1
  39. package/package.json +129 -129
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { jwtDecode } from 'jwt-decode';
2
2
  import Web3 from 'web3';
3
- import { ChainTypes as ChainTypes$1, getSmartContractInstance, getAddressTokenBalanceByContract, getTokenUri, getTokenOfOwnerByIndex } from '@explorins/web3-ts';
4
3
  import { FetchRequest, JsonRpcProvider } from 'ethers';
4
+ import { getSmartContractInstance, getAddressTokenBalanceByContract, getTokenUri, getTokenOfOwnerByIndex } from '@explorins/web3-ts';
5
5
 
6
6
  /**
7
7
  * PERS SDK Configuration interfaces
@@ -1276,7 +1276,8 @@ class AuthAdminApi {
1276
1276
  */
1277
1277
  async loginTenantAdmin(jwt) {
1278
1278
  // TODO: Implement proper JWT and bypass header handling when PersApiClient supports it
1279
- return this.apiClient.post(`${this.basePath}/token`, {});
1279
+ const requestBody = { authToken: jwt };
1280
+ return this.apiClient.post(`${this.basePath}/token`, requestBody);
1280
1281
  }
1281
1282
  /**
1282
1283
  * ADMIN: Refresh access token
@@ -1861,7 +1862,7 @@ class DonationApi {
1861
1862
  * ✅ ONLY method actually used by framework
1862
1863
  */
1863
1864
  async getAllDonationTypes() {
1864
- return this.apiClient.get('/purchase/donation/type');
1865
+ return this.apiClient.get('/purchases/donation-types');
1865
1866
  }
1866
1867
  }
1867
1868
 
@@ -3673,79 +3674,197 @@ class Web3ChainService {
3673
3674
  }
3674
3675
  }
3675
3676
 
3676
- //IMPORTANT//
3677
- //This function is temporary so we install ethers just to make it work, once we delete this function we must uninstall Ethers
3677
+ // ✅ REVERT: Función síncrona como el código comentado que funciona
3678
3678
  const getWeb3ProviderFromChainData = (chainData, timeout = 15000, customUserAgentName = '', tokenRefresher) => {
3679
- // Fixed ethers provider setup for authenticated requests
3679
+ console.log(`🔧 [getWeb3FCD] Creating provider for chain ${chainData.chainId || 'unknown'}`);
3680
3680
  let ethersProvider;
3681
3681
  if (chainData.authHeader) {
3682
- // For authenticated requests, create a custom FetchRequest
3682
+ // AUTHENTICATED: For private chains
3683
3683
  const fetchRequest = new FetchRequest(chainData.rpcUrl);
3684
3684
  fetchRequest.timeout = timeout;
3685
- fetchRequest.setHeader('Authorization', chainData.authHeader);
3685
+ // ✅ IMPROVED AUTH HEADER: Better handling
3686
+ const authValue = chainData.authHeader.startsWith('Bearer ')
3687
+ ? chainData.authHeader
3688
+ : `Bearer ${chainData.authHeader}`;
3689
+ fetchRequest.setHeader('Authorization', authValue);
3686
3690
  fetchRequest.setHeader('Content-Type', 'application/json');
3691
+ fetchRequest.setHeader('Accept', 'application/json');
3687
3692
  if (customUserAgentName) {
3688
3693
  fetchRequest.setHeader('User-Agent', customUserAgentName);
3689
3694
  }
3690
- // Create provider with the configured FetchRequest
3691
3695
  ethersProvider = new JsonRpcProvider(fetchRequest, undefined, {
3692
3696
  staticNetwork: false,
3693
- polling: false, // Disable polling for better Lambda performance
3697
+ polling: false,
3698
+ batchMaxCount: 1, // ✅ DISABLE BATCHING: Better for private chains
3694
3699
  });
3695
3700
  }
3696
3701
  else {
3697
- // For public chains, use simple URL-based provider
3702
+ // ✅ PUBLIC: For public chains
3698
3703
  ethersProvider = new JsonRpcProvider(chainData.rpcUrl, undefined, {
3699
3704
  staticNetwork: false,
3700
3705
  polling: false,
3701
3706
  });
3702
3707
  }
3708
+ console.log(`✅ [getWeb3FCD] Provider created successfully`);
3703
3709
  return {
3704
3710
  web3Provider: null,
3705
3711
  ethersProvider: ethersProvider,
3706
3712
  isAuthenticated: !!chainData.authHeader,
3707
3713
  };
3708
3714
  };
3715
+ // ✅ NEW: Async wrapper with retry for higher-level usage
3716
+ const getWeb3ProviderWithRetry = async (chainData, timeout = 15000, customUserAgentName = '', tokenRefresher, retryConfig = { maxAttempts: 3, baseDelay: 1000, maxDelay: 8000 }) => {
3717
+ let lastError = null;
3718
+ for (let attempt = 1; attempt <= retryConfig.maxAttempts; attempt++) {
3719
+ try {
3720
+ console.log(`🔄 [Web3Provider] Attempt ${attempt}/${retryConfig.maxAttempts} for chain ${chainData.chainId || 'unknown'}`);
3721
+ // ✅ SYNC CALL: Use the original sync function
3722
+ const provider = getWeb3ProviderFromChainData(chainData, timeout, customUserAgentName, tokenRefresher);
3723
+ await validateChainConnection(provider.ethersProvider, chainData.authHeader ? 'private' : 'public');
3724
+ console.log(`✅ [Web3Provider] Successfully connected on attempt ${attempt}`);
3725
+ return provider;
3726
+ }
3727
+ catch (error) {
3728
+ lastError = error instanceof Error ? error : new Error(String(error));
3729
+ console.warn(`⚠️ [Web3Provider] Attempt ${attempt} failed:`, lastError.message);
3730
+ // ✅ NO RETRY: if auth error, no retry
3731
+ if (isAuthError(lastError) && chainData.authHeader) {
3732
+ console.error(`❌ [Web3Provider] Auth error, stopping retries`);
3733
+ break;
3734
+ }
3735
+ if (attempt === retryConfig.maxAttempts)
3736
+ break;
3737
+ const delay = Math.min(retryConfig.baseDelay * Math.pow(2, attempt - 1), retryConfig.maxDelay);
3738
+ console.log(`⏳ [Web3Provider] Retrying in ${delay}ms...`);
3739
+ await sleep(delay);
3740
+ }
3741
+ }
3742
+ throw new Error(`Failed to create Web3 provider after ${retryConfig.maxAttempts} attempts. Last error: ${lastError?.message}`);
3743
+ };
3744
+ async function validateChainConnection(provider, chainType) {
3745
+ try {
3746
+ console.log(`🔍 [Validation] Testing ${chainType} chain connection...`);
3747
+ // ✅ LIGHTWEIGHT TEST: Use eth_chainId (works for both public and private)
3748
+ const timeoutPromise = new Promise((_, reject) => {
3749
+ setTimeout(() => reject(new Error(`${chainType} chain validation timeout`)), 3000);
3750
+ });
3751
+ // Try chainId first (fast, lightweight, universal)
3752
+ const chainIdPromise = provider.send('eth_chainId', []);
3753
+ const result = await Promise.race([chainIdPromise, timeoutPromise]);
3754
+ console.log(`✅ [Validation] ${chainType} chain connection validated - Chain ID: ${result}`);
3755
+ }
3756
+ catch (error) {
3757
+ // ✅ FALLBACK: Try net_version if chainId fails
3758
+ try {
3759
+ console.log(`🔄 [Validation] Trying fallback validation for ${chainType} chain...`);
3760
+ const timeoutPromise = new Promise((_, reject) => {
3761
+ setTimeout(() => reject(new Error(`${chainType} chain fallback validation timeout`)), 3000);
3762
+ });
3763
+ const versionPromise = provider.send('net_version', []);
3764
+ const result = await Promise.race([versionPromise, timeoutPromise]);
3765
+ console.log(`✅ [Validation] ${chainType} chain connection validated via fallback - Network Version: ${result}`);
3766
+ }
3767
+ catch (fallbackError) {
3768
+ throw new Error(`${chainType} chain validation failed: ${error instanceof Error ? error.message : String(error)}`);
3769
+ }
3770
+ }
3771
+ }
3772
+ // ✅ HELPER: Auth error detection
3773
+ function isAuthError(error) {
3774
+ const message = error.message.toLowerCase();
3775
+ return (message.includes('unauthorized') ||
3776
+ message.includes('401') ||
3777
+ message.includes('token expired') ||
3778
+ message.includes('-40100'));
3779
+ }
3780
+ // ✅ HELPER: Sleep utility
3781
+ function sleep(ms) {
3782
+ return new Promise(resolve => setTimeout(resolve, ms));
3783
+ }
3784
+ /*
3785
+ //IMPORTANT//
3786
+ //This function is temporary so we install ethers just to make it work, once we delete this function we must uninstall Ethers
3787
+
3788
+ import { ChainData } from "@explorins/web3-ts";
3789
+ import { FetchRequest, JsonRpcProvider } from "ethers";
3790
+
3791
+ export const getWeb3ProviderFromChainData = (
3792
+ chainData: ChainData,
3793
+ timeout = 15000,
3794
+ customUserAgentName = '',
3795
+ tokenRefresher?: () => Promise<string>
3796
+ ) => {
3797
+
3798
+ // Fixed ethers provider setup for authenticated requests
3799
+ let ethersProvider: JsonRpcProvider;
3800
+
3801
+ if (chainData.authHeader) {
3802
+ // For authenticated requests, create a custom FetchRequest
3803
+ const fetchRequest = new FetchRequest(chainData.rpcUrl);
3804
+ fetchRequest.timeout = timeout;
3805
+ fetchRequest.setHeader('Authorization', chainData.authHeader);
3806
+ fetchRequest.setHeader('Content-Type', 'application/json');
3807
+
3808
+ if (customUserAgentName) {
3809
+ fetchRequest.setHeader('User-Agent', customUserAgentName);
3810
+ }
3811
+
3812
+ // Create provider with the configured FetchRequest
3813
+ ethersProvider = new JsonRpcProvider(fetchRequest, undefined, {
3814
+ staticNetwork: false,
3815
+ polling: false, // Disable polling for better Lambda performance
3816
+ });
3817
+ } else {
3818
+ // For public chains, use simple URL-based provider
3819
+ ethersProvider = new JsonRpcProvider(chainData.rpcUrl, undefined, {
3820
+ staticNetwork: false,
3821
+ polling: false,
3822
+ });
3823
+ }
3824
+
3825
+ return {
3826
+ web3Provider: null,
3827
+ ethersProvider: ethersProvider,
3828
+ isAuthenticated: !!chainData.authHeader,
3829
+ };
3830
+ }; */
3709
3831
 
3710
3832
  class Web3ProviderService {
3711
- constructor(publicHttpProviderService) {
3712
- this.publicHttpProviderService = publicHttpProviderService;
3833
+ constructor() {
3713
3834
  this._web3 = null;
3714
3835
  this._currentChainId = null;
3836
+ this._creationPromise = null;
3715
3837
  }
3716
- async getWeb3(chainId, chainType, privateChainData = null) {
3717
- if (!this._web3 || this._currentChainId !== chainId) {
3718
- if (!chainId)
3719
- throw new Error('ChainId not found');
3720
- try {
3721
- this._currentChainId = chainId;
3722
- const provider = await this.getWeb3ByChainId(chainId, chainType, privateChainData);
3723
- this._web3 = this.convertToWeb3(provider);
3724
- }
3725
- catch (error) {
3726
- console.error('Error getting web3 connection from chain id ' + chainId, error);
3727
- throw new Error('Error getting web3 connection from chain id ' + chainId);
3728
- }
3838
+ async getWeb3(chainId, chainType, chainData) {
3839
+ // EARLY RETURN: Reuse existing provider
3840
+ if (this._web3 && this._currentChainId === chainId) {
3841
+ return this._web3;
3729
3842
  }
3730
- return this._web3;
3731
- }
3732
- // Keep return type as 'any' to avoid TypeScript errors while still being adapted later
3733
- getWeb3ByChainId(chainId, chainType, privateChainData = null) {
3734
- // Rest of the method remains the same
3735
- if (chainType === ChainTypes$1.PRIVATE && privateChainData) {
3736
- //const privateProvider = this.privateChainProviderService.getProviderFromChainData(privateChainData)
3737
- const privateProvider = getWeb3ProviderFromChainData(privateChainData);
3738
- if (!privateProvider || privateProvider instanceof Error)
3739
- throw new Error('Error getting web3 provider');
3740
- return privateProvider;
3843
+ // ✅ PREVENT RACE CONDITION: Wait for ongoing creation
3844
+ if (this._creationPromise) {
3845
+ return await this._creationPromise;
3741
3846
  }
3742
- else {
3743
- const publicProvider = this.publicHttpProviderService.getProvider(chainId);
3744
- if (!publicProvider || publicProvider instanceof Error)
3745
- throw new Error('Error getting web3 provider');
3746
- return publicProvider;
3847
+ if (!chainId)
3848
+ throw new Error('ChainId not found');
3849
+ if (!chainData)
3850
+ throw new Error('ChainData not found');
3851
+ // ✅ CREATE AND CACHE: Single promise for concurrent calls
3852
+ this._creationPromise = this.createProvider(chainId, chainType, chainData);
3853
+ try {
3854
+ const web3Instance = await this._creationPromise;
3855
+ this._web3 = web3Instance;
3856
+ this._currentChainId = chainId;
3857
+ return web3Instance;
3858
+ }
3859
+ finally {
3860
+ // ✅ CLEANUP: Always reset promise after completion
3861
+ this._creationPromise = null;
3747
3862
  }
3748
3863
  }
3864
+ async createProvider(chainId, chainType, chainData) {
3865
+ const provider = await getWeb3ProviderWithRetry(chainData);
3866
+ return this.convertToWeb3(provider);
3867
+ }
3749
3868
  convertToWeb3(provider) {
3750
3869
  if (provider instanceof Web3) {
3751
3870
  return provider;
@@ -3797,6 +3916,128 @@ class Web3ProviderService {
3797
3916
  {};
3798
3917
  }
3799
3918
  }
3919
+ /* import Web3 from "web3";
3920
+ import { ChainData, ChainType, ChainTypes } from "@explorins/web3-ts";
3921
+ import { PublicHttpProviderService } from "./public-http-provider.service";
3922
+ import { getWeb3ProviderFromChainData } from "./getWeb3FCD.service";
3923
+
3924
+
3925
+ export class Web3ProviderService {
3926
+
3927
+ private _web3: Web3 | null = null;
3928
+ private _currentChainId: number | null = null;
3929
+
3930
+ constructor(
3931
+ private readonly publicHttpProviderService: PublicHttpProviderService,
3932
+ ) {
3933
+ }
3934
+
3935
+ public async getWeb3(chainId: number, chainType: ChainType, privateChainData: ChainData | null = null) {
3936
+ if (!this._web3 || this._currentChainId !== chainId) {
3937
+
3938
+ if(!chainId) throw new Error('ChainId not found')
3939
+
3940
+ try {
3941
+ this._currentChainId = chainId;
3942
+ const provider = await this.getWeb3ByChainId(chainId, chainType, privateChainData);
3943
+ this._web3 = this.convertToWeb3(provider);
3944
+ } catch (error) {
3945
+ console.error('Error getting web3 connection from chain id ' + chainId , error)
3946
+ throw new Error('Error getting web3 connection from chain id ' + chainId)
3947
+ }
3948
+ }
3949
+ return this._web3 as Web3;
3950
+ }
3951
+
3952
+ // Keep return type as 'any' to avoid TypeScript errors while still being adapted later
3953
+ private getWeb3ByChainId(chainId: number, chainType: ChainType, privateChainData: ChainData | null = null): any {
3954
+ // Rest of the method remains the same
3955
+ if(chainType === ChainTypes.PRIVATE && privateChainData) {
3956
+ //const privateProvider = this.privateChainProviderService.getProviderFromChainData(privateChainData)
3957
+ const privateProvider = getWeb3ProviderFromChainData(privateChainData);
3958
+
3959
+ if(!privateProvider || privateProvider instanceof Error) throw new Error('Error getting web3 provider');
3960
+
3961
+
3962
+ return privateProvider;
3963
+
3964
+ } else {
3965
+
3966
+ const publicProvider = this.publicHttpProviderService.getProvider(chainId)
3967
+ if(!publicProvider || publicProvider instanceof Error) throw new Error('Error getting web3 provider');
3968
+
3969
+ return publicProvider;
3970
+ }
3971
+ }
3972
+
3973
+ private convertToWeb3(provider: unknown): Web3 {
3974
+ if (provider instanceof Web3) {
3975
+ return provider as Web3;
3976
+ }
3977
+
3978
+ if (provider && typeof provider === 'object' && 'web3Provider' in provider) {
3979
+ const providerObj = provider as {
3980
+ web3Provider?: unknown;
3981
+ ethersProvider?: any;
3982
+ isAuthenticated?: boolean;
3983
+ };
3984
+
3985
+ // If we want to user the web3Provider directly:
3986
+ /*if (providerObj.web3Provider) {
3987
+ return new Web3(providerObj.web3Provider as never);
3988
+ }*/
3989
+ /*if (providerObj.ethersProvider) {
3990
+
3991
+ const url = this.extractUrlFromEthersProvider(providerObj.ethersProvider);
3992
+ const headers = this.extractHeadersFromEthersProvider(providerObj.ethersProvider);
3993
+
3994
+ const web3 = new Web3(url);
3995
+ const currentProvider = web3.currentProvider as unknown as Record<string, unknown>;
3996
+
3997
+ if (currentProvider) {
3998
+ currentProvider['url'] = url;
3999
+
4000
+ if (headers && Object.keys(headers).length > 0) {
4001
+ currentProvider['request'] = async (payload: Record<string, unknown>): Promise<Record<string, unknown>> => {
4002
+ const response = await fetch(url, {
4003
+ method: 'POST',
4004
+ headers: {
4005
+ 'Content-Type': 'application/json',
4006
+ ...headers
4007
+ },
4008
+ body: JSON.stringify(payload)
4009
+ });
4010
+
4011
+ if (!response.ok) {
4012
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
4013
+ }
4014
+
4015
+ return await response.json() as Record<string, unknown>;
4016
+ };
4017
+ }
4018
+ }
4019
+
4020
+ return web3;
4021
+ }
4022
+ }
4023
+
4024
+ return new Web3(provider as never);
4025
+ }
4026
+
4027
+
4028
+ private extractUrlFromEthersProvider(ethersProvider: any): string {
4029
+ return ethersProvider.connection?.url ||
4030
+ ethersProvider._getConnection?.()?.url ||
4031
+ ethersProvider.url ||
4032
+ '';
4033
+ }
4034
+
4035
+ private extractHeadersFromEthersProvider(ethersProvider: any): Record<string, string> {
4036
+ return ethersProvider.connection?.headers ||
4037
+ ethersProvider._getConnection?.()?.headers ||
4038
+ {};
4039
+ }
4040
+ } */
3800
4041
 
3801
4042
  /**
3802
4043
  * Web3 Chain Domain Models
@@ -4147,7 +4388,10 @@ class Web3Service {
4147
4388
  }
4148
4389
  }
4149
4390
 
4150
- function createWeb3SDK(apiClient, web3ProviderService) {
4391
+ //import { PublicHttpProviderService } from '../web3-chain/services/public-http-provider.service';
4392
+ function createWeb3SDK(apiClient) {
4393
+ // TODO: FIX LATER - TEMPORARY CONSTRUCTION
4394
+ const web3ProviderService = new Web3ProviderService();
4151
4395
  const web3ChainSDK = createWeb3ChainSDK(apiClient, web3ProviderService);
4152
4396
  const web3Api = new Web3Api(web3ChainSDK.service);
4153
4397
  const web3Service = new Web3Service(web3Api, web3ChainSDK.service);