Skip to content

Commit

Permalink
Add delegation to minter/wallet, add anbond and update delegate modals
Browse files Browse the repository at this point in the history
  • Loading branch information
denis-skripnik committed Jan 21, 2021
1 parent d55cb43 commit 3c216db
Show file tree
Hide file tree
Showing 6 changed files with 193 additions and 5 deletions.
5 changes: 3 additions & 2 deletions blockchains/minter/apps/wallet/content.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
<h2>Балансы пользователя <span id="username"></span></h2>
<ul id="balances"></ul>
<ul id="actions" class="terms" style="display: none;"> </ul>
<h2>Делегированные монеты</h2>
<p><a href="'.$conf['siteUrl'].'minter/wallet/delegation" target="_blank">Перейти</a></p>
<div style="display: none;" id="vesting_withdraw_modal">
<h4 class="modal-title">Вывод СГ в golos</h4>
<p><button data-fancybox-close class="btn">Закрыть</button></p>
Expand Down Expand Up @@ -58,7 +59,7 @@
</div>
</div>
<div style="display: none;" id="delegate_modal">
<h4 class="modal-title">Конвертация <span class="delegate_modal_token"></span></h4>
<h4 class="modal-title">Делегирование <span class="delegate_modal_token"></span></h4>
<p><button data-fancybox-close class="btn">Закрыть</button></p>
<div id="action_delegate">
<form class="form" name="postForm">
Expand Down
4 changes: 4 additions & 0 deletions blockchains/minter/apps/wallet/delegation/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"title": "Кошелёк для Minter | Делегирование",
"description": "Делегирование - это одна из страниц сервиса, что называется кошельком. Создан также для Минтера."
}
62 changes: 62 additions & 0 deletions blockchains/minter/apps/wallet/delegation/content.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php if (!defined('NOTLOAD')) exit('No direct script access allowed');
return '<div id="seed_auth_msg" style="display: none;"><p>Для работы с кошельком необходимо авторизоваться seed фразой. Укажите её <a href="'.$conf['siteUrl'].'minter/accounts" target="_blank">на странице аккаунтов</a>.</p></div>
<div id="seed_page">
<div id="main_wallet_info" style="display: none;">
<p>Адрес: <a target="_blank" id="address_link"><span id="current_address"></span></a><br>
<input type="button" id="copy_address" value="Копировать"></p>
<ul id="balances" style="display: none;"></ul>
<ul id="actions" class="terms" style="display: none;"></ul>
<h2>Делегированные монеты</h2>
<table><thead><tr>
<th>Статус валидатора, ключ<br>
Название</th>
<th>Стек<br>
В BIP</th>
<th>В списке ожидания?</th>
<th>Действия...</th>
</tr></thead>
</tr></thead>
<tbody id="delegation_tbody"></tbody></table>
<div style="display: none;" id="delegate_modal">
<h4 class="modal-title">Конвертация <span class="delegate_modal_token"></span></h4>
<p><button data-fancybox-close class="btn">Закрыть</button></p>
<div id="action_delegate">
<form class="form" name="postForm">
<p><label for="delegate_template">Выберите шаблон делегирования:</label></p>
<p><select name="delegate_template" id="select_delegate_template">
<option value="">Выберите шаблон (данные будут установлены в поля при выборе)</option>
</select> <span style="display: none;" id="remove_delegate_template">(<input type="button" value="Удалить текущий шаблон" id="action_remove_delegate_template">)</span> </p>
<p><label for="delegate_to">Публичный ключ валидатора (можно выбрать <a href="'.$conf['siteUrl'].'minter/validators" target="_blank">тут</a>):</label></p>
<p><input type="text" name="delegate_to" id="action_delegate_key" placeholder="MP..."></p>
<p><label for="delegate_amount">Сумма делегирования (<span id="max_token_delegate">делегировать все доступные <span id="max_delegate_amount"></span> <span class="delegate_modal_token"></span></span>):</label></p>
<p><input type="text" name="delegate_amount" id="action_delegate_stake" placeholder="Введите сумму в формате 1.000"></p>
<p><strong>Комиссия: <span id="delegate_fee">1</span> <span class="delegate_modal_token"></span></strong></p>
<p><input type="button" id="action_delegate_start" value="Делегировать"></p>
<hr>
<p><input type="button" id="action_save_delegate_template" value="Создать шаблон делегирования"></p>
</form>
</div>
</div>
<div style="display: none;" id="anbond_modal">
<h4 class="modal-title">Анбонд <span class="anbond_modal_token"></span></h4>
<p><button data-fancybox-close class="btn">Закрыть</button></p>
<div id="action_anbond">
<form class="form" name="postForm">
<p><label for="delegate_to">Публичный ключ валидатора:</label></p>
<p><input type="text" readonly name="anbond_to" id="action_anbond_key"></p>
<p><label for="anbond_amount">Сумма анбонда (<span id="max_token_anbond">все доступные <span id="max_anbond_amount"></span> <span class="anbond_modal_token"></span></span>):</label></p>
<p><input type="text" name="anbond_amount" id="action_anbond_stake" placeholder="Введите сумму в формате 1.000"></p>
<p><strong>Комиссия: <span id="anbond_fee">10</span> <span class="anbond_modal_token"></span></strong></p>
<p><input type="button" id="action_anbond_start" value="Анбонднуть"></p>
</form>
</div>
</div>
</div>
</div>
<script>
getDelegations();
</script>
'; ?>
16 changes: 15 additions & 1 deletion blockchains/minter/apps/wallet/index.php
Original file line number Diff line number Diff line change
@@ -1,2 +1,16 @@
<?php if (!defined('NOTLOAD')) exit('No direct script access allowed');
?>
require_once 'functions.php';
function generateAppPages() {
global $conf;
$delegation = pageUrl()[2];
if (is_dir(__DIR__.'/'.$delegation)) {
$page_config = configs(__DIR__.'/'.$delegation.'/config.json');
$data = [];
$data['title'] = $page_config['title'];
$data['description'] = $page_config['description'];
$data['content'] = require_once(__DIR__.'/'.$delegation.'/content.php');
}
return $data;
}
$data = generateAppPages();
?>
82 changes: 80 additions & 2 deletions blockchains/minter/apps/wallet/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ async function getFee(coin, type, memo) {
let memo_bytes = byteCount(memo) * 0.2;
let type_fee = 1;
if (type === 'convert') type_fee = 10;
if (type === 'delegate') type_fee = 20;
if (type === 'delegate' || type === 'anbond') type_fee = 20;
let fee = (memo_bytes + type_fee).toFixed(3);
if (coin !== 'BIP') {
let coin_info = await minter.getCoinInfo(coin);
Expand Down Expand Up @@ -265,6 +265,43 @@ async function getConvertPrice() {
}
}

async function getDelegations() {
try {
let result = await axios.get('https://explorer-api.minter.network/api/v2/addresses/Mxae30a08fae2cc95960c5055d1142fd676995e18b/delegations');
let res = result.data.data;
if (res && res.length > 0) {
$('#delegation_tbody').css('display', 'block');
let table = '';
for (let el of res) {
let amount = parseFloat(el.value).toFixed(3) + ' ' + el.coin.symbol;
let bip_amount = parseFloat(el.bip_value).toFixed(3) + ' BIP';
let validator_key = el.validator.public_key;
let validator_name = el.validator.name;
let validator_status = 'Валидатор';
if (el.validator.status === 1) {
validator_status = 'Кандидат';
} else if (el.validator.status === 0) {
validator_status = 'Отключён';
}
let is_waitlisted = (el.is_waitlisted == false ? 'Нет' : 'Да');
table += `<tr>
<td><strong>${validator_status}</strong>
<input type="text" readonly id="validator_${validator_key}" value="${validator_key}"> (<input type="button" value="копировать" onclick="copyText('validator_${validator_key}');">)<br>
${validator_name}</td>
<td>${amount}<br>
${bip_amount}</td>
<td>${is_waitlisted}</td>
<td><a data-fancybox class="delegate_modal" data-src="#delegate_modal" href="javascript:;" data-token="${el.coin.symbol}" data-pubkey="${validator_key}" onclick="getDelegateTemplates('${el.coin.symbol}');">Делегировать ${el.coin.symbol}</a>, <a data-fancybox class="anbond_modal" data-src="#anbond_modal" href="javascript:;" data-token="${el.coin.symbol}" data-pubkey="${validator_key}" data-amount="${parseFloat(el.value).toFixed(3)}">Анбонд ${el.coin.symbol}</a></td>
</tr>`;
} // end for
$('#delegation_tbody').html(table);
} // end if res.

} catch(e) {
console.log('Ошибка с делегированием: ' + e);
}
}

$(document).ready(async function() {
if (seed) {
jQuery("#main_wallet_info").css("display", "block");
Expand Down Expand Up @@ -298,11 +335,34 @@ $('.convert_modal_token').html(token);

$(document).on('click', '.delegate_modal', async function(e) {
let token = $(this).attr('data-token');
$('.delegate_modal_token').html(token);
let key = $(this).attr('data-pubkey');
if (key) {
$('#action_delegate_key').val(key);
}
$('.delegate_modal_token').html(token);
$('#max_delegate_amount').html($('#max_' + token).html());
await getFee(token, 'delegate');
});

$(document).on('click', '.anbond_modal', async function(e) {
let token = $(this).attr('data-token');
let key = $(this).attr('data-pubkey');
$('#action_anbond_key').val(key);
let amount = $(this).attr('data-amount');
$('.anbond_modal_token').html(token);
$('#max_anbond_amount').html(amount);
await getFee(token, 'anbond');
});

$("#max_token_anbond").click(async function(){
let coin = $('.anbond_modal_token').html();
let max_amount = $('#max_anbond_amount').html();
max_amount = parseFloat(max_amount);
let fee = parseFloat($('#anbond_fee').html());
max_amount -= fee + 0.001;
$('#action_anbond_stake').val(new Number(max_amount).toFixed(3));
});

$("#action_transfer_start").click(async function(){
let q = window.confirm('Вы действительно хотите сделать перевод средств?');
if (q == true) {
Expand Down Expand Up @@ -380,6 +440,24 @@ $("#action_delegate_start").click(async function(){
}
}); // end subform

$("#action_anbond_start").click(async function(){
let q = window.confirm('Вы действительно хотите сделать анбонд?');
if (q == true) {
let coin = $('.anbond_modal_token').html();
let publicKey = $('#action_anbond_key').val();
let stake = $('#action_anbond_stake').val();
stake = parseFloat(stake);

try {
$.fancybox.close();
await anbond(coin, publicKey, stake)
await loadBalances();
} catch(e) {
window.alert('Ошибка: ' + e);
}
}
}); // end subform

$("#action_save_transfer_template").click(function(){
let name = window.prompt('Введите название шаблона');
if (name && name !== '') {
Expand Down
29 changes: 29 additions & 0 deletions blockchains/minter/js/blockchain.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,35 @@ $( document ).ready(function() {
});
}

async function anbond(coin, publicKey, stake) {
let wif = sender.privateKey;
const txParams = {
chainId: 1,
type: TX_TYPE.UNBOND,
data: {
publicKey,
coin,
stake,
},
};
const idTxParams = await minter.replaceCoinSymbol(txParams);
console.log(idTxParams);
minter.postTx(idTxParams, {privateKey: wif})
.then(async (txHash) => {
$.fancybox.open(`<p id="message"><strong>Пожалуйста, подождите. Идёт отправка и проверка доставки транзакции.</strong></p>`);
await new Promise(r => setTimeout(r, 5000));
let res = await getTransaction(txHash.hash);
if (res === true) {
document.getElementById('message').innerHTML = (`<strong>Ok. Транзакция создана и отправлена: <a href="/minter/explorer/tx/${txHash.hash}" target="_blank">${txHash.hash}</a></strong>`);
} else {
document.getElementById('message').innerHTML = ('Ошибка. Транзакция отправлена, но не принята.');
}
}).catch((error) => {
const errorMessage = error.response.error.message
throw `Ошибка: ${errorMessage}`;
});
}

async function getBalance(address) {
try {
let response = await axios.get('/address/' + address);
Expand Down

0 comments on commit 3c216db

Please sign in to comment.