-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
462 lines (406 loc) · 19.1 KB
/
script.js
File metadata and controls
462 lines (406 loc) · 19.1 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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// CONTRACT DETAILS & CONSTANTS
const CONTRACT_ADDRESS = "0xE61FEb2c3278A6094571ce12177767221cA4b661";
const TOKENS = {
usdt: {
address: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F",
decimals: 6,
symbol: "USDT"
},
usdc: {
address: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
decimals: 6,
symbol: "USDC (Bridget)"
},
dai: {
address: "0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063",
decimals: 18,
symbol: "DAI"
}
};
const ABI = [
"function donate(address token, address[] recipients, uint256[] amounts) external",
"function donatePreset(string calldata name, address token, uint256 amount) external",
"function getPreset(string calldata name) external view returns (address[] memory recipients, uint256[] memory percentages)",
"function getWhitelistedRecipients() external view returns (address[] memory)",
"function totalDonatedOverallInUsdt() external view returns (uint256)",
"event Donation(address indexed donor, address indexed token, address indexed recipient, uint256 amount)"
];
const ERC20_ABI = [
"function approve(address spender, uint256 amount) public returns (bool)"
];
const ORGS = [
{ key: "thisproject", address: "0xc0F467567570AADa929fFA115E65bB39066e3E42", link: "https://nrt314.github.io/donate-site" },
{ key: "ovdinfo", address: "0x421896bb0Dcf271a294bC7019014EE90503656Fd", link: "https://ovd.info" },
{ key: "mediazona", address: "0xE86D7D922DeF8a8FEB21f1702C9AaEEDBec32DDC", link: "https://zona.media" },
{ key: "zhuk", address: "0x1913A02BB3836AF224aEF136461F43189A0cEcd0", link: "https://www.zhuk.world/" },
{ key: "breakfastshow", address: "0xdB4BB555a15bC8bB3b07E57452a8E6E24b358e7F", link: "https://www.youtube.com/@The_Breakfast_Show" },
{ key: "kovcheg", address: "0xBf178F99b8790db1BD2194D80c3a268AE4AcE804", link: "https://kovcheg.live" },
{ key: "findexit", address: "0xADb524cE8c2009e727f6dF4b6a443D455c700244", link: "https://www.youtube.com/@ishemvihod" },
{ key: "gulagunet", address: "0x6051F40d4eF5d5E5BC2B6F4155AcCF57Be6B8F58", link: "https://www.youtube.com/channel/UCbanC4P0NmnzNYXQIrjvoSA" },
{ key: "meduza", address: "0x00B9d7Fe4a2d3aCdd4102Cfb55b98d193B94C0fa", link: "https://meduza.io/" },
{ key: "cit", address: "0xfBcc8904ce75fF90CC741DA80703202faf5b2FcF", link: "https://www.youtube.com/@CITonWar" },
{ key: "importantstories", address: "0x5433CE0E05D117C54f814cc6697244eA0b902DBF", link: "https://istories.media" },
{ key: "fbk", address: "0x314aC71aEB2feC4D60Cc50Eb46e64980a27F2680", link: "https://fbk.info" },
{ key: "iditelesom", address: "0x387C5300586336d145A87C245DD30f9724C6eC01", link: "https://iditelesom.org/ru" },
{ key: "memorial", address: "0x0a4aB5D641f63cd7a2d44d0a643424f5d0df376b", link: "https://memopzk.org/" },
{ key: "insider", address: "0xad8221D4A4feb023156b9E09917Baa4ff81A65F8", link: "https://theins.ru" },
{ key: "rain", address: "0x552dAfED221689e44676477881B6947074a5C342", link: "https://tvrain.tv/" }
];
const PRESET_NAME = "equal";
const presetRecipients = ORGS.map(org => org.address);
// DOM ELEMENTS
const ELEMENTS = {
donationTable: document.getElementById("donationTable"),
totalAmountEl: document.getElementById("totalAmount"),
nrtAmountEl: document.getElementById("nrtAmount"),
statusEl: document.getElementById("status"),
tokenSymbolHeader: document.getElementById("tokenSymbolHeader"),
tokenSymbolAmount: document.getElementById("tokenSymbolAmount"),
presetTokenSymbolEl: document.getElementById("presetTokenSymbol"),
presetAmountInputEl: document.getElementById("presetAmountInput"),
connectBrowserBtn: document.getElementById("connectBrowserBtn"),
connectMobileBtn: document.getElementById("connectMobileBtn"),
connectButtons: document.getElementById("connectButtons"),
disconnectBtn: document.getElementById("disconnectBtn"),
walletAddressEl: document.getElementById("walletAddress"),
presetDonationEl: document.getElementById("presetDonation"),
customDonationEl: document.getElementById("customDonation"),
presetDescriptionEl: document.getElementById("presetDescription"),
aboutContentEl: document.getElementById("about-content"),
plansContentEl: document.getElementById("plans-content"),
faqContentEl: document.getElementById("faq-content"),
contactForm: document.getElementById("contactForm"),
contactStatus: document.getElementById("contactStatus"),
langEnBtn: document.getElementById("lang-en"),
langRuBtn: document.getElementById("lang-ru"),
tokenRadios: document.querySelectorAll('input[name="token"]'),
donationTypeRadios: document.querySelectorAll('input[name="donation-type"]'),
howToGetNrtContentEl: document.getElementById("how-to-get-nrt-content"),
howContractWorksContentEl: document.getElementById("how-contract-works-content"),
discussionsContentEl: document.getElementById("discussions-content"),
howToBuyCryptoContentEl: document.getElementById("how-to-buy-crypto-content")
};
// STATE
let translations = {};
let currentLang = 'en';
let provider, signer;
const inputMap = new Map();
let selectedToken = TOKENS.usdt;
let donationType = 'custom';
// --- Polygon Network Logic ---
const POLYGON_CHAIN_ID = '0x89'; // 137 в шестнадцатеричной системе
async function switchToPolygon() {
if (!window.ethereum) throw new Error("Кошелек не найден");
try {
// Пытаемся переключить сеть
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: POLYGON_CHAIN_ID }],
});
console.log("Успешно переключено на Polygon");
} catch (switchError) {
// Ошибка 4902 означает, что сеть не добавлена в MetaMask
if (switchError.code === 4902) {
console.log("Сеть Polygon не найдена в кошельке, попытка добавить...");
try {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: POLYGON_CHAIN_ID,
chainName: 'Polygon Mainnet',
rpcUrls: ['https://polygon-rpc.com/'],
nativeCurrency: {
name: 'MATIC',
symbol: 'MATIC',
decimals: 18,
},
blockExplorerUrls: ['https://polygonscan.com/'],
},
],
});
} catch (addError) {
console.error("Не удалось добавить сеть Polygon:", addError);
throw addError; // Пробрасываем ошибку дальше
}
} else {
console.error("Не удалось переключить сеть:", switchError);
throw switchError; // Пробрасываем ошибку дальше
}
}
}
// --- General Functions ---
async function fetchTranslations() {
try {
const response = await fetch('translations.json');
translations = await response.json();
setLanguage(currentLang);
} catch (error) {
console.error("Error fetching translations:", error);
}
}
function showModal(message) {
document.getElementById("modalMessage").innerHTML = message;
document.getElementById("myModal").style.display = "block";
}
function closeModal() {
document.getElementById("myModal").style.display = "none";
}
window.onclick = function(event) {
if (event.target === document.getElementById("myModal")) {
closeModal();
}
};
function updateContent() {
const texts = translations[currentLang];
if (!texts) return;
const langKeys = document.querySelectorAll('[data-lang-key]');
langKeys.forEach(element => {
const key = element.getAttribute('data-lang-key');
if (texts[key] !== undefined) {
element.innerHTML = texts[key];
}
});
if (ELEMENTS.aboutContentEl) {
ELEMENTS.aboutContentEl.innerHTML = `
<h3 class="font-semibold text-xl mb-2">${texts.about_section_idea_title}</h3>
<p class="mb-4">${texts.about_section_idea_text}</p>
<h3 class="font-semibold text-xl mb-2">${texts.about_section_why_polygon_title}</h3>
<p class="mb-4">${texts.about_section_why_polygon_text}</p>
<h3 class="font-semibold text-xl mb-2">${texts.about_section_what_is_nrt_title}</h3>
<p class="mb-4">${texts.about_section_what_is_nrt_text}</p>
`;
}
if (ELEMENTS.plansContentEl) {
ELEMENTS.plansContentEl.innerHTML = `
<h3 class="font-semibold text-xl mb-2">${texts.plans_section_short_term_title}</h3>
<p class="mb-4">${texts.plans_section_short_term_text}</p>
<h3 class="font-semibold text-xl mb-2">${texts.plans_section_global_title}</h3>
<p class="mb-4">${texts.plans_section_global_text}</p>
`;
}
if (ELEMENTS.faqContentEl && texts.faq_questions) {
ELEMENTS.faqContentEl.innerHTML = texts.faq_questions.map((item) => `
<details class="faq-item bg-gray-50 border border-gray-200 rounded-lg mb-2">
<summary class="font-medium text-gray-700">${item.q}</summary>
<div class="px-4 py-3 text-gray-600">${item.a}</div>
</details>
`).join('');
}
if (ELEMENTS.discussionsContentEl) {
ELEMENTS.discussionsContentEl.innerHTML = texts.discussions_content || '';
}
if (ELEMENTS.howToGetNrtContentEl) {
ELEMENTS.howToGetNrtContentEl.innerHTML = texts.how_to_get_nrt_content || '';
}
if (ELEMENTS.howToBuyCryptoContentEl) {
ELEMENTS.howToBuyCryptoContentEl.innerHTML = texts.how_to_buy_crypto_content || '';
}
const presetRecipientsCount = presetRecipients.length;
ELEMENTS.presetDescriptionEl.textContent = texts.preset_description.replace('{count}', presetRecipientsCount);
}
function setLanguage(lang) {
currentLang = lang;
updateContent();
renderDonationTable();
const contractLink = document.getElementById('contract-link');
if (contractLink) {
const newHref = lang === 'ru' ? 'contract-details-ru.html' : 'contract-details-en.html';
contractLink.setAttribute('href', newHref);
}
ELEMENTS.langEnBtn.classList.toggle('border-blue-600', lang === 'en');
ELEMENTS.langEnBtn.classList.toggle('border-transparent', lang !== 'en');
ELEMENTS.langRuBtn.classList.toggle('border-blue-600', lang === 'ru');
ELEMENTS.langRuBtn.classList.toggle('border-transparent', lang !== 'ru');
recalc();
}
// --- Donation Logic ---
function renderDonationTable() {
ELEMENTS.donationTable.innerHTML = '';
const orgNames = translations[currentLang]?.org_names || {};
ORGS.forEach(({ key, address, link }) => {
const name = orgNames[key] || key;
const row = document.createElement("tr");
row.className = "hover:bg-gray-50 transition-colors duration-200";
row.innerHTML = `<td class="p-3 border border-gray-300"><a href="${link}" target="_blank" class="text-blue-600 hover:underline">${name}</a></td>
<td class="p-3 border border-gray-300 font-mono text-xs hidden md:table-cell"><code>${address}</code></td>
<td class="p-3 border border-gray-300">
<input type="number" min="0" step="0.01" value="0" class="w-full md:w-32 p-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"/>
</td>`;
const input = row.querySelector("input");
input.addEventListener("input", recalc);
inputMap.set(address, input);
ELEMENTS.donationTable.appendChild(row);
});
}
function recalc() {
let totalInTokens = 0;
const tokenSymbol = selectedToken.symbol;
if (donationType === 'preset') {
totalInTokens = parseFloat(ELEMENTS.presetAmountInputEl.value) || 0;
} else {
for (const input of inputMap.values()) {
totalInTokens += parseFloat(input.value) || 0;
}
}
ELEMENTS.presetTokenSymbolEl.textContent = tokenSymbol;
ELEMENTS.tokenSymbolHeader.textContent = tokenSymbol;
ELEMENTS.tokenSymbolAmount.textContent = tokenSymbol;
ELEMENTS.totalAmountEl.textContent = `${totalInTokens.toFixed(2)} ${tokenSymbol}`;
ELEMENTS.nrtAmountEl.textContent = `${totalInTokens.toFixed(2)}`;
}
// --- Wallet & Connection Logic ---
function resetWalletState() {
signer = null;
ELEMENTS.walletAddressEl.innerText = '';
ELEMENTS.connectButtons.classList.remove('hidden');
ELEMENTS.disconnectBtn.classList.add('hidden');
console.log("Wallet connection reset.");
}
function setupWalletListeners() {
if (window.ethereum) {
window.ethereum.on('accountsChanged', (accounts) => {
if (accounts.length === 0) {
console.log('Wallet disconnected.');
resetWalletState();
} else {
console.log('Account changed to:', accounts[0]);
connectWallet();
}
});
window.ethereum.on('chainChanged', () => {
console.log('Chain changed. Reloading page...');
window.location.reload();
});
}
}
async function connectWallet() {
if (!window.ethereum) {
showModal(translations[currentLang].modal_metamask);
return;
}
try {
// Сначала принудительно переключаемся на Polygon
await switchToPolygon();
// Теперь, когда мы в нужной сети, продолжаем подключение
provider = new ethers.BrowserProvider(window.ethereum);
const accounts = await provider.send("eth_requestAccounts", []);
signer = await provider.getSigner();
const address = accounts[0];
ELEMENTS.walletAddressEl.innerText = `Wallet: ${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
ELEMENTS.connectButtons.classList.add('hidden');
ELEMENTS.disconnectBtn.classList.remove('hidden');
setupWalletListeners();
} catch (e) {
// Отображаем осмысленное сообщение об ошибке, если пользователь отклонил переключение/добавление сети
showModal(`${translations[currentLang].modal_error} ${e.message}`);
}
}
// --- Event Listeners ---
ELEMENTS.langEnBtn.addEventListener('click', () => setLanguage('en'));
ELEMENTS.langRuBtn.addEventListener('click', () => setLanguage('ru'));
ELEMENTS.tokenRadios.forEach(radio => {
radio.addEventListener('change', (e) => {
selectedToken = TOKENS[e.target.value];
recalc();
});
});
ELEMENTS.donationTypeRadios.forEach(radio => {
radio.addEventListener('change', (e) => {
donationType = e.target.value;
if (donationType === 'preset') {
ELEMENTS.presetDonationEl.classList.remove('hidden');
ELEMENTS.customDonationEl.classList.add('hidden');
} else {
ELEMENTS.presetDonationEl.classList.add('hidden');
ELEMENTS.customDonationEl.classList.remove('hidden');
}
recalc();
});
});
ELEMENTS.presetAmountInputEl.addEventListener('input', recalc);
ELEMENTS.connectBrowserBtn.onclick = connectWallet;
ELEMENTS.connectMobileBtn.onclick = () => showModal(translations[currentLang].modal_wip);
ELEMENTS.disconnectBtn.onclick = resetWalletState;
document.getElementById("donateBtn").onclick = async () => {
if (!signer) {
showModal(translations[currentLang].modal_connect);
return;
}
try {
// 1. Проверка сети ПЕРЕД транзакцией
const network = await provider.getNetwork();
if (network.chainId !== 137n) { // ВАЖНО: ethers.js v6 возвращает chainId как BigInt (137n)
// Желательно добавить перевод для этого сообщения в ваш translations.json
showModal(translations[currentLang].modal_switch_to_polygon || "Please switch to Polygon network to donate.");
return;
}
let total = 0;
if (donationType === 'preset') {
total = parseFloat(ELEMENTS.presetAmountInputEl.value) || 0;
} else {
for (const input of inputMap.values()) {
total += parseFloat(input.value) || 0;
}
}
if (total <= 0) {
showModal(translations[currentLang].modal_no_amount);
return;
}
ELEMENTS.statusEl.textContent = '';
// 2. Остальная логика транзакции
const tokenContract = new ethers.Contract(selectedToken.address, ERC20_ABI, signer);
const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, signer);
const totalAmount = ethers.parseUnits(total.toString(), selectedToken.decimals);
ELEMENTS.statusEl.textContent = translations[currentLang].status_approve;
const approveTx = await tokenContract.approve(CONTRACT_ADDRESS, totalAmount);
await approveTx.wait();
ELEMENTS.statusEl.textContent = translations[currentLang].status_donate;
let donateTx;
if (donationType === 'preset') {
donateTx = await contract.donatePreset(PRESET_NAME, selectedToken.address, totalAmount);
} else {
let recipients = [];
let amounts = [];
for (const [addr, input] of inputMap.entries()) {
const value = parseFloat(input.value) || 0;
if (value > 0) {
recipients.push(ethers.getAddress(addr));
amounts.push(ethers.parseUnits(value.toString(), selectedToken.decimals));
}
}
if (recipients.length === 0) {
showModal(translations[currentLang].modal_no_amount);
ELEMENTS.statusEl.textContent = '';
return;
}
donateTx = await contract.donate(selectedToken.address, recipients, amounts);
}
await donateTx.wait();
ELEMENTS.statusEl.textContent = translations[currentLang].status_success;
} catch (err) {
console.error(err);
let errorMessage = err.reason || err.message;
ELEMENTS.statusEl.textContent = `${translations[currentLang].status_error} ${errorMessage}`;
}
};
ELEMENTS.contactForm.addEventListener("submit", async function(event) {
event.preventDefault();
const texts = translations[currentLang];
ELEMENTS.contactStatus.textContent = texts.contact_status_sending;
const response = await fetch(this.action, {
method: this.method,
body: new FormData(this),
headers: { 'Accept': 'application/json' }
});
if (response.ok) {
ELEMENTS.contactStatus.textContent = texts.contact_status_success;
ELEMENTS.contactForm.reset();
} else {
ELEMENTS.contactStatus.textContent = texts.contact_status_error;
}
});
// --- Initialization ---
window.onload = function() {
fetchTranslations();
};