Code refactoring

This commit is contained in:
sairaj mote 2023-10-25 21:14:51 +05:30
parent d28f66929c
commit 5b72b3021e

View File

@ -580,7 +580,6 @@
if (this.routingStart) {
this.routingStart(this.state)
}
console
if (this.routes[page]) {
await this.routes[page](this.state)
this.lastPage = page
@ -848,14 +847,17 @@
}).catch(err => reject(err))
})
}
function getConvertedAmount(amount) {
function getConvertedAmount(amount, shouldFormat = false) {
// check if amount is a string and convert it to a number
if (typeof amount === 'string') {
amount = parseFloat(amount)
}
let convertedAmount = amount;
if (globalExchangeRate[selectedCurrency])
return parseFloat((amount * globalExchangeRate[selectedCurrency]).toFixed(8))
else return amount
convertedAmount = parseFloat((amount * globalExchangeRate[selectedCurrency]).toFixed(8))
if (shouldFormat)
convertedAmount = formatAmount(convertedAmount)
return convertedAmount
}
function roundUp(amount, precision = 2) {
return parseFloat((Math.ceil(amount * Math.pow(10, precision)) / Math.pow(10, precision)).toFixed(precision))
@ -891,7 +893,7 @@
el.isValid // trigger validation
} else {
if (el.dataset.btcAmount === undefined) return
el.textContent = formatAmount(getConvertedAmount(el.dataset.btcAmount))
el.textContent = getConvertedAmount(el.dataset.btcAmount, true)
}
})
previouslySelectedCurrency = selectedCurrency
@ -934,7 +936,7 @@
<div class="grid gap-0-5">
<div class="flex gap-0-5 space-between align-center flex-wrap">
<time class="transaction__time">${getFormattedTime(time)}</time>
<div class="transaction__amount amount-shown" data-btc-amount="${amount}">${formatAmount(getConvertedAmount(amount))}</div>
<div class="transaction__amount amount-shown" data-btc-amount="${amount}">${getConvertedAmount(amount, true)}</div>
</div>
<div class="transaction__receiver">
${transactionReceiver}
@ -970,7 +972,7 @@
getRef('transactions_list').innerHTML = '<sm-spinner class="justify-self-center margin-top-1-5"></sm-spinner>';
getRef('address_balance').innerHTML = '<sm-spinner class="justify-self-center margin-top-1-5"></sm-spinner>';
btcOperator.getAddressData(address).then(result => {
getRef('address_balance').value = formatAmount(getConvertedAmount(result.balance));
getRef('address_balance').value = getConvertedAmount(result.balance, true);
getRef('address_balance').dataset.btcAmount = result.balance;
getRef('address_balance').parentElement.classList.remove('hidden')
getRef('filter_selector').classList.remove('hidden')
@ -1045,7 +1047,7 @@
<svg class="icon" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M15 4c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6zM3 12c0-2.61 1.67-4.83 4-5.65V4.26C3.55 5.15 1 8.27 1 12s2.55 6.85 6 7.74v-2.09c-2.33-.82-4-3.04-4-5.65z"/></svg>
<div>Fee</div>
</div>
<div class="amount-shown" data-btc-amount="${fee}">${formatAmount(getConvertedAmount(fee))}</div>
<div class="amount-shown" data-btc-amount="${fee}">${getConvertedAmount(fee, true)}</div>
</div>
</div>
<details class="margin-bottom-1-5 justify-self-center w-100">
@ -1059,14 +1061,14 @@
<svg class="icon" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z"/></svg>
<div>Total Inputs</div>
</div>
<div class="amount-shown" data-btc-amount="${total_input_value}">${formatAmount(getConvertedAmount(total_input_value))}</div>
<div class="amount-shown" data-btc-amount="${total_input_value}">${getConvertedAmount(total_input_value, true)}</div>
</div>
<div class="tx-detail">
<div class="flex align-center gap-0-3">
<svg class="icon" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8-8 8z"/></svg>
<div>Total Outputs</div>
</div>
<div class="amount-shown" data-btc-amount="${total_output_value}">${formatAmount(getConvertedAmount(total_output_value))}</div>
<div class="amount-shown" data-btc-amount="${total_output_value}">${getConvertedAmount(total_output_value, true)}</div>
</div>
<div class="tx-detail">
<div class="flex align-center gap-0-3">
@ -1087,7 +1089,7 @@
${inputs.map(input => html`
<li class="in-out-card">
<a href="${`#/search?query=${input.address}`}" class="input-address wrap-around">${input.address}</a>
<div class="input-value amount-shown" data-btc-amount="${input.value}">${formatAmount(getConvertedAmount(input.value))}</div>
<div class="input-value amount-shown" data-btc-amount="${input.value}">${getConvertedAmount(input.value, true)}</div>
</li>
`)}
</ul>
@ -1101,7 +1103,7 @@
${outputs.map(output => html`
<li class="in-out-card">
<a href="${`#/search?query=${output.address}`}" class="output-address wrap-around">${output.address}</a>
<div class="output-value amount-shown" data-btc-amount="${output.value}">${formatAmount(getConvertedAmount(output.value))}</div>
<div class="output-value amount-shown" data-btc-amount="${output.value}">${getConvertedAmount(output.value, true)}</div>
</li>
`)}
</ul>
@ -1357,7 +1359,7 @@
<sm-copy value=${address}><p>${address}<p></sm-copy>
</div>
<p>
Balance: <b class="amount-shown" data-btc-amount=${balance}>${formatAmount(getConvertedAmount(balance))}</b>
Balance: <b class="amount-shown" data-btc-amount=${balance}>${getConvertedAmount(balance, true)}</b>
</p>
</div>
`)
@ -1450,14 +1452,14 @@
${Object.entries(receivers).map(([address, amount]) => html.node/*html*/`
<div class="grid gap-0-5" style="padding:0.5rem;border:solid thin rgba(var(--text-color),0.3);border-radius: 0.3rem;">
<b>${address}</b>
<b class="amount-shown" data-btc-amount=${amount}>${formatAmount(getConvertedAmount(amount))}</b>
<b class="amount-shown" data-btc-amount=${amount}>${getConvertedAmount(amount, true)}</b>
</div>
`)}
</div>
</div>
<div class="grid">
<span class="label">Fee</span>
<b class="amount-shown" data-btc-amount=${fee}>${formatAmount(getConvertedAmount(fee))}</b>
<b class="amount-shown" data-btc-amount=${fee}>${getConvertedAmount(fee, true)}</b>
</div>
</div>
`,
@ -1614,16 +1616,16 @@
</div>
<div>
<div class="label">Amount</div>
<b>${formatAmount(getConvertedAmount(value))}</b>
<b>${getConvertedAmount(value, true)}</b>
</div>
</li>`)}
</ul>
</div>
<div class="grid gap-0-5">
<p>
Previous fee: <b>${formatAmount(getConvertedAmount(previousFee))}</b> ${recommendedFee ? html`| Recommended fee: <b>${formatAmount(getConvertedAmount(recommendedFee))}</b>` : ''}
Previous fee: <b>${getConvertedAmount(previousFee, true)}</b> ${recommendedFee ? html`| Recommended fee: <b>${getConvertedAmount(recommendedFee, true)}</b>` : ''}
</p>
<sm-input id="new_fee" placeholder="New fee" type="number" min=${getConvertedAmount(previousFee)} step="0.00000001" error-text=${`New fee should be greater than ${formatAmount(getConvertedAmount(previousFee))}`} animate required>
<sm-input id="new_fee" placeholder="New fee" type="number" min=${getConvertedAmount(previousFee)} step="0.00000001" error-text=${`New fee should be greater than ${getConvertedAmount(previousFee, true)}`} animate required>
<div class="currency-symbol flex" slot="icon"> </div>
</sm-input>
</div>
@ -1697,16 +1699,12 @@
SEGWIT_OUTPUT_SIZE = 23,
BECH32M_OUTPUT_SIZE = 35; // Check this later
const util = {};
util.Sat_to_BTC = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8));
util.BTC_to_Sat = value => parseInt(value * SATOSHI_IN_BTC);
function get_fee_rate() {
return new Promise((resolve, reject) => {
fetch('https://api.blockchain.info/mempool/fees').then(response => {
if (response.ok)
response.json()
.then(result => resolve(util.Sat_to_BTC(result.regular)))
.then(result => resolve(btcOperator.util.Sat_to_BTC(result.regular)))
.catch(error => reject(error));
else
reject(response);
@ -1782,16 +1780,16 @@
const opts = {};
const tx = new taproot.Transaction(opts);
const totalAmount = amounts.reduce((total, amount) => total + amount, 0)
const amountInSat = util.BTC_to_Sat(totalAmount)
const amountInSat = btcOperator.util.BTC_to_Sat(totalAmount)
// check if sender has enough balance
const senderBalance = await btcOperator.getBalance(address)
const feeRate = await get_fee_rate();
let calculatedFee = 0
const { input_size } = await addUTXOs(tx, tr, [address], util.BTC_to_Sat(totalAmount), feeRate)
const { input_size } = await addUTXOs(tx, tr, [address], btcOperator.util.BTC_to_Sat(totalAmount), feeRate)
calculatedFee += input_size
// add receivers
receivers.forEach((receiver, i) => {
tx.addOutputAddress(receiver, BigInt(util.BTC_to_Sat(amounts[i])))
tx.addOutputAddress(receiver, BigInt(btcOperator.util.BTC_to_Sat(amounts[i])))
calculatedFee += _sizePerOutput(receiver)
})
calculatedFee += _sizePerOutput(address)
@ -1800,8 +1798,8 @@
// add change address
const changeAmount = senderBalance - (totalAmount + fee)
if (changeAmount < 0)
return reject(`Insufficient balance. Required: ${formatAmount(getConvertedAmount(totalAmount + fee))}, Available: ${formatAmount(getConvertedAmount(util.Sat_to_BTC(senderBalance)))}`)
tx.addOutputAddress(address, BigInt(util.BTC_to_Sat(changeAmount)));
return reject(`Insufficient balance. Required: ${getConvertedAmount(totalAmount + fee, true)}, Available: ${getConvertedAmount(btcOperator.util.Sat_to_BTC(senderBalance), true)}`)
tx.addOutputAddress(address, BigInt(btcOperator.util.BTC_to_Sat(changeAmount)));
const privKey = coinjs.wif2privkey(senderPrivateKey).privkey;
const privKey_arrayForm = hex.decode(privKey);
tx.sign(privKey_arrayForm, undefined, new Uint8Array(32));