@explorins/pers-sdk 1.2.1 → 1.2.2

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