-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathamm_interface.html
More file actions
505 lines (421 loc) · 26.3 KB
/
amm_interface.html
File metadata and controls
505 lines (421 loc) · 26.3 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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AMM 兑换与流动性界面 - 最终稳定版 (v4)</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/6.7.0/ethers.umd.min.js" type="application/javascript"></script>
<style>
/* CSS 样式,保持简洁和可读性 */
body {
font-family: 'Arial', sans-serif;
background-color: #f7f9fc;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background: #fff;
padding: 30px;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #007bff;
margin-bottom: 25px;
}
.status {
padding: 10px;
margin-bottom: 15px;
border-radius: 6px;
background-color: #e9f5ff;
color: #0056b3;
border: 1px solid #cce5ff;
}
.section {
padding: 15px;
border: 1px solid #e0e0e0;
border-radius: 8px;
margin-bottom: 20px;
background-color: #fcfcfc;
}
input[type="number"], .input-group button {
padding: 10px;
margin-right: 10px;
border-radius: 4px;
border: 1px solid #ccc;
width: 150px;
box-sizing: border-box;
margin-bottom: 10px;
}
button {
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.2s;
margin-top: 5px;
}
.btn-connect { background-color: #28a745; color: white; }
.btn-connect:hover { background-color: #218838; }
.btn-approve { background-color: #ffc107; color: #333; }
.btn-approve:hover { background-color: #e0a800; }
.btn-primary { background-color: #007bff; color: white; }
.btn-primary:hover { background-color: #0056b3; }
.btn-direction { background-color: #f8f9fa; border: 1px solid #ccc; color: #333; margin: 0 5px 10px 0; }
.btn-active-direction { background-color: #007bff; color: white; border: 1px solid #007bff; margin: 0 5px 10px 0; }
.reserves p { margin: 5px 0; font-size: 1.1em; }
</style>
</head>
<body>
<div class="container">
<h2>🚀 自动做市商 (AMM) 界面</h2>
<div id="status" class="status">请连接您的钱包...</div>
<div id="wallet-info" style="text-align: center; margin-bottom: 20px;">
<button id="connect-wallet" class="btn-connect">连接钱包</button>
</div>
<hr>
<div class="section reserves">
<h3>🏦 池子状态</h3>
<p>Token A 储备: <strong id="reserve-a">0</strong></p>
<p>Token B 储备: <strong id="reserve-b">0</strong></p>
<p>您的 LP 代币余额: <strong id="lp-balance">0</strong></p>
</div>
<hr>
<div class="section">
<h3>🔒 步骤 1: 授权代币</h3>
<button id="approve-a" class="btn-approve" disabled>授权 Token A</button>
<button id="approve-b" class="btn-approve" disabled>授权 Token B</button>
<p style="font-size: 0.8em; color: gray; margin-top: 10px;">必须授权 AMM 合约才能使用您的代币。</p>
</div>
<hr>
<div class="section">
<h3>➕ 步骤 2: 添加流动性</h3>
<input type="number" id="input-a-add" placeholder="Token A 数量">
<input type="number" id="input-b-add" placeholder="Token B 数量">
<button id="add-liquidity" class="btn-primary" disabled>添加流动性</button>
</div>
<hr>
<div class="section">
<h3>➖ 步骤 3: 移除流动性</h3>
<input type="number" id="input-lp-remove" placeholder="LP Token 数量">
<button id="remove-liquidity" class="btn-primary" disabled>移除流动性</button>
</div>
<hr>
<div class="section">
<h3>🔄 步骤 4: 兑换代币</h3>
<div style="margin-bottom: 10px;">
<button id="swap-a-to-b" class="btn-active-direction">A → B</button>
<button id="swap-b-to-a" class="btn-direction">B → A</button>
</div>
<input type="number" id="input-swap" placeholder="输入兑换数量">
<p style="font-size: 0.9em; color: #6c757d;">预计收到的数量将根据滑点容忍度计算。</p>
<button id="execute-swap" class="btn-primary" disabled>执行兑换 (A → B)</button>
</div>
</div>
<script>
const { ethers } = window;
// ==========================================================
// 1. 您的配置信息
// ==========================================================
// 🚨 关键更新:AMM 合约地址
const AMM_ADDRESS = "0x8181A6147f1649DC771c716290fA0D9E42640559";
// Token A 地址 (保持不变)
const TOKEN_A_ADDRESS = "0x113ecc7d890ced42a4822877370eff5db5fc6b06";
// Token B 新地址
const TOKEN_B_ADDRESS = "0xa6e27e0808ab5c5874793e08d2084ffd72489290";
const DECIMALS = 18;
const MAX_UINT256 = ethers ? ethers.MaxUint256 : (2n**256n - 1n);
const SLIPPAGE_TOLERANCE = 0.995;
// 简化 ERC20 ABI
const ERC20_ABI = [
"function approve(address spender, uint256 value) external returns (bool)",
"function allowance(address owner, address spender) external view returns (uint256)",
"function balanceOf(address account) external view returns (uint256)",
"function decimals() external view returns (uint8)",
];
// 您的 AMM 合约的完整 JSON ABI (保持不变)
const AMM_ABI = [
{"inputs": [{"internalType": "uint256", "name": "amountA", "type": "uint256"}, {"internalType": "uint256", "name": "amountB", "type": "uint256"}], "name": "addLiquidity", "outputs": [], "stateMutability": "nonpayable", "type": "function"},
{"inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function"},
{"inputs": [{"internalType": "address", "name": "_tokenA", "type": "address"}, {"internalType": "address", "name": "_tokenB", "type": "address"}, {"internalType": "string", "name": "_name", "type": "string"}, {"internalType": "string", "name": "_symbol", "type": "string"}], "stateMutability": "nonpayable", "type": "constructor"},
{"inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "allowance", "type": "uint256"}, {"internalType": "uint256", "name": "needed", "type": "uint256"}], "name": "ERC20InsufficientAllowance", "type": "error"},
{"inputs": [{"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "uint256", "name": "balance", "type": "uint256"}, {"internalType": "uint256", "name": "needed", "type": "uint256"}], "name": "ERC20InsufficientBalance", "type": "error"},
{"inputs": [{"internalType": "address", "name": "approver", "type": "address"}], "name": "ERC20InvalidApprover", "type": "error"},
{"inputs": [{"internalType": "address", "name": "receiver", "type": "address"}], "name": "ERC20InvalidReceiver", "type": "error"},
{"inputs": [{"internalType": "address", "name": "sender", "type": "address"}], "name": "ERC20InvalidSender", "type": "error"},
{"inputs": [{"internalType": "address", "name": "spender", "type": "address"}], "name": "ERC20InvalidSpender", "type": "error"},
{"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "owner", "type": "address"}, {"indexed": true, "internalType": "address", "name": "spender", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "value", "type": "uint256"}], "name": "Approval", "type": "event"},
{"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "provider", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "amountA", "type": "uint256"}, {"indexed": false, "internalType": "uint256", "name": "amountB", "type": "uint256"}, {"indexed": false, "internalType": "uint256", "name": "liquidity", "type": "uint256"}], "name": "LiquidityAdded", "type": "event"},
{"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "provider", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "amountA", "type": "uint256"}, {"indexed": false, "internalType": "uint256", "name": "amountB", "type": "uint256"}, {"indexed": false, "internalType": "uint256", "name": "liquidity", "type": "uint256"}], "name": "LiquidityRemoved", "type": "event"},
{"inputs": [{"internalType": "uint256", "name": "liquidityToRemove", "type": "uint256"}], "name": "removeLiquidity", "outputs": [{"internalType": "uint256", "name": "amountAOut", "type": "uint256"}, {"internalType": "uint256", "name": "amountBOut", "type": "uint256"}], "stateMutability": "nonpayable", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "amountAIn", "type": "uint256"}, {"internalType": "uint256", "name": "minBOut", "type": "uint256"}], "name": "swapAforB", "outputs": [], "stateMutability": "nonpayable", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "amountBIn", "type": "uint256"}, {"internalType": "uint256", "name": "minAOut", "type": "uint256"}], "name": "swapBforA", "outputs": [], "stateMutability": "nonpayable", "type": "function"},
{"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "trader", "type": "address"}, {"indexed": false, "internalType": "address", "name": "tokenIn", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "amountIn", "type": "uint256"}, {"indexed": false, "internalType": "address", "name": "tokenOut", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "amountOut", "type": "uint256"}], "name": "TokensSwapped", "type": "event"},
{"inputs": [{"internalType": "address", "name": "to", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function"},
{"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "from", "type": "address"}, {"indexed": true, "internalType": "address", "name": "to", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "value", "type": "uint256"}], "name": "Transfer", "type": "event"},
{"inputs": [{"internalType": "address", "name": "from", "type": "address"}, {"internalType": "address", "name": "to", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function"},
{"inputs": [{"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"},
{"inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "getReserves", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "owner", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "reserveA", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "reserveB", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "tokenA", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "tokenB", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"}
];
// ==========================================================
// 状态变量
let provider = null;
let signer = null;
let account = null;
let reserves = { A: 0, B: 0 };
let isAtoB = true;
// DOM 元素引用
const dom = {
status: document.getElementById('status'),
connectButton: document.getElementById('connect-wallet'),
reserveA: document.getElementById('reserve-a'),
reserveB: document.getElementById('reserve-b'),
lpBalance: document.getElementById('lp-balance'),
approveA: document.getElementById('approve-a'),
approveB: document.getElementById('approve-b'),
inputAAdd: document.getElementById('input-a-add'),
inputBAdd: document.getElementById('input-b-add'),
addLiquidityBtn: document.getElementById('add-liquidity'),
inputLPRemove: document.getElementById('input-lp-remove'),
removeLiquidityBtn: document.getElementById('remove-liquidity'),
swapAtoBBtn: document.getElementById('swap-a-to-b'),
swapBtoABtn: document.getElementById('swap-b-to-a'),
inputSwap: document.getElementById('input-swap'),
executeSwapBtn: document.getElementById('execute-swap'),
};
// 辅助函数
function updateStatus(message, isError = false) {
dom.status.textContent = message;
dom.status.style.backgroundColor = isError ? '#ffe9e9' : '#e9f5ff';
dom.status.style.color = isError ? '#cc0000' : '#0056b3';
}
function setButtonsEnabled(enabled) {
dom.approveA.disabled = !enabled;
dom.approveB.disabled = !enabled;
dom.addLiquidityBtn.disabled = !enabled;
dom.removeLiquidityBtn.disabled = !enabled;
dom.executeSwapBtn.disabled = !enabled;
}
function getContracts(useSigner = true) {
if (!provider || !ethers) return {};
const actor = useSigner && signer ? signer : provider;
const ammContract = new ethers.Contract(AMM_ADDRESS, AMM_ABI, actor);
const tokenAContract = new ethers.Contract(TOKEN_A_ADDRESS, ERC20_ABI, actor);
const tokenBContract = new ethers.Contract(TOKEN_B_ADDRESS, ERC20_ABI, actor);
return { ammContract, tokenAContract, tokenBContract };
}
// ==========================================================
// 2. 连接钱包 (兼容版)
// ==========================================================
async function connectWallet() {
if (typeof ethers === 'undefined' || !window.ethereum) {
updateStatus("Ethers.js 未加载或钱包扩展程序未安装。", true);
return;
}
try {
updateStatus("连接中,请在钱包中确认授权...");
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
if (accounts && accounts.length > 0) {
provider = new ethers.BrowserProvider(window.ethereum);
signer = await provider.getSigner();
account = accounts[0];
setButtonsEnabled(true);
dom.connectButton.textContent = `✅ 已连接: ${account.substring(0, 6)}...${account.substring(38)}`;
dom.connectButton.disabled = true;
updateStatus(`连接成功! 账户: ${account}`);
window.ethereum.on('accountsChanged', () => window.location.reload());
window.ethereum.on('chainChanged', () => window.location.reload());
fetchPoolData();
} else {
updateStatus("钱包未提供账户信息,连接失败。", true);
}
} catch (error) {
console.error("连接失败:", error);
if (error.code === 4001) {
updateStatus("连接被用户拒绝。", true);
} else {
updateStatus(`连接失败。请检查钱包是否解锁且网络正确。`, true);
}
}
}
// 获取池子状态和 LP 余额
async function fetchPoolData() {
const { ammContract } = getContracts(false);
if (!ammContract) return;
try {
const [reserveA_raw, reserveB_raw] = await ammContract.getReserves();
reserves.A = ethers.formatUnits(reserveA_raw, DECIMALS);
reserves.B = ethers.formatUnits(reserveB_raw, DECIMALS);
dom.reserveA.textContent = reserves.A;
dom.reserveB.textContent = reserves.B;
if (account) {
const lpBalanceRaw = await ammContract.balanceOf(account);
dom.lpBalance.textContent = ethers.formatUnits(lpBalanceRaw, DECIMALS);
}
} catch (error) {
console.error("无法获取池子数据:", error);
if (account) {
updateStatus("无法读取合约数据,请检查网络和合约地址是否正确。", true);
}
}
}
// 授权代币
async function handleApprove(tokenContract, tokenName) {
if (!signer) return;
updateStatus(`正在发送 ${tokenName} 授权交易...`);
try {
// 授权最大金额,避免重复授权
const tx = await tokenContract.approve(AMM_ADDRESS, MAX_UINT256);
await tx.wait();
updateStatus(`${tokenName} 授权成功! Tx Hash: ${tx.hash.substring(0, 10)}...`);
} catch (error) {
console.error(`${tokenName} 授权失败:`, error);
updateStatus(`${tokenName} 授权失败。请确保网络畅通且有 Gas 费用。`, true);
}
}
// ==========================================================
// 3. 修正后的添加流动性函数 (解决数字转换和错误提示问题)
// ==========================================================
async function handleAddLiquidity() {
const { ammContract } = getContracts(true);
const inputA = dom.inputAAdd.value;
const inputB = dom.inputBAdd.value;
const numA = parseFloat(inputA);
const numB = parseFloat(inputB);
if (!ammContract || isNaN(numA) || isNaN(numB) || numA <= 0 || numB <= 0) {
updateStatus("请输入有效的代币数量 (大于零)。", true);
return;
}
updateStatus("正在添加流动性...");
try {
// 🚨 关键修复:确保浮点数转换成精确的字符串,防止出现科学计数法或精度损失
const amountA_str = numA.toFixed(DECIMALS > 20 ? 20 : DECIMALS);
const amountB_str = numB.toFixed(DECIMALS > 20 ? 20 : DECIMALS);
const amountA_wei = ethers.parseUnits(amountA_str, DECIMALS);
const amountB_wei = ethers.parseUnits(amountB_str, DECIMALS);
console.log(`Debug: Token A Wei: ${amountA_wei.toString()}, Token B Wei: ${amountB_wei.toString()}`);
const tx = await ammContract.addLiquidity(amountA_wei, amountB_wei);
await tx.wait();
updateStatus(`流动性添加成功! Tx Hash: ${tx.hash.substring(0, 10)}...`);
fetchPoolData();
} catch (error) {
console.error("添加流动性失败:", error);
let errorMessage = "添加流动性失败。";
if (error.reason) {
errorMessage += `**错误原因: ${error.reason}**`;
} else if (error.message && error.message.includes("missing revert data")) {
// 现在最常见的原因是未给新 AMM 地址授权
errorMessage += "合约回退(无明确数据)。**请检查:1. 是否已为新的 AMM 地址重新授权 Token A/B 2. 钱包中是否有足够的余额。**";
} else {
errorMessage += `请确保已重新授权,并拥有足够的代币余额。详细错误: ${error.message.substring(0, 50)}...`;
}
updateStatus(errorMessage, true);
}
}
// 移除流动性
async function handleRemoveLiquidity() {
const { ammContract } = getContracts(true);
const lpInput = dom.inputLPRemove.value;
const numLP = parseFloat(lpInput);
if (!ammContract || isNaN(numLP) || numLP <= 0) {
updateStatus("请输入要移除的 LP 代币数量。", true);
return;
}
updateStatus("正在移除流动性...");
try {
const lpAmount_str = numLP.toFixed(DECIMALS > 20 ? 20 : DECIMALS);
const lpAmount_wei = ethers.parseUnits(lpAmount_str, DECIMALS);
const tx = await ammContract.removeLiquidity(lpAmount_wei);
await tx.wait();
updateStatus(`流动性移除成功! Tx Hash: ${tx.hash.substring(0, 10)}...`);
fetchPoolData();
} catch (error) {
console.error("移除流动性失败:", error);
updateStatus("移除流动性失败。请确认 LP 代币余额充足。", true);
}
}
// 兑换功能
async function handleSwap() {
const { ammContract } = getContracts(true);
const amountIn = dom.inputSwap.value;
const numIn = parseFloat(amountIn);
if (!ammContract || isNaN(numIn) || numIn <= 0) {
updateStatus("请输入有效的兑换数量。", true);
return;
}
updateStatus("正在计算最小输出量...");
const amountIn_str = numIn.toFixed(DECIMALS > 20 ? 20 : DECIMALS);
const amountIn_wei = ethers.parseUnits(amountIn_str, DECIMALS);
if (reserves.A === 0 || reserves.B === 0) {
updateStatus("池子储备金为零,无法进行兑换。", true);
return;
}
const reserveA_raw = ethers.parseUnits(reserves.A.toString(), DECIMALS);
const reserveB_raw = ethers.parseUnits(reserves.B.toString(), DECIMALS);
const reserveIn = isAtoB ? reserveA_raw : reserveB_raw;
const reserveOut = isAtoB ? reserveB_raw : reserveA_raw;
const FEE_NUMERATOR = 997n;
const FEE_DENOMINATOR = 1000n;
const amountIn_withFee = amountIn_wei * FEE_NUMERATOR / FEE_DENOMINATOR;
const numerator = reserveOut * amountIn_withFee;
const denominator = reserveIn + amountIn_withFee;
const amountOut_wei = numerator / denominator;
const minOut_wei = amountOut_wei * BigInt(Math.floor(SLIPPAGE_TOLERANCE * 10000)) / 10000n;
updateStatus("正在发送兑换交易...");
try {
let tx;
if (isAtoB) {
tx = await ammContract.swapAforB(amountIn_wei, minOut_wei);
} else {
tx = await ammContract.swapBforA(amountIn_wei, minOut_wei);
}
await tx.wait();
updateStatus(`兑换成功! 收到约 ${ethers.formatUnits(amountOut_wei, DECIMALS)} 个 Token ${isAtoB ? 'B' : 'A'}. Tx Hash: ${tx.hash.substring(0, 10)}...`);
fetchPoolData();
} catch (error) {
console.error("兑换失败:", error);
updateStatus("兑换失败。可能原因:滑点过大、余额不足、未授权。", true);
}
}
// 4. 事件监听器
dom.connectButton.addEventListener('click', connectWallet);
// 确保授权是针对新的AMM合约地址
dom.approveA.addEventListener('click', () => handleApprove(getContracts(true).tokenAContract, "Token A"));
dom.approveB.addEventListener('click', () => handleApprove(getContracts(true).tokenBContract, "Token B"));
dom.addLiquidityBtn.addEventListener('click', handleAddLiquidity);
dom.removeLiquidityBtn.addEventListener('click', handleRemoveLiquidity);
dom.executeSwapBtn.addEventListener('click', handleSwap);
// 兑换方向切换
dom.swapAtoBBtn.addEventListener('click', () => {
isAtoB = true;
dom.swapAtoBBtn.className = 'btn-active-direction';
dom.swapBtoABtn.className = 'btn-direction';
dom.executeSwapBtn.textContent = '执行兑换 (A → B)';
dom.inputSwap.placeholder = '输入 Token A 数量';
});
dom.swapBtoABtn.addEventListener('click', () => {
isAtoB = false;
dom.swapAtoBBtn.className = 'btn-direction';
dom.swapBtoABtn.className = 'btn-active-direction';
dom.executeSwapBtn.textContent = '执行兑换 (B → A)';
dom.inputSwap.placeholder = '输入 Token B 数量';
});
// 初始化时禁用所有功能按钮
document.addEventListener('DOMContentLoaded', () => {
setButtonsEnabled(false);
});
</script>
</body>
</html>