-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
386 lines (332 loc) · 12 KB
/
Copy pathapp.js
File metadata and controls
386 lines (332 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// Initialize Telegram Web App
const tg = window.Telegram.WebApp;
tg.ready();
tg.expand();
// Set theme colors - white theme
tg.setHeaderColor('#ffffff');
tg.setBackgroundColor('#ffffff');
// Get user ID from Telegram or URL
function getUserID() {
// Try Telegram WebApp first
if (tg.initDataUnsafe?.user?.id) {
return tg.initDataUnsafe.user.id;
}
// Fallback to URL parameter
const urlParams = new URLSearchParams(window.location.search);
const userId = urlParams.get('user_id');
if (userId) {
return parseInt(userId);
}
return null;
}
// API endpoint - get from environment or use default
// For Vercel, this should be set as environment variable
// Default to Railway URL
const API_URL = process.env.API_URL || window.API_URL || 'https://web-production-11ef2.up.railway.app/api/stats';
// Extract base URL - if API_URL ends with /api/stats, remove it
const BOT_API_URL = API_URL.endsWith('/api/stats') ? API_URL.replace('/api/stats', '') : API_URL.replace('/stats', '');
// TON Connect
let tonConnectUI = null;
let walletAddress = null;
// Initialize TON Connect
function initTONConnect() {
if (typeof TonConnectUI !== 'undefined') {
tonConnectUI = new TonConnectUI({
manifestUrl: `${window.location.origin}/tonconnect-manifest.json`,
buttonRootId: 'ton-connect-btn'
});
// Check if wallet is already connected
tonConnectUI.connectionRestored.then(() => {
const account = tonConnectUI.wallet?.account;
if (account) {
walletAddress = account.address;
console.log('TON wallet connected:', walletAddress);
updateUI();
}
});
// Handle wallet connection
tonConnectUI.onStatusChange((wallet) => {
if (wallet) {
walletAddress = wallet.account.address;
console.log('TON wallet connected:', walletAddress);
updateUI();
} else {
walletAddress = null;
console.log('TON wallet disconnected');
updateUI();
}
});
} else {
console.error('TON Connect UI not loaded');
}
}
// Check payment status
async function checkPaymentStatus() {
const userId = getUserID();
if (!userId) return;
try {
const response = await fetch(`${BOT_API_URL}/api/ton/payment_info?user_id=${userId}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
if (response.ok) {
const data = await response.json();
console.log('Payment info:', data);
// Show payment section if needed
const paymentSection = document.getElementById('payment-section');
const tonConnectSection = document.getElementById('ton-connect-section');
if (data.needs_payment) {
// Update payment info
document.getElementById('ton-price').textContent = data.ton_price;
document.getElementById('eggs-pack-size').textContent = data.eggs_per_pack;
document.getElementById('pay-amount').textContent = data.ton_price;
// Show payment section if wallet is connected
if (walletAddress) {
paymentSection.style.display = 'block';
tonConnectSection.style.display = 'none';
} else {
tonConnectSection.style.display = 'block';
paymentSection.style.display = 'none';
}
} else {
paymentSection.style.display = 'none';
tonConnectSection.style.display = 'none';
}
}
} catch (error) {
console.error('Error checking payment status:', error);
}
}
// Handle TON payment
async function handleTONPayment() {
const userId = getUserID();
if (!userId || !walletAddress) {
alert('Please connect your TON wallet first');
return;
}
try {
// Get payment info
const response = await fetch(`${BOT_API_URL}/api/ton/payment_info?user_id=${userId}`);
const paymentInfo = await response.json();
if (!paymentInfo.needs_payment) {
alert('You don\'t need to pay right now');
return;
}
const amount = paymentInfo.ton_price; // 0.1 TON
const wallet = paymentInfo.ton_wallet; // Recipient wallet
// Create transaction
const transaction = {
validUntil: Math.floor(Date.now() / 1000) + 360, // 5 minutes
messages: [
{
address: wallet,
amount: (amount * 1000000000).toString(), // Convert to nanotons
}
]
};
// Send transaction
const result = await tonConnectUI.sendTransaction(transaction);
console.log('Transaction result:', result);
// Verify payment with backend
const verifyResponse = await fetch(`${BOT_API_URL}/api/ton/verify_payment`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: userId,
tx_hash: result.boc,
amount: amount
})
});
const verifyData = await verifyResponse.json();
if (verifyResponse.ok && verifyData.success) {
alert(`✅ Payment successful! You can now send ${verifyData.eggs_added} more eggs.`);
// Reload payment status
checkPaymentStatus();
} else {
alert(`❌ Payment verification failed: ${verifyData.error || 'Unknown error'}`);
}
} catch (error) {
console.error('Error processing payment:', error);
alert(`❌ Payment failed: ${error.message}`);
}
}
// Update UI based on wallet connection
function updateUI() {
checkPaymentStatus();
}
// Navigation
let currentPage = 'home-page';
function showPage(pageId) {
// Hide all pages
document.querySelectorAll('.page').forEach(page => {
page.classList.remove('active');
});
// Show selected page
const page = document.getElementById(pageId);
if (page) {
page.classList.add('active');
currentPage = pageId;
}
// Update nav items
document.querySelectorAll('.nav-item').forEach(item => {
item.classList.remove('active');
if (item.dataset.page === pageId) {
item.classList.add('active');
}
});
// Update Telegram back button
if (pageId === 'home-page') {
tg.BackButton.hide();
} else {
tg.BackButton.show();
}
// Update stats on stats page
if (pageId === 'stats-page') {
updateStatsPage();
}
}
function setupNavigation() {
document.querySelectorAll('.nav-item').forEach(item => {
item.addEventListener('click', () => {
const pageId = item.dataset.page;
showPage(pageId);
});
});
}
// Update stats on stats page
function updateStatsPage() {
const hatchedCountStats = document.getElementById('hatched-count-stats');
const myEggsCountStats = document.getElementById('my-eggs-count-stats');
const hatchedCount = document.getElementById('hatched-count');
const myEggsCount = document.getElementById('my-eggs-count');
if (hatchedCountStats && hatchedCount) {
hatchedCountStats.textContent = hatchedCount.textContent;
}
if (myEggsCountStats && myEggsCount) {
myEggsCountStats.textContent = myEggsCount.textContent;
}
}
// Load statistics
async function loadStats() {
const hatchedCountEl = document.getElementById('hatched-count');
const myEggsCountEl = document.getElementById('my-eggs-count');
const userId = getUserID();
if (!userId) {
console.warn('No user ID found');
if (hatchedCountEl) hatchedCountEl.textContent = '0';
if (myEggsCountEl) myEggsCountEl.textContent = '0';
updateStatsPage();
return;
}
// Show loading
if (hatchedCountEl) hatchedCountEl.innerHTML = '<span class="loading"></span>';
if (myEggsCountEl) myEggsCountEl.innerHTML = '<span class="loading"></span>';
try {
console.log(`Fetching stats from: ${API_URL}?user_id=${userId}`);
const response = await fetch(`${API_URL}?user_id=${userId}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
console.log('Response status:', response.status);
if (response.ok) {
const data = await response.json();
console.log('Stats data:', data);
const hatchedValue = data.hatched_by_me || 0;
const myEggsValue = data.my_eggs_hatched || 0;
if (hatchedCountEl) {
animateValue(hatchedCountEl, 0, hatchedValue, 1000);
}
if (myEggsCountEl) {
animateValue(myEggsCountEl, 0, myEggsValue, 1000);
}
// Update stats page after animation
setTimeout(() => {
updateStatsPage();
}, 1000);
} else {
const errorText = await response.text();
console.error('API error:', response.status, errorText);
throw new Error(`Failed to load stats: ${response.status}`);
}
} catch (error) {
console.error('Error loading stats:', error);
if (hatchedCountEl) hatchedCountEl.textContent = '0';
if (myEggsCountEl) myEggsCountEl.textContent = '0';
updateStatsPage();
}
}
// Animate number counting
function animateValue(element, start, end, duration) {
let startTimestamp = null;
const step = (timestamp) => {
if (!startTimestamp) startTimestamp = timestamp;
const progress = Math.min((timestamp - startTimestamp) / duration, 1);
const easeOutQuart = 1 - Math.pow(1 - progress, 4);
const current = Math.floor(easeOutQuart * (end - start) + start);
element.textContent = current.toLocaleString();
if (progress < 1) {
window.requestAnimationFrame(step);
}
};
window.requestAnimationFrame(step);
}
// Handle Send Egg button
function setupSendEggButton() {
const sendEggBtn = document.getElementById('send-egg-btn');
if (sendEggBtn) {
sendEggBtn.addEventListener('click', () => {
// Open inline mode in Telegram
tg.openLink('https://t.me/tohatchbot?start=egg', { try_instant_view: false });
});
}
}
// Setup payment button
function setupPaymentButton() {
const payBtn = document.getElementById('pay-ton-btn');
if (payBtn) {
payBtn.addEventListener('click', handleTONPayment);
}
}
// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
// Setup navigation
setupNavigation();
// Show home page by default
showPage('home-page');
loadStats();
setupSendEggButton();
setupPaymentButton();
// Initialize TON Connect
initTONConnect();
// Check payment status after a delay to ensure TON Connect is initialized
setTimeout(() => {
checkPaymentStatus();
}, 1000);
// Handle back button
tg.BackButton.onClick(() => {
if (currentPage !== 'home-page') {
showPage('home-page');
tg.BackButton.hide();
} else {
tg.close();
}
});
// Show back button only if not on home page
if (currentPage !== 'home-page') {
tg.BackButton.show();
}
// Check if we need to show payment UI from URL
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('pay') === 'true') {
// Show payment section
setTimeout(() => {
checkPaymentStatus();
}, 1500);
}
});