@monygroupcorp/micro-web3 0.1.0

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.
@@ -0,0 +1,191 @@
1
+ class PriceService {
2
+ constructor(blockchainService, eventBus, updateInterval = 60000) {
3
+ if (!blockchainService || !eventBus) {
4
+ throw new Error('PriceService requires blockchainService and eventBus instances.');
5
+ }
6
+ this._blockchainService = blockchainService;
7
+ this.eventBus = eventBus;
8
+
9
+ this._cache = new Map();
10
+ this._contractUpdateInterval = null;
11
+ this._updateIntervalTime = updateInterval;
12
+ this._cacheExpirationTime = 5 * 60 * 1000; // 5 minutes
13
+
14
+ this._updateDebounceTimeout = null;
15
+ this._updateDebounceDelay = 2000; // 2 seconds
16
+ this._lastEmittedData = null;
17
+
18
+ this.getCurrentPrice = this.getCurrentPrice.bind(this);
19
+ this.startContractUpdates = this.startContractUpdates.bind(this);
20
+ this.stopContractUpdates = this.stopContractUpdates.bind(this);
21
+ this.debouncedUpdateContractData = this.debouncedUpdateContractData.bind(this);
22
+ }
23
+
24
+ // Initialize with an address
25
+ initialize(address = null) {
26
+ console.log('PriceService: Fetching initial data immediately', address ? `for address: ${address}` : '(no address yet)');
27
+ this.updateContractData(address).catch(error => {
28
+ console.error('Failed to fetch initial contract data:', error);
29
+ });
30
+
31
+ this.startContractUpdates(address);
32
+ }
33
+
34
+ async getCurrentPrice() {
35
+ try {
36
+ if (!this._blockchainService) {
37
+ throw new Error('PriceService not initialized');
38
+ }
39
+
40
+ const cachedPrice = this._getCacheValue('currentPrice');
41
+ if (cachedPrice !== null) {
42
+ return cachedPrice;
43
+ }
44
+
45
+ const price = await this._blockchainService.getTokenPrice();
46
+
47
+ if (typeof price !== 'number' || isNaN(price) || price <= 0) {
48
+ console.error('Invalid price value:', price);
49
+ throw new Error('Invalid price value received');
50
+ }
51
+
52
+ this._setCacheValue('currentPrice', price);
53
+ this.eventBus.emit('price:updated', { price });
54
+
55
+ return price;
56
+ } catch (error) {
57
+ console.error('Error fetching price:', error);
58
+ throw error;
59
+ }
60
+ }
61
+
62
+ async calculateCost(execAmount) {
63
+ try {
64
+ if (!this._blockchainService) {
65
+ throw new Error('PriceService not initialized');
66
+ }
67
+ return await this._blockchainService.calculateCost(execAmount);
68
+ } catch (error) {
69
+ console.error('Error calculating cost:', error);
70
+ throw error;
71
+ }
72
+ }
73
+
74
+ async updateContractData(address = null) {
75
+ try {
76
+ const dataPromises = [
77
+ this._blockchainService.getCurrentPrice(),
78
+ this._blockchainService.getTotalBondingSupply(),
79
+ this._blockchainService.getTotalMessages(),
80
+ this._blockchainService.getNFTSupply(),
81
+ this._blockchainService.getFreeSupply(),
82
+ this._blockchainService.getContractEthBalance(),
83
+ this._blockchainService.getCurrentTier(),
84
+ this._blockchainService.getLiquidityPool(),
85
+ ];
86
+
87
+ if (address) {
88
+ dataPromises.push(
89
+ this._blockchainService.getEthBalance(address),
90
+ this._blockchainService.getTokenBalance(address),
91
+ this._blockchainService.getNFTBalance(address),
92
+ this._blockchainService.getFreeMint(address)
93
+ );
94
+ }
95
+
96
+ const [
97
+ currentPrice,
98
+ totalBondingSupply,
99
+ totalMessages,
100
+ totalNFTs,
101
+ freeSupply,
102
+ contractEthBalance,
103
+ currentTier,
104
+ liquidityPool,
105
+ ethBalance,
106
+ tokenBalance,
107
+ nftBalance,
108
+ freeMint,
109
+ ] = await Promise.all(dataPromises);
110
+
111
+ const contractData = {
112
+ totalBondingSupply,
113
+ currentPrice,
114
+ totalMessages,
115
+ totalNFTs,
116
+ freeSupply,
117
+ freeMint: freeMint !== undefined ? freeMint : false,
118
+ contractEthBalance,
119
+ currentTier,
120
+ liquidityPool,
121
+ };
122
+
123
+ const balances = {
124
+ eth: ethBalance || '0',
125
+ exec: tokenBalance || '0',
126
+ nfts: nftBalance || 0,
127
+ };
128
+
129
+ const contractDataChanged = !this._lastEmittedData || JSON.stringify(this._lastEmittedData.contractData) !== JSON.stringify(contractData);
130
+ const balancesChanged = !this._lastEmittedData || JSON.stringify(this._lastEmittedData.balances) !== JSON.stringify(balances);
131
+
132
+ if (contractDataChanged) {
133
+ this.eventBus.emit('contractData:updated', contractData);
134
+ }
135
+
136
+ if (balancesChanged) {
137
+ this.eventBus.emit('balances:updated', balances);
138
+ }
139
+
140
+ if (!this._lastEmittedData || this._lastEmittedData.contractData.currentPrice !== currentPrice) {
141
+ this.eventBus.emit('price:updated', { price: currentPrice });
142
+ }
143
+
144
+ this._lastEmittedData = { contractData, balances };
145
+
146
+ } catch (error) {
147
+ console.error('Error updating contract data:', error);
148
+ this.eventBus.emit('price:error', { error: error.message });
149
+ }
150
+ }
151
+
152
+ startContractUpdates() {
153
+ this.stopContractUpdates(); // Clear any existing interval
154
+
155
+ // Initial contract data fetch
156
+ this.debouncedUpdateContractData();
157
+
158
+ // Set up interval for contract updates
159
+ this._contractUpdateInterval = setInterval(() => {
160
+ this.debouncedUpdateContractData();
161
+ }, this._updateIntervalTime);
162
+ }
163
+
164
+ stopContractUpdates() {
165
+ if (this._contractUpdateInterval) {
166
+ clearInterval(this._contractUpdateInterval);
167
+ this._contractUpdateInterval = null;
168
+ }
169
+ }
170
+
171
+ _setCacheValue(key, value) {
172
+ this._cache.set(key, {
173
+ value,
174
+ timestamp: Date.now()
175
+ });
176
+ }
177
+
178
+ debouncedUpdateContractData(address = null) {
179
+ if (this._updateDebounceTimeout) {
180
+ clearTimeout(this._updateDebounceTimeout);
181
+ }
182
+
183
+ this._updateDebounceTimeout = setTimeout(() => {
184
+ this.updateContractData(address).catch(error => {
185
+ console.error('Failed to update contract data:', error);
186
+ });
187
+ }, this._updateDebounceDelay);
188
+ }
189
+ }
190
+
191
+ export default PriceService;