From ee6224e7075d5a5370abdf068a83a912d05897db Mon Sep 17 00:00:00 2001 From: Kurdistan Tech Ministry Date: Sun, 2 Nov 2025 23:49:58 +0300 Subject: [PATCH] =?UTF-8?q?docs:=20Pel=C3=AAn=20p=C3=AA=C5=9Fkeftin=C3=AA?= =?UTF-8?q?=20=C3=BB=20am=C3=BBr=C3=AAn=20testing=20DEX=20z=C3=AAde=20bike?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - README_DEX_IMPROVEMENTS.md: Belgekirin û rave kirinên DEX - check-pool.mjs: Amûra kontrolkirina rewşa pool - create-beta-pool.mjs: Script ji bo çêkirina pool li beta testnet - create-beta-pool.js: Versiyona JavaScript ya scripta çêkirina pool Ev pel ji bo pêşkeftin û testing in. 🤖 Bi [Claude Code](https://claude.com/claude-code) re hate çêkirin Co-Authored-By: Claude --- README_DEX_IMPROVEMENTS.md | 436 +++++++++++++++++++++++++++++++++++++ check-pool.mjs | 175 +++++++++++++++ create-beta-pool.js | 57 +++++ create-beta-pool.mjs | 91 ++++++++ 4 files changed, 759 insertions(+) create mode 100644 README_DEX_IMPROVEMENTS.md create mode 100644 check-pool.mjs create mode 100644 create-beta-pool.js create mode 100644 create-beta-pool.mjs diff --git a/README_DEX_IMPROVEMENTS.md b/README_DEX_IMPROVEMENTS.md new file mode 100644 index 00000000..19ae2025 --- /dev/null +++ b/README_DEX_IMPROVEMENTS.md @@ -0,0 +1,436 @@ +# DEX System Improvements - User Guide + +## Overview + +This document provides a comprehensive guide to the newly implemented DEX improvements for PezkuwiChain beta testnet. + +--- + +## 🆕 What's New + +### 1. Pool Monitoring Dashboard ✨ +- Real-time pool metrics +- LP position tracking +- Impermanent loss calculator +- APR estimations + +### 2. Arbitrage Bot 🤖 +- Automated price monitoring +- Smart arbitrage execution +- Pool balance maintenance + +### 3. Enhanced Swap Interface 📈 +- Price impact visualization +- Slippage tolerance controls +- Minimum received calculations + +--- + +## 📊 Pool Dashboard + +### Access +Navigate to: **http://localhost:5173/pool** (after login) + +### Features + +#### Canlı Metrikler (Live Metrics) +``` +┌─────────────────────────────────────────┐ +│ Total Liquidity │ Current Price │ +│ $200,000 │ 1 HEZ = 5.0000 PEZ │ +├─────────────────────────────────────────┤ +│ Estimated APR │ Constant (k) │ +│ 109.50% │ 50.0B │ +└─────────────────────────────────────────┘ +``` + +#### Pool Reserves Tab +- View wHEZ reserve +- View PEZ reserve +- See AMM formula: x × y = k + +#### Your Position Tab (LP'ler için) +- LP token balance +- Pool share percentage +- Token values +- Estimated earnings (daily/monthly/yearly) + +#### Impermanent Loss Calculator +Calculate potential IL at different price changes: +- +10%: -0.05% loss +- +25%: -0.62% loss +- +50%: -2.02% loss +- +100%: -5.72% loss +- +200%: -13.40% loss + +--- + +## 🔄 Token Swap Improvements + +### Price Impact Display + +Swap interface now shows: +- **Green** (<1%): Excellent swap +- **Yellow** (1-5%): Good swap +- **Red** (>5%): High impact warning + +### Slippage Tolerance + +Default: **0.5%** + +Customize: 0.1% | 0.5% | 1% | Custom + +**Recommendation:** +- Normal: 0.5-1% +- Volatile markets: 2-5% +- Large swaps: 5-10% + +### Minimum Received + +System automatically calculates minimum tokens you'll receive after slippage: + +``` +Input: 1000 HEZ +Expected: 4850.62 PEZ +Min Received (0.5% slip): 4826.37 PEZ +``` + +--- + +## 🤖 Arbitrage Bot Usage + +### Purpose +Maintains pool price balance by executing arbitrage trades when price deviates from reference. + +### Installation + +```bash +cd /home/mamostehp/Pezkuwi-SDK + +# Ensure substrate-interface is installed +pip3 install substrate-interface --break-system-packages +``` + +### Configuration + +Edit `/home/mamostehp/Pezkuwi-SDK/scripts/arbitrage_bot.py`: + +```python +CONFIG = { + 'ws_url': 'ws://127.0.0.1:9944', # Testnet endpoint + 'reference_price': 5.0, # Target: 1 HEZ = 5 PEZ + 'min_profit_percent': 2.0, # Min 2% deviation to trade + 'max_swap_amount_hez': 5000, # Max 5K HEZ per trade + 'check_interval': 30, # Check every 30 seconds + 'slippage_tolerance': 0.05, # 5% slippage +} +``` + +### Running the Bot + +**Foreground (for testing):** +```bash +python3 ./scripts/arbitrage_bot.py +``` + +**Background (production):** +```bash +nohup python3 ./scripts/arbitrage_bot.py > /tmp/arb-bot.log 2>&1 & + +# Monitor logs +tail -f /tmp/arb-bot.log +``` + +### Bot Output Example + +``` +====================================================================== + 🤖 Arbitrage Bot Started +====================================================================== + +⚙️ Configuration: + Reference Price: 1 HEZ = 5.0 PEZ + Min Profit: 2.0% + Max Swap: 5000 HEZ + Check Interval: 30s + +────────────────────────────────────────────────────────────────────── +🔍 Check #1 - 2025-11-02 20:30:15 +────────────────────────────────────────────────────────────────────── +📊 Pool Price: 1 HEZ = 5.1234 PEZ +📊 Reference: 1 HEZ = 5.0000 PEZ +📊 Deviation: +2.47% + +💰 HEZ overpriced by 2.47% → Sell HEZ for PEZ + +💡 Arbitrage opportunity detected! + Expected profit: 2.47% + +🔄 Executing arbitrage: HEZ_TO_PEZ + Amount: 5000.00 tokens + Step 1: Wrapping HEZ to wHEZ... + Step 2: Swapping wHEZ to PEZ... +✅ Swap successful! Block: 0x1234... + +✨ Arbitrage executed successfully! + Total trades: 1 + +💤 Sleeping for 30 seconds... +``` + +### Bot Commands + +**Check if running:** +```bash +ps aux | grep arbitrage_bot +``` + +**Stop bot:** +```bash +pkill -f arbitrage_bot.py +``` + +**View recent activity:** +```bash +tail -50 /tmp/arb-bot.log +``` + +--- + +## 📈 Liquidity Mining (Future) + +### Timeline +6 weeks implementation (as per LIQUIDITY_MINING_PLAN.md) + +### Expected Features +- Stake LP tokens to earn HEZ rewards +- 10 HEZ/block emission (~5M HEZ/year) +- Target APR: 50-150% +- Auto-compound options +- Governance participation + +### How to Prepare +1. Add liquidity to wHEZ/PEZ pool +2. Hold LP tokens in wallet +3. Wait for liquidity mining launch announcement + +--- + +## 🔐 Security Best Practices + +### For Users +1. **Always check price impact** before large swaps +2. **Set appropriate slippage** (don't use 50% unless necessary) +3. **Verify transaction details** in confirmation dialog +4. **Start with small amounts** when testing + +### For LP Providers +1. **Understand impermanent loss** before adding liquidity +2. **Monitor pool metrics** via dashboard +3. **Calculate expected APR** vs IL risk +4. **Diversify positions** across pools (when available) + +### For Bot Operators +1. **Use dedicated wallet** for bot (not main funds) +2. **Monitor bot logs** regularly +3. **Set reasonable limits** (max_swap_amount) +4. **Test on testnet** before mainnet + +--- + +## 🎯 Recommended Safe Swap Limits + +Based on current pool liquidity (100K wHEZ + 500K PEZ): + +| Swap Amount | Price Impact | Risk Level | Recommendation | +|-------------|--------------|------------|----------------| +| 0 - 1,000 HEZ | <1% | ✅ Low | Safe for all users | +| 1,000 - 5,000 HEZ | 1-5% | ⚠️ Medium | Experienced users | +| 5,000 - 11,500 HEZ | 5-10% | ⚠️ High | Split into smaller swaps | +| 11,500+ HEZ | >10% | ❌ Very High | Not recommended | + +**Pro Tip:** For swaps >10K HEZ, split into multiple 5K swaps over time. + +--- + +## 📱 Quick Reference + +### URLs + +| Feature | URL | Requires Login | +|---------|-----|----------------| +| Home | http://localhost:5173 | No | +| Swap | http://localhost:5173/wallet (Swap tab) | Yes | +| Pool Dashboard | http://localhost:5173/pool | Yes | +| Wallet | http://localhost:5173/wallet | Yes | + +### Default Network Settings + +``` +Network: PezkuwiChain Beta Testnet +Endpoint: ws://127.0.0.1:9944 +Chain ID: pezkuwichain-beta +Block Time: ~6 seconds +``` + +### Token Info + +| Token | Type | Asset ID | Symbol | +|-------|------|----------|--------| +| HEZ | Native | - | HEZ | +| wHEZ | Wrapped | 0 | wHEZ | +| PEZ | Utility | 1 | PEZ | + +### Pool Info + +| Pool | Assets | Liquidity | LP Fee | +|------|--------|-----------|--------| +| wHEZ/PEZ | 0 & 1 | 100K wHEZ + 500K PEZ | 3% | + +--- + +## 🛠️ Troubleshooting + +### Issue: Pool dashboard shows "No pool data" + +**Solution:** +1. Check beta testnet is running: + ```bash + ps aux | grep pezkuwi + ``` +2. Check pool was initialized: + ```bash + python3 /tmp/init_beta_pools.py + ``` +3. Ensure wallet is connected + +### Issue: Swap fails with "1010 invalid transaction" + +**Solution:** +- This should be fixed now! Swap paths updated to simple arrays. +- If still happens, check slippage tolerance (increase to 1-2%) +- Verify account has sufficient balance + gas + +### Issue: Arbitrage bot not trading + +**Possible Causes:** +1. Price deviation <2% (working as expected) +2. Bot account has insufficient funds +3. Pool liquidity exhausted +4. Network connection issues + +**Check:** +```bash +tail -f /tmp/arb-bot.log # See bot activity +``` + +### Issue: High impermanent loss + +**Understand:** +- IL is inherent to AMMs +- It's "impermanent" - can recover if price returns +- LP fees offset IL over time +- Calculator shows worst-case scenarios + +**Mitigation:** +- Add liquidity when volatility is low +- Hold position long-term for fee accumulation +- Monitor APR vs IL regularly + +--- + +## 💡 Tips & Tricks + +### For Traders +1. **Use limit orders** (when implemented) for better prices +2. **Split large swaps** to reduce price impact +3. **Trade during high liquidity** periods +4. **Monitor arbitrage bot** - trade after it corrects price + +### For LPs +1. **Add liquidity in balanced ratios** (current pool ratio) +2. **Compound rewards** (when liquidity mining live) +3. **Track impermanent loss** via dashboard +4. **Calculate APR including fees** + +### For Developers +1. **Review pool analysis** in `/tmp/pool-analysis.md` +2. **Check liquidity mining plan** in SDK docs +3. **Use pool monitoring** for integration testing +4. **Monitor bot behavior** before mainnet + +--- + +## 📞 Support & Resources + +### Documentation +- **Main README**: `/home/mamostehp/DKSweb/README.md` +- **Pool Analysis**: `/tmp/pool-analysis.md` +- **LM Plan**: `/home/mamostehp/Pezkuwi-SDK/docs/LIQUIDITY_MINING_PLAN.md` + +### Scripts +- **Pool Init**: `/tmp/init_beta_pools.py` +- **Arb Bot**: `/home/mamostehp/Pezkuwi-SDK/scripts/arbitrage_bot.py` +- **Pool Check**: `/tmp/check-pool.mjs` + +### Components +- **PoolDashboard**: `/home/mamostehp/DKSweb/src/components/PoolDashboard.tsx` +- **TokenSwap**: `/home/mamostehp/DKSweb/src/components/TokenSwap.tsx` + +### Getting Help +1. Check this document first +2. Review error messages in console +3. Check bot logs: `tail -f /tmp/arb-bot.log` +4. Review transaction in Polkadot.js Apps + +--- + +## 🚀 What's Next? + +### Short Term (Done ✅) +- [x] Pool monitoring dashboard +- [x] Arbitrage bot +- [x] Frontend improvements +- [x] Documentation + +### Medium Term (1-2 months) +- [ ] Liquidity mining implementation +- [ ] Multiple pool support +- [ ] Advanced charting +- [ ] Transaction history + +### Long Term (3-6 months) +- [ ] Governance integration +- [ ] Cross-chain swaps +- [ ] Limit orders +- [ ] Mobile app + +--- + +## ⚖️ Disclaimer + +**Beta Testnet Warning:** +- This is a **test environment** +- Tokens have **NO real value** +- Use for **testing purposes only** +- Expect **occasional resets** +- **Do not** use on mainnet without thorough testing + +**Financial Advice:** +- This is **NOT financial advice** +- **DYOR** before any transactions +- **Understand risks** of AMM trading +- **Impermanent loss** is real +- **Never invest** more than you can afford to lose + +--- + +## 📄 License + +MIT License - See project root for details + +--- + +**Last Updated:** 2025-11-02 +**Version:** 1.0.0-beta +**Network:** PezkuwiChain Beta Testnet diff --git a/check-pool.mjs b/check-pool.mjs new file mode 100644 index 00000000..033d5d58 --- /dev/null +++ b/check-pool.mjs @@ -0,0 +1,175 @@ +import { ApiPromise, WsProvider } from '@polkadot/api'; + +async function main() { + const wsProvider = new WsProvider('ws://127.0.0.1:9944'); + const api = await ApiPromise.create({ provider: wsProvider }); + + console.log('\n' + '='.repeat(70)); + console.log(' Beta Testnet - DEX Pool Status & Analysis'); + console.log('='.repeat(70) + '\n'); + + const ONE_TOKEN = BigInt(10 ** 12); + + // Pool: wHEZ (0) / PEZ (1) + const poolId = [0, 1]; + + console.log('📊 Pool: wHEZ (Asset 0) / PEZ (Asset 1)\n'); + + try { + // Get pool info + const poolInfo = await api.query.assetConversion.pools(poolId); + + if (poolInfo.isSome) { + const lpTokenId = poolInfo.unwrap().toString(); + console.log(`✅ Pool exists - LP Token ID: ${lpTokenId}\n`); + + // Get pool account + const poolAccount = await api.query.assetConversion.poolAccountIds(poolId); + + if (poolAccount.isSome) { + const poolAddr = poolAccount.unwrap().toString(); + console.log(`🏦 Pool Account: ${poolAddr}\n`); + + // Get reserves + const whezBalance = await api.query.assets.account(0, poolAddr); + const pezBalance = await api.query.assets.account(1, poolAddr); + + if (whezBalance.isSome && pezBalance.isSome) { + const whezReserve = BigInt(whezBalance.unwrap().balance.toString()); + const pezReserve = BigInt(pezBalance.unwrap().balance.toString()); + + console.log('💰 Pool Reserves:'); + console.log(` wHEZ: ${(Number(whezReserve) / Number(ONE_TOKEN)).toLocaleString('en-US', { minimumFractionDigits: 2 })} wHEZ`); + console.log(` PEZ: ${(Number(pezReserve) / Number(ONE_TOKEN)).toLocaleString('en-US', { minimumFractionDigits: 2 })} PEZ\n`); + + // Calculate k (constant product) + const k = whezReserve * pezReserve; + console.log('💎 AMM Constant Product:'); + console.log(` k = ${(Number(whezReserve) / Number(ONE_TOKEN)).toFixed(2)} × ${(Number(pezReserve) / Number(ONE_TOKEN)).toFixed(2)} = ${(Number(k) / Number(ONE_TOKEN ** BigInt(2))).toLocaleString('en-US')}\n`); + + // Current price + const priceHezToPez = Number(pezReserve) / Number(whezReserve); + const pricePezToHez = Number(whezReserve) / Number(pezReserve); + + console.log('💱 Current Prices:'); + console.log(` 1 HEZ = ${priceHezToPez.toFixed(4)} PEZ`); + console.log(` 1 PEZ = ${pricePezToHez.toFixed(6)} HEZ\n`); + + // Swap simulation with 3% fee + console.log('🔄 Swap Scenarios (3% LP Fee):'); + console.log('-'.repeat(70) + '\n'); + + function calculateSwap(amountIn, reserveIn, reserveOut) { + // 3% fee: effective amount = amountIn * 0.97 + const amountInWithFee = amountIn * BigInt(97) / BigInt(100); + + // AMM formula: (reserveIn + amountInWithFee) * (reserveOut - amountOut) = k + // amountOut = (amountInWithFee * reserveOut) / (reserveIn + amountInWithFee) + const numerator = amountInWithFee * reserveOut; + const denominator = reserveIn + amountInWithFee; + const amountOut = numerator / denominator; + + // Price impact + const priceImpact = Number(amountOut) / Number(reserveOut) * 100; + + // Effective rate + const effectiveRate = Number(amountOut) / Number(amountIn); + + return { amountOut, priceImpact, effectiveRate }; + } + + // HEZ → PEZ scenarios + console.log('📈 HEZ → PEZ Swaps:\n'); + const hezAmounts = [100, 1000, 5000, 10000, 25000, 50000]; + + for (const amount of hezAmounts) { + const amountIn = BigInt(amount) * ONE_TOKEN; + const { amountOut, priceImpact, effectiveRate } = calculateSwap(amountIn, whezReserve, pezReserve); + + console.log(` ${amount.toLocaleString('en-US').padStart(7)} HEZ → ${(Number(amountOut) / Number(ONE_TOKEN)).toLocaleString('en-US', { minimumFractionDigits: 2 }).padStart(12)} PEZ (Rate: ${effectiveRate.toFixed(4)}, Impact: ${priceImpact.toFixed(2)}%)`); + } + + // PEZ → HEZ scenarios + console.log('\n📉 PEZ → HEZ Swaps:\n'); + const pezAmounts = [500, 5000, 25000, 50000, 100000, 250000]; + + for (const amount of pezAmounts) { + const amountIn = BigInt(amount) * ONE_TOKEN; + const { amountOut, priceImpact, effectiveRate } = calculateSwap(amountIn, pezReserve, whezReserve); + + console.log(` ${amount.toLocaleString('en-US').padStart(7)} PEZ → ${(Number(amountOut) / Number(ONE_TOKEN)).toLocaleString('en-US', { minimumFractionDigits: 2 }).padStart(12)} HEZ (Rate: ${effectiveRate.toFixed(6)}, Impact: ${priceImpact.toFixed(2)}%)`); + } + + // Maximum recommended swaps + console.log('\n⚠️ Recommended Limits (10% price impact):\n'); + + // For 10% impact: solve for amountIn where amountOut/reserveOut = 0.10 + // This is approximate: amountOut ≈ 0.10 * reserveOut + // 0.10 * reserveOut = (0.97 * amountIn * reserveOut) / (reserveIn + 0.97 * amountIn) + // Solving: amountIn ≈ (0.10 * reserveIn) / (0.97 - 0.10) + + const maxHezFor10pct = Number(whezReserve) * 0.10 / 0.87 / Number(ONE_TOKEN); + const maxPezFor10pct = Number(pezReserve) * 0.10 / 0.87 / Number(ONE_TOKEN); + + console.log(` Max HEZ → PEZ: ~${maxHezFor10pct.toLocaleString('en-US', { maximumFractionDigits: 0 })} HEZ`); + console.log(` Max PEZ → HEZ: ~${maxPezFor10pct.toLocaleString('en-US', { maximumFractionDigits: 0 })} PEZ\n`); + + } else { + console.log('❌ Pool reserves not found\n'); + } + } else { + console.log('❌ Pool account not found\n'); + } + } else { + console.log('❌ Pool does not exist\n'); + } + + } catch (error) { + console.log(`❌ Error: ${error.message}\n`); + } + + console.log('='.repeat(70)); + console.log(' AMM Mechanisms'); + console.log('='.repeat(70) + '\n'); + + console.log('🔧 Built-in Mechanisms:\n'); + + console.log('1️⃣ Automatic Rebalancing (Self-Regulating):'); + console.log(' ✓ Pool OTOMATIK olarak dengelenir (x × y = k formülü)'); + console.log(' ✓ Fiyat değişimi supply/demand\'e göre gerçekleşir'); + console.log(' ✓ Arbitraj botları fiyat dengesini sağlar\n'); + + console.log('2️⃣ Liquidity Provider (LP) Mechanism:'); + console.log(' ✓ Herkes pool\'a likidite ekleyebilir (addLiquidity)'); + console.log(' ✓ LP tokenları alırlar (pool payı temsil eder)'); + console.log(' ✓ Fee\'lerden gelir kazanırlar (%3 swap fee)'); + console.log(' ✓ İstedikleri zaman çıkabilirler (removeLiquidity)\n'); + + console.log('3️⃣ Pool ASLA Boşalmaz:'); + console.log(' ✓ Matematiksel olarak imkansız (x × y = k)'); + console.log(' ✓ Reserve azaldıkça fiyat üstel olarak artar'); + console.log(' ✓ %90 reserve swap\'i için extreme yüksek ödeme gerekir'); + console.log(' ✓ Bu yüksek fiyat arbitraj fırsatı yaratır → likidite gelir\n'); + + console.log('4️⃣ NO Automatic Burn Mechanism:'); + console.log(' ✗ Otomatik yakma mekanizması YOK'); + console.log(' ✗ Aşırı bakiye birikimi problemi olmaz'); + console.log(' ✓ Fazla token pool\'a girerse fiyat düşer → arbitraj'); + console.log(' ✓ Piyasa doğal olarak dengelenir\n'); + + console.log('5️⃣ NO Automatic Liquidity Addition:'); + console.log(' ✗ Otomatik likidite ekleme YOK'); + console.log(' ✓ LP\'ler incentive ile (fee geliri) manuel ekler'); + console.log(' ✓ Yüksek volume → yüksek fee → daha fazla LP gelir'); + console.log(' ✓ Düşük liquidity → yüksek slippage → LP fırsatı\n'); + + console.log('💡 Best Practices:'); + console.log(' • Büyük swapları birden fazla küçük swap\'a bölün'); + console.log(' • Slippage tolerance ayarlayın (örn: %5)'); + console.log(' • High impact swaplarda arbitraj beklentisi olsun'); + console.log(' • Liquidity arttırmak için incentive programları ekleyin\n'); + + await api.disconnect(); +} + +main().catch(console.error); diff --git a/create-beta-pool.js b/create-beta-pool.js new file mode 100644 index 00000000..586f8510 --- /dev/null +++ b/create-beta-pool.js @@ -0,0 +1,57 @@ +const { ApiPromise, WsProvider, Keyring } = require('@polkadot/api'); +const { cryptoWaitReady } = require('@polkadot/util-crypto'); + +async function main() { + await cryptoWaitReady(); + + const wsProvider = new WsProvider('ws://127.0.0.1:9944'); + const api = await ApiPromise.create({ provider: wsProvider }); + + // Founder account from seed phrase + const keyring = new Keyring({ type: 'sr25519' }); + const founder = keyring.addFromUri('skill dose toward always latin fish film cabbage praise blouse kingdom depth'); + + console.log('🔑 Founder address:', founder.address); + console.log(''); + + // Get founder balance + const { data: balance } = await api.query.system.account(founder.address); + console.log('💰 HEZ Balance:', balance.free.toHuman()); + console.log(''); + + // Check PEZ balance (asset ID: 1) + const pezBalance = await api.query.assets.account(1, founder.address); + if (pezBalance.isSome) { + console.log('💰 PEZ Balance:', pezBalance.unwrap().balance.toHuman()); + } else { + console.log('💰 PEZ Balance: 0'); + } + console.log(''); + + // Create HEZ/PEZ pool + console.log('🏊 Creating HEZ/PEZ pool...'); + + // In Substrate asset_conversion, asset1 should be < asset2 + // Native token (HEZ) is typically 0, PEZ is 1 + const asset1 = { parents: 0, interior: { Here: null } }; // Native HEZ + const asset2 = { parents: 0, interior: { X2: [{ PalletInstance: 50 }, { GeneralIndex: 1 }] } }; // PEZ token (asset ID 1) + + const txHash = await api.tx.assetConversion + .createPool(asset1, asset2) + .signAndSend(founder, { nonce: -1 }); + + console.log('✅ Pool creation submitted:', txHash.toHex()); + console.log(''); + console.log('⏳ Waiting for pool to be created...'); + + await new Promise(resolve => setTimeout(resolve, 15000)); + + console.log(''); + console.log('✅ Pool should be created!'); + console.log(''); + console.log('💧 Next: Add liquidity via frontend'); + + await api.disconnect(); +} + +main().catch(console.error); diff --git a/create-beta-pool.mjs b/create-beta-pool.mjs new file mode 100644 index 00000000..08be5bb0 --- /dev/null +++ b/create-beta-pool.mjs @@ -0,0 +1,91 @@ +import { ApiPromise, WsProvider, Keyring } from '@polkadot/api'; +import { cryptoWaitReady } from '@polkadot/util-crypto'; + +async function main() { + await cryptoWaitReady(); + + const wsProvider = new WsProvider('ws://127.0.0.1:9944'); + const api = await ApiPromise.create({ provider: wsProvider }); + + // Founder account from seed phrase + const keyring = new Keyring({ type: 'sr25519' }); + const founder = keyring.addFromUri('skill dose toward always latin fish film cabbage praise blouse kingdom depth'); + + console.log('🔑 Founder address:', founder.address); + console.log(''); + + // Get founder balance + const { data: balance } = await api.query.system.account(founder.address); + console.log('💰 HEZ Balance:', balance.free.toHuman()); + console.log(''); + + // Check PEZ balance (asset ID: 1) + const pezBalance = await api.query.assets.account(1, founder.address); + if (pezBalance.isSome) { + console.log('💰 PEZ Balance:', pezBalance.unwrap().balance.toHuman()); + } else { + console.log('💰 PEZ Balance: 0'); + } + console.log(''); + + // Create HEZ/PEZ pool + console.log('🏊 Creating HEZ/PEZ pool...'); + + // For asset conversion pools: + // Native HEZ = { parents: 0, interior: 'Here' } + // PEZ token (asset ID 1) = { parents: 0, interior: { X2: [{ PalletInstance: 50 }, { GeneralIndex: 1 }] } } + + const asset1 = api.createType('MultiLocation', { + parents: 0, + interior: api.createType('Junctions', 'Here') + }); + + const asset2 = api.createType('MultiLocation', { + parents: 0, + interior: api.createType('Junctions', { + X2: [ + api.createType('Junction', { PalletInstance: 50 }), + api.createType('Junction', { GeneralIndex: 1 }) + ] + }) + }); + + console.log('Asset 1 (HEZ):', asset1.toHuman()); + console.log('Asset 2 (PEZ):', asset2.toHuman()); + console.log(''); + + return new Promise((resolve, reject) => { + api.tx.assetConversion + .createPool(asset1, asset2) + .signAndSend(founder, ({ status, events }) => { + console.log('Transaction status:', status.type); + + if (status.isInBlock) { + console.log('✅ Pool creation included in block:', status.asInBlock.toHex()); + console.log(''); + + events.forEach(({ event: { data, method, section } }) => { + console.log(` ${section}.${method}:`, data.toHuman()); + }); + + console.log(''); + console.log('✅ HEZ/PEZ pool created successfully!'); + console.log(''); + console.log('💧 Next: Add liquidity via Polkadot.js Apps or your frontend'); + console.log(' - Go to Developer > Extrinsics'); + console.log(' - Select assetConversion > addLiquidity'); + console.log(' - Add HEZ and PEZ tokens to the pool'); + + api.disconnect(); + resolve(); + } + }) + .catch(err => { + console.error('❌ Error:', err); + api.disconnect(); + reject(err); + }); + }); +} + +main().catch(console.error).finally(() => process.exit(0));