603 lines
29 KiB
HTML
603 lines
29 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>RanchiMall Taproot wallet</title>
|
|
<link rel="stylesheet" href="css/main.min.css">
|
|
</head>
|
|
|
|
<body class="hidden">
|
|
<sm-notifications id="notification_drawer"></sm-notifications>
|
|
<main class="page">
|
|
<header id="main_header">
|
|
<a href="#/home" id="logo" class="app-brand">
|
|
<svg id="main_logo" class="icon" viewBox="0 0 27.25 32">
|
|
<title>RanchiMall</title>
|
|
<path
|
|
d="M27.14,30.86c-.74-2.48-3-4.36-8.25-6.94a20,20,0,0,1-4.2-2.49,6,6,0,0,1-1.25-1.67,4,4,0,0,1,0-2.26c.37-1.08.79-1.57,3.89-4.55a11.66,11.66,0,0,0,3.34-4.67,6.54,6.54,0,0,0,.05-2.82C20,3.6,18.58,2,16.16.49c-.89-.56-1.29-.64-1.3-.24a3,3,0,0,1-.3.72l-.3.55L13.42.94C13,.62,12.4.26,12.19.15c-.4-.2-.73-.18-.72.05a9.39,9.39,0,0,1-.61,1.33s-.14,0-.27-.13C8.76.09,8-.27,8,.23A11.73,11.73,0,0,1,6.76,2.6C4.81,5.87,2.83,7.49.77,7.49c-.89,0-.88,0-.61,1,.22.85.33.92,1.09.69A5.29,5.29,0,0,0,3,8.33c.23-.17.45-.29.49-.26a2,2,0,0,1,.22.63A1.31,1.31,0,0,0,4,9.34a5.62,5.62,0,0,0,2.27-.87L7,8l.13.55c.19.74.32.82,1,.65a7.06,7.06,0,0,0,3.46-2.47l.6-.71-.06.64c-.17,1.63-1.3,3.42-3.39,5.42L6.73,14c-3.21,3.06-3,5.59.6,8a46.77,46.77,0,0,0,4.6,2.41c.28.13,1,.52,1.59.87,3.31,2,4.95,3.92,4.95,5.93a2.49,2.49,0,0,0,.07.77h0c.09.09,0,.1.9-.14a2.61,2.61,0,0,0,.83-.32,3.69,3.69,0,0,0-.55-1.83A11.14,11.14,0,0,0,17,26.81a35.7,35.7,0,0,0-5.1-2.91C9.37,22.64,8.38,22,7.52,21.17a3.53,3.53,0,0,1-1.18-2.48c0-1.38.71-2.58,2.5-4.23,2.84-2.6,3.92-3.91,4.67-5.65a3.64,3.64,0,0,0,.42-2A3.37,3.37,0,0,0,13.61,5l-.32-.74.29-.48c.17-.27.37-.63.46-.8l.15-.3.44.64a5.92,5.92,0,0,1,1,2.81,5.86,5.86,0,0,1-.42,1.94c0,.12-.12.3-.15.4a9.49,9.49,0,0,1-.67,1.1,28,28,0,0,1-4,4.29C8.62,15.49,8.05,16.44,8,17.78a3.28,3.28,0,0,0,1.11,2.76c.95,1,2.07,1.74,5.25,3.32,3.64,1.82,5.22,2.9,6.41,4.38A4.78,4.78,0,0,1,21.94,31a3.21,3.21,0,0,0,.14.92,1.06,1.06,0,0,0,.43-.05l.83-.22.46-.12-.06-.46c-.21-1.53-1.62-3.25-3.94-4.8a37.57,37.57,0,0,0-5.22-2.82A13.36,13.36,0,0,1,11,21.19a3.36,3.36,0,0,1-.8-4.19c.41-.85.83-1.31,3.77-4.15,2.39-2.31,3.43-4.13,3.43-6a5.85,5.85,0,0,0-2.08-4.29c-.23-.21-.44-.43-.65-.65A2.5,2.5,0,0,1,15.27.69a10.6,10.6,0,0,1,2.91,2.78A4.16,4.16,0,0,1,19,6.16a4.91,4.91,0,0,1-.87,3c-.71,1.22-1.26,1.82-4.27,4.67a9.47,9.47,0,0,0-2.07,2.6,2.76,2.76,0,0,0-.33,1.54,2.76,2.76,0,0,0,.29,1.47c.57,1.21,2.23,2.55,4.65,3.73a32.41,32.41,0,0,1,5.82,3.24c2.16,1.6,3.2,3.16,3.2,4.8a1.94,1.94,0,0,0,.09.76,4.54,4.54,0,0,0,1.66-.4C27.29,31.42,27.29,31.37,27.14,30.86ZM6.1,7h0a3.77,3.77,0,0,1-1.46.45L4,7.51l.68-.83a25.09,25.09,0,0,0,3-4.82A12,12,0,0,1,8.28.76c.11-.12.77.32,1.53,1l.63.58-.57.84A10.34,10.34,0,0,1,6.1,7Zm5.71-1.78A9.77,9.77,0,0,1,9.24,7.18h0a5.25,5.25,0,0,1-1.17.28l-.58,0,.65-.78a21.29,21.29,0,0,0,2.1-3.12c.22-.41.42-.76.44-.79s.5.43.9,1.24L12,5ZM13.41,3a2.84,2.84,0,0,1-.45.64,11,11,0,0,1-.9-.91l-.84-.9.19-.45c.34-.79.39-.8,1-.31A9.4,9.4,0,0,1,13.8,2.33q-.18.34-.39.69Z" />
|
|
</svg>
|
|
<div class="app-name">
|
|
<div class="app-name__company">RanchiMall</div>
|
|
<h4 class="app-name__title">
|
|
Taproot Wallet
|
|
</h4>
|
|
</div>
|
|
</a>
|
|
<theme-toggle></theme-toggle>
|
|
</header>
|
|
<menu>
|
|
<li>
|
|
<button class="button button--colored" onclick="generateNewAddress()">
|
|
Create new address
|
|
</button>
|
|
<button class="button button--colored" onclick="convertToTaproot()">
|
|
Convert to Taproot address
|
|
</button>
|
|
</li>
|
|
</menu>
|
|
<h3>
|
|
Send Transaction
|
|
</h3>
|
|
<sm-form>
|
|
<div class="flex flex-direction-column gap-0-5">
|
|
<h4>Sender</h4>
|
|
<sm-input id="private_key_input" placeholder="Sender's private key" data-private-key
|
|
class="password-field" type="password" required>
|
|
<svg class="icon" slot="icon" xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24"
|
|
height="24px" viewBox="0 0 24 24" width="24px" fill="#000000">
|
|
<g>
|
|
<rect fill="none" height="24" width="24"></rect>
|
|
</g>
|
|
<g>
|
|
<path
|
|
d="M21,10h-8.35C11.83,7.67,9.61,6,7,6c-3.31,0-6,2.69-6,6s2.69,6,6,6c2.61,0,4.83-1.67,5.65-4H13l2,2l2-2l2,2l4-4.04L21,10z M7,15c-1.65,0-3-1.35-3-3c0-1.65,1.35-3,3-3s3,1.35,3,3C10,13.65,8.65,15,7,15z">
|
|
</path>
|
|
</g>
|
|
</svg>
|
|
<label slot="right" class="interact">
|
|
<input type="checkbox" class="hidden" autocomplete="off" readonly=""
|
|
onchange="togglePrivateKeyVisibility(this)">
|
|
<svg class="icon invisible" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24"
|
|
width="24px" fill="#000000">
|
|
<title>Hide password</title>
|
|
<path d="M0 0h24v24H0zm0 0h24v24H0zm0 0h24v24H0zm0 0h24v24H0z" fill="none"></path>
|
|
<path
|
|
d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z">
|
|
</path>
|
|
</svg>
|
|
<svg class="icon visible" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24"
|
|
width="24px" fill="#000000">
|
|
<title>Show password</title>
|
|
<path d="M0 0h24v24H0z" fill="none"></path>
|
|
<path
|
|
d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z">
|
|
</path>
|
|
</svg>
|
|
</label>
|
|
</sm-input>
|
|
</div>
|
|
<div class="flex flex-direction-column gap-1">
|
|
<div class="flex flex-direction-column gap-0-5">
|
|
<h4>Receiver</h4>
|
|
<sm-input id="receiver_address_input" placeholder="Receiver's address" data-btc-address
|
|
required></sm-input>
|
|
<sm-input id="amount_input" placeholder="Amount" type="number" required>
|
|
<div class="currency-symbol flex" slot="icon">
|
|
<svg class="icon" xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24"
|
|
height="24px" viewBox="0 0 24 24" width="24px" fill="#000000">
|
|
<g>
|
|
<rect fill="none" height="24" width="24"></rect>
|
|
</g>
|
|
<g>
|
|
<path
|
|
d="M17.06,11.57C17.65,10.88,18,9.98,18,9c0-1.86-1.27-3.43-3-3.87L15,3h-2v2h-2V3H9v2H6v2h2v10H6v2h3v2h2v-2h2v2h2v-2 c2.21,0,4-1.79,4-4C19,13.55,18.22,12.27,17.06,11.57z M10,7h4c1.1,0,2,0.9,2,2s-0.9,2-2,2h-4V7z M15,17h-5v-4h5c1.1,0,2,0.9,2,2 S16.1,17,15,17z">
|
|
</path>
|
|
</g>
|
|
</svg>
|
|
</div>
|
|
</sm-input>
|
|
</div>
|
|
<sm-input id="fee_input" placeholder="Fee" required></sm-input>
|
|
<button class="button button--primary" type="submit" onclick="sendTx()">Send</button>
|
|
</div>
|
|
</sm-form>
|
|
</main>
|
|
<script src="https://unpkg.com/uhtml@3.0.1/es.js"></script>
|
|
<script src="scripts/components.min.js" type="text/javascript"></script>
|
|
<script src="scripts/btcwallet_scripts_lib.js" type="text/javascript"></script>
|
|
<script src="scripts/btcOperator.js"></script>
|
|
<script src="scripts/floCrypto.js"></script>
|
|
<script src="scripts/tap_combined.js" type="text/javascript"></script>
|
|
<script id="ui_utils">
|
|
const uiGlobals = {}
|
|
const { html, svg, render: renderElem } = uhtml;
|
|
uiGlobals.connectionErrorNotification = []
|
|
//Checks for internet connection status
|
|
if (!navigator.onLine)
|
|
uiGlobals.connectionErrorNotification.push(notify('There seems to be a problem connecting to the internet, Please check you internet connection.', 'error'))
|
|
window.addEventListener('offline', () => {
|
|
uiGlobals.connectionErrorNotification.push(notify('There seems to be a problem connecting to the internet, Please check you internet connection.', 'error'))
|
|
})
|
|
window.addEventListener('online', () => {
|
|
uiGlobals.connectionErrorNotification.forEach(notification => {
|
|
getRef('notification_drawer').remove(notification)
|
|
})
|
|
notify('We are back online.', 'success')
|
|
})
|
|
|
|
// Use instead of document.getElementById
|
|
function getRef(elementId) {
|
|
return document.getElementById(elementId)
|
|
}
|
|
|
|
let zIndex = 50
|
|
// function required for popups or modals to appear
|
|
function openPopup(popupId, pinned) {
|
|
zIndex++
|
|
getRef(popupId).setAttribute('style', `z-index: ${zIndex}`)
|
|
getRef(popupId).show({ pinned })
|
|
return getRef(popupId);
|
|
}
|
|
|
|
// hides the popup or modal
|
|
function closePopup() {
|
|
if (popupStack.peek() === undefined)
|
|
return;
|
|
popupStack.peek().popup.hide()
|
|
}
|
|
|
|
document.addEventListener('popupopened', e => {
|
|
switch (e.target.id) {
|
|
}
|
|
})
|
|
document.addEventListener('popupclosed', e => {
|
|
zIndex--
|
|
switch (e.target.id) {
|
|
case 'retrieve_btc_addr_popup':
|
|
getRef('recovered_btc_addr_wrapper').classList.add('hidden')
|
|
break;
|
|
case 'increase_fee_popup':
|
|
renderElem(getRef('increase_fee_popup_content'), html``)
|
|
break;
|
|
}
|
|
})
|
|
|
|
//Function for displaying toast notifications. pass in error for mode param if you want to show an error.
|
|
function notify(message, mode, options = {}) {
|
|
let icon
|
|
switch (mode) {
|
|
case 'success':
|
|
icon = `<svg class="icon icon--success" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill="none" d="M0 0h24v24H0z"/><path d="M10 15.172l9.192-9.193 1.415 1.414L10 18l-6.364-6.364 1.414-1.414z"/></svg>`
|
|
break;
|
|
case 'error':
|
|
icon = `<svg class="icon icon--error" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill="none" d="M0 0h24v24H0z"/><path d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm-1-7v2h2v-2h-2zm0-8v6h2V7h-2z"/></svg>`
|
|
options.pinned = true
|
|
break;
|
|
}
|
|
getRef("notification_drawer").push(message, { icon, ...options });
|
|
if (mode === 'error') {
|
|
console.error(message)
|
|
}
|
|
}
|
|
|
|
function getFormattedTime(timestamp, format) {
|
|
try {
|
|
if (String(timestamp).length < 13)
|
|
timestamp *= 1000
|
|
let [day, month, date, year] = new Date(timestamp).toString().split(' '),
|
|
minutes = new Date(timestamp).getMinutes(),
|
|
hours = new Date(timestamp).getHours(),
|
|
currentTime = new Date().toString().split(' ')
|
|
|
|
minutes = minutes < 10 ? `0${minutes}` : minutes
|
|
let finalHours = ``;
|
|
if (hours > 12)
|
|
finalHours = `${hours - 12}:${minutes}`
|
|
else if (hours === 0)
|
|
finalHours = `12:${minutes}`
|
|
else
|
|
finalHours = `${hours}:${minutes}`
|
|
|
|
finalHours = hours >= 12 ? `${finalHours} PM` : `${finalHours} AM`
|
|
switch (format) {
|
|
case 'date-only':
|
|
return `${month} ${date}, ${year}`;
|
|
break;
|
|
case 'time-only':
|
|
return finalHours;
|
|
case 'relative':
|
|
// check if timestamp is older than a day
|
|
if (Date.now() - new Date(timestamp) < 60 * 60 * 24 * 1000)
|
|
return `${finalHours}`;
|
|
else
|
|
return relativeTime.from(timestamp)
|
|
default:
|
|
return `${month} ${date}, ${year} at ${finalHours}`;
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
return timestamp;
|
|
}
|
|
}
|
|
// detect browser version
|
|
function detectBrowser() {
|
|
let ua = navigator.userAgent,
|
|
tem,
|
|
M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
|
|
if (/trident/i.test(M[1])) {
|
|
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
|
|
return 'IE ' + (tem[1] || '');
|
|
}
|
|
if (M[1] === 'Chrome') {
|
|
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
|
|
if (tem != null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
|
|
}
|
|
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
|
|
if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
|
|
return M.join(' ');
|
|
}
|
|
window.addEventListener("load", () => {
|
|
const [browserName, browserVersion] = detectBrowser().split(' ');
|
|
const supportedVersions = {
|
|
Chrome: 85,
|
|
Firefox: 75,
|
|
Safari: 13,
|
|
}
|
|
if (browserName in supportedVersions) {
|
|
if (parseInt(browserVersion) < supportedVersions[browserName]) {
|
|
notify(`${browserName} ${browserVersion} is not fully supported, some features may not work properly. Please update to ${supportedVersions[browserName]} or higher.`, 'error')
|
|
}
|
|
} else {
|
|
notify('Browser is not fully compatible, some features may not work. for best experience please use Chrome, Edge, Firefox or Safari', 'error')
|
|
}
|
|
document.body.classList.remove('hidden')
|
|
document.querySelectorAll('sm-input[data-btc-address]').forEach(input => input.customValidation = (value) => {
|
|
return {
|
|
isValid: btcOperator.validateAddress(value),
|
|
errorText: `Invalid address. It's a long string of random characters usually starting with '1','3' or 'bc1'.`
|
|
}
|
|
})
|
|
document.querySelectorAll('sm-input[data-private-key]').forEach(input => input.customValidation = (value) => {
|
|
return {
|
|
isValid: floCrypto.getPubKeyHex(value),
|
|
errorText: `Invalid private key. It's a long string of random characters usually starting with 'L' or 'R'.`
|
|
}
|
|
})
|
|
document.addEventListener('keyup', (e) => {
|
|
if (e.key === 'Escape') {
|
|
closePopup()
|
|
}
|
|
})
|
|
document.addEventListener('copy', () => {
|
|
notify('copied', 'success')
|
|
})
|
|
document.addEventListener("pointerdown", (e) => {
|
|
if (e.target.closest("button:not(:disabled), .interactive:not(:disabled)")) {
|
|
createRipple(e, e.target.closest("button, .interactive"));
|
|
}
|
|
});
|
|
});
|
|
function createRipple(event, target) {
|
|
const circle = document.createElement("span");
|
|
const diameter = Math.max(target.clientWidth, target.clientHeight);
|
|
const radius = diameter / 2;
|
|
const targetDimensions = target.getBoundingClientRect();
|
|
circle.style.width = circle.style.height = `${diameter}px`;
|
|
circle.style.left = `${event.clientX - (targetDimensions.left + radius)}px`;
|
|
circle.style.top = `${event.clientY - (targetDimensions.top + radius)}px`;
|
|
circle.classList.add("ripple");
|
|
const rippleAnimation = circle.animate(
|
|
[
|
|
{
|
|
opacity: 1,
|
|
transform: `scale(0)`
|
|
},
|
|
{
|
|
transform: "scale(4)",
|
|
opacity: 0,
|
|
},
|
|
],
|
|
{
|
|
duration: 600,
|
|
fill: "forwards",
|
|
easing: "ease-out",
|
|
}
|
|
);
|
|
target.append(circle);
|
|
rippleAnimation.onfinish = () => {
|
|
circle.remove();
|
|
};
|
|
}
|
|
function buttonLoader(id, show) {
|
|
const button = typeof id === 'string' ? document.getElementById(id) : id;
|
|
button.disabled = show;
|
|
const animOptions = {
|
|
duration: 200,
|
|
fill: 'forwards',
|
|
easing: 'ease'
|
|
}
|
|
if (show) {
|
|
button.parentNode.append(document.createElement('sm-spinner'))
|
|
button.animate([
|
|
{
|
|
clipPath: 'circle(100%)',
|
|
},
|
|
{
|
|
clipPath: 'circle(0)',
|
|
},
|
|
], animOptions)
|
|
} else {
|
|
button.getAnimations().forEach(anim => anim.cancel())
|
|
const potentialTarget = button.parentNode.querySelector('sm-spinner')
|
|
if (potentialTarget) potentialTarget.remove();
|
|
}
|
|
}
|
|
let isMobileView = false
|
|
const mobileQuery = window.matchMedia('(max-width: 40rem)')
|
|
function handleMobileChange(e) {
|
|
isMobileView = e.matches
|
|
}
|
|
mobileQuery.addEventListener('change', handleMobileChange)
|
|
|
|
handleMobileChange(mobileQuery)
|
|
const slideInLeft = [
|
|
{
|
|
opacity: 0,
|
|
transform: 'translateX(1.5rem)'
|
|
},
|
|
{
|
|
opacity: 1,
|
|
transform: 'translateX(0)'
|
|
}
|
|
]
|
|
const slideOutLeft = [
|
|
{
|
|
opacity: 1,
|
|
transform: 'translateX(0)'
|
|
},
|
|
{
|
|
opacity: 0,
|
|
transform: 'translateX(-1.5rem)'
|
|
},
|
|
]
|
|
const slideInRight = [
|
|
{
|
|
opacity: 0,
|
|
transform: 'translateX(-1.5rem)'
|
|
},
|
|
{
|
|
opacity: 1,
|
|
transform: 'translateX(0)'
|
|
}
|
|
]
|
|
const slideOutRight = [
|
|
{
|
|
opacity: 1,
|
|
transform: 'translateX(0)'
|
|
},
|
|
{
|
|
opacity: 0,
|
|
transform: 'translateX(1.5rem)'
|
|
},
|
|
]
|
|
const slideInDown = [
|
|
{
|
|
opacity: 0,
|
|
transform: 'translateY(-1.5rem)'
|
|
},
|
|
{
|
|
opacity: 1,
|
|
transform: 'translateY(0)'
|
|
},
|
|
]
|
|
const slideOutUp = [
|
|
{
|
|
opacity: 1,
|
|
transform: 'translateY(0)'
|
|
},
|
|
{
|
|
opacity: 0,
|
|
transform: 'translateY(-1.5rem)'
|
|
},
|
|
]
|
|
</script>
|
|
<script type="text/javascript">
|
|
function togglePrivateKeyVisibility(input) {
|
|
const target = input.closest('sm-input')
|
|
target.type = target.type === 'password' ? 'text' : 'password';
|
|
target.focusIn()
|
|
}
|
|
function generateNewAddress() {
|
|
|
|
}
|
|
</script>
|
|
<script type="text/javascript">
|
|
//This library uses API provided by chain.so (https://chain.so/)
|
|
const URL = "https://blockchain.info/";
|
|
|
|
const DUST_AMT = 546,
|
|
MIN_FEE_UPDATE = 219;
|
|
|
|
const fetch_api = function (api, json_res = true) {
|
|
return new Promise((resolve, reject) => {
|
|
console.debug(URL + api);
|
|
fetch(URL + api).then(response => {
|
|
if (response.ok) {
|
|
(json_res ? response.json() : response.text())
|
|
.then(result => resolve(result))
|
|
.catch(error => reject(error))
|
|
} else {
|
|
response.json()
|
|
.then(result => reject(result))
|
|
.catch(error => reject(error))
|
|
}
|
|
}).catch(error => reject(error))
|
|
})
|
|
};
|
|
|
|
const SATOSHI_IN_BTC = 1e8;
|
|
|
|
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)))
|
|
.catch(error => reject(error));
|
|
else
|
|
reject(response);
|
|
}).catch(error => reject(error))
|
|
})
|
|
}
|
|
|
|
const broadcastTx = rawTxHex => new Promise((resolve, reject) => {
|
|
let url = 'https://coinb.in/api/?uid=1&key=12345678901234567890123456789012&setmodule=bitcoin&request=sendrawtransaction';
|
|
fetch(url, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
},
|
|
body: "rawtx=" + rawTxHex
|
|
}).then(response => {
|
|
response.text().then(resultText => {
|
|
let r = resultText.match(/<result>.*<\/result>/);
|
|
if (!r)
|
|
reject(resultText);
|
|
else {
|
|
r = r.pop().replace('<result>', '').replace('</result>', '');
|
|
if (r == '1') {
|
|
let txid = resultText.match(/<txid>.*<\/txid>/).pop().replace('<txid>', '').replace('</txid>', '');
|
|
resolve(txid);
|
|
} else if (r == '0') {
|
|
let error = resultText.match(/<response>.*<\/response>/).pop().replace('<response>', '').replace('</response>', '');
|
|
reject(decodeURIComponent(error.replace(/\+/g, " ")));
|
|
} else reject(resultText);
|
|
}
|
|
}).catch(error => reject(error))
|
|
}).catch(error => reject(error))
|
|
});
|
|
function getTaprootAddress(wif) {
|
|
if (!wif)
|
|
wif = coinjs.newKeys().wif
|
|
const { privkey } = coinjs.wif2privkey(wif)
|
|
const privKey_arrayform = hex.decode(privkey)
|
|
const pubS = secp256k1_schnorr.getPublicKey(privKey_arrayform);
|
|
const taproot = btc.p2tr(pubS);
|
|
return {
|
|
taproot,
|
|
privKey: wif
|
|
}
|
|
}
|
|
|
|
|
|
const BASE_TX_SIZE = 12,
|
|
BASE_INPUT_SIZE = 41,
|
|
LEGACY_INPUT_SIZE = 107,
|
|
BECH32_INPUT_SIZE = 27,
|
|
SEGWIT_INPUT_SIZE = 59,
|
|
BECH32M_INPUT_SIZE = 39, // Check this later
|
|
BASE_OUTPUT_SIZE = 9,
|
|
LEGACY_OUTPUT_SIZE = 25,
|
|
BECH32_OUTPUT_SIZE = 23,
|
|
SEGWIT_OUTPUT_SIZE = 23,
|
|
BECH32M_OUTPUT_SIZE = 35; // Check this later
|
|
|
|
function _sizePerInput(addr) {
|
|
switch (coinjs.addressDecode(addr).type) {
|
|
case "standard":
|
|
return BASE_INPUT_SIZE + LEGACY_INPUT_SIZE;
|
|
case "bech32":
|
|
return BASE_INPUT_SIZE + BECH32_INPUT_SIZE;
|
|
case "bech32m":
|
|
return BASE_INPUT_SIZE + BECH32M_INPUT_SIZE;
|
|
default:
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function _sizePerOutput(addr) {
|
|
switch (coinjs.addressDecode(addr).type) {
|
|
case "standard":
|
|
return BASE_OUTPUT_SIZE + LEGACY_OUTPUT_SIZE;
|
|
case "bech32":
|
|
return BASE_OUTPUT_SIZE + BECH32_OUTPUT_SIZE;
|
|
case "bech32m":
|
|
return BASE_OUTPUT_SIZE + BECH32M_OUTPUT_SIZE;
|
|
default:
|
|
return null;
|
|
}
|
|
}
|
|
async function createTx(senderPrivateKey, receiver, amount, fee) {
|
|
try {
|
|
const { taproot: { address, script } } = getTaprootAddress(senderPrivateKey)
|
|
const amountInSat = BigInt(util.BTC_to_Sat(amount))
|
|
const opts = {};
|
|
const tx = new btc.Transaction(opts);
|
|
|
|
await addUTXOs(tx, taproot, [address], util.BTC_to_Sat(amount))
|
|
|
|
tx.addOutputAddress(receiver, amountInSat);
|
|
|
|
tx.sign(privKey_arrayform, undefined, new Uint8Array(32));
|
|
|
|
tx.finalize()
|
|
console.log(tx.hex);
|
|
} catch (e) {
|
|
console.error(e)
|
|
}
|
|
}
|
|
const testTaproot = 'bc1p05whkacavgmh77pgsr7v5k4tyg28x3pqyjanfnjkzzdngqur4yks39w8zk'
|
|
function addUTXOs(tx, taproot, senders = [testTaproot], required_amount, fee_rate, rec_args = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
required_amount = parseFloat(required_amount.toFixed(8));
|
|
if (typeof rec_args.n === "undefined") {
|
|
rec_args.n = 0;
|
|
rec_args.input_size = 0;
|
|
rec_args.input_amount = 0;
|
|
}
|
|
if (required_amount <= 0)
|
|
return resolve({
|
|
input_size: rec_args.input_size,
|
|
input_amount: rec_args.input_amount,
|
|
change_amount: required_amount * -1 //required_amount will be -ve of change_amount
|
|
});
|
|
else if (rec_args.n >= senders.length)
|
|
return reject("Insufficient Balance");
|
|
let addr = senders[rec_args.n];
|
|
let size_per_input = _sizePerInput(addr);
|
|
fetch_api(`unspent?active=${addr}`).then(result => {
|
|
let utxos = result.unspent_outputs;
|
|
// console.debug("add-utxo", addr, required_amount, utxos);
|
|
for (let i = 0; i < utxos.length && required_amount > 0; i++) {
|
|
if (!utxos[i].confirmations) //ignore unconfirmed utxo
|
|
continue;
|
|
const { tx_hash, tx_index, value } = utxos[i];
|
|
// tx.addinput(utxos[i].tx_hash_big_endian, utxos[i].tx_output_n, script, 0xfffffffd /*sequence*/); //0xfffffffd for Replace-by-fee
|
|
const input = { txid: tx_hash, index: tx_index, script: taproot.script, amount: value }
|
|
tx.addInput({ ...input, ...taproot, witnessUtxo: { script: input.script, amount: input.amount }, });
|
|
|
|
//update track values
|
|
rec_args.input_size += size_per_input; // Adjust input size calculation
|
|
rec_args.input_amount += util.Sat_to_BTC(utxos[i].value);
|
|
required_amount -= util.Sat_to_BTC(utxos[i].value);
|
|
if (fee_rate) //automatic fee calculation (dynamic)
|
|
required_amount += size_per_input * fee_rate;
|
|
}
|
|
rec_args.n += 1;
|
|
addUTXOs(tx, taproot, senders, required_amount, fee_rate, rec_args)
|
|
.then(result => resolve(result))
|
|
.catch(error => reject(error))
|
|
}).catch(error => reject(error))
|
|
});
|
|
}
|
|
</script>
|
|
</body>
|
|
|
|
</html> |