Added ability to check eth address balance directly
This commit is contained in:
parent
8df66c737d
commit
650207bacc
111
index.html
111
index.html
@ -445,6 +445,16 @@
|
||||
errorText: `Invalid private key.<br> It usually starts with "L" or "R".`
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: '#check_balance_input',
|
||||
customValidation: (value) => {
|
||||
if (!value) return { isValid: false, errorText: 'Please enter a private key or eth address' }
|
||||
return {
|
||||
isValid: floCrypto.getPubKeyHex(value) || ethOperator.isValidAddress(value),
|
||||
errorText: `Invalid private key or eth address.<br> It usually starts with "L" or "R" or "0x"`
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -454,7 +464,7 @@
|
||||
routingEnd(state) {
|
||||
let { page } = state
|
||||
if (!page)
|
||||
page = 'search'
|
||||
page = 'balance'
|
||||
if (page !== 'send') {
|
||||
taprootScriptTxDetails = {}
|
||||
}
|
||||
@ -569,8 +579,8 @@
|
||||
</h2>
|
||||
<sm-form oninvalid="handleInvalidSearch()">
|
||||
<div id="input_wrapper">
|
||||
<sm-input id="private_key_input" class="password-field flex-1" placeholder="FLO/BTC private key"
|
||||
type="password" data-private-key animate required>
|
||||
<sm-input id="check_balance_input" class="password-field flex-1" placeholder="FLO/BTC private key or Ethereum address"
|
||||
type="password" animate 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
|
||||
@ -580,39 +590,13 @@
|
||||
</label>
|
||||
</sm-input>
|
||||
<div class="multi-state-button">
|
||||
<button id="check_balance_button" class="button button--primary h-100 w-100" type="submit" onclick="checkBalance()" disabled>
|
||||
<button id="check_balance_button" class="button button--primary h-100 w-100" type="submit" onclick=${() => checkBalance()} disabled>
|
||||
Check balance
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</sm-form>
|
||||
<div id="eth_balance_wrapper" class="grid gap-2 hidden">
|
||||
<div class="grid">
|
||||
<div class="label">ETH address</div>
|
||||
<sm-copy id="eth_address"></sm-copy>
|
||||
</div>
|
||||
<div class="grid">
|
||||
<div class="label">FLO address</div>
|
||||
<sm-copy id="flo_address"></sm-copy>
|
||||
</div>
|
||||
<div class="grid gap-1">
|
||||
<h4>Balance</h4>
|
||||
<ul id="eth_address_balance" class="flex flex-direction-column gap-0-5">
|
||||
<li class="flex align-center space-between">
|
||||
<p>Ether</p>
|
||||
<b id="ether_balance">0</b>
|
||||
</li>
|
||||
<li class="flex align-center space-between">
|
||||
<p>USDC</p>
|
||||
<b id="usdc_balance">0</b>
|
||||
</li>
|
||||
<li class="flex align-center space-between">
|
||||
<p>USDT</p>
|
||||
<b id="usdt_balance">0</b>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="eth_balance_wrapper" class="grid gap-2 hidden"></div>
|
||||
</section>
|
||||
`)
|
||||
if (window.ethereum && !(window.currentChainId && window.currentChainId === '0x1')) {
|
||||
@ -663,10 +647,13 @@
|
||||
const { ethAddress } = contacts[floAddress]
|
||||
renderedContacts.push(html`
|
||||
<li class="contact" .dataset=${{ floAddress, ethAddress }}>
|
||||
<sm-chips onchange=${e => e.target.closest('.contact').querySelector('sm-copy').value = e.target.value}>
|
||||
<sm-chip value=${floAddress} selected>FLO</sm-chip>
|
||||
<sm-chip value=${ethAddress}>ETH</sm-chip>
|
||||
</sm-chips>
|
||||
${floAddress === ethAddress ? html`
|
||||
`: html`
|
||||
<sm-chips onchange=${e => e.target.closest('.contact').querySelector('sm-copy').value = e.target.value}>
|
||||
<sm-chip value=${floAddress} selected>FLO</sm-chip>
|
||||
<sm-chip value=${ethAddress}>ETH</sm-chip>
|
||||
</sm-chips>
|
||||
`}
|
||||
<sm-copy value="${floAddress}"></sm-copy>
|
||||
<div class="flex align-center space-between gap-0-5">
|
||||
<button class="button button--small" onclick=${() => deleteContact(floAddress)}>
|
||||
@ -683,13 +670,17 @@
|
||||
}
|
||||
function checkBalance(ethAddress, floAddress) {
|
||||
if (!ethAddress) {
|
||||
const keyToConvert = document.querySelector('[data-private-key]').value.trim()
|
||||
if (/^[0-9a-fA-F]{64}$/.test(keyToConvert)) {
|
||||
keyToConvert = coinjs.privkey2wif(keyToConvert)
|
||||
const keyToConvert = document.querySelector('#check_balance_input').value.trim()
|
||||
if (ethOperator.isValidAddress(keyToConvert)) {
|
||||
ethAddress = keyToConvert
|
||||
} else {
|
||||
if (/^[0-9a-fA-F]{64}$/.test(keyToConvert)) {
|
||||
keyToConvert = coinjs.privkey2wif(keyToConvert)
|
||||
}
|
||||
const ethPrivateKey = coinjs.wif2privkey(keyToConvert).privkey;
|
||||
ethAddress = floEthereum.ethAddressFromPrivateKey(ethPrivateKey)
|
||||
floAddress = floCrypto.getFloID(keyToConvert)
|
||||
}
|
||||
const ethPrivateKey = coinjs.wif2privkey(keyToConvert).privkey;
|
||||
ethAddress = floEthereum.ethAddressFromPrivateKey(ethPrivateKey)
|
||||
floAddress = floCrypto.getFloID(keyToConvert)
|
||||
}
|
||||
if (!ethAddress) return
|
||||
buttonLoader('check_balance_button', true)
|
||||
@ -699,21 +690,45 @@
|
||||
ethOperator.getTokenBalance(ethAddress, 'usdt')
|
||||
])
|
||||
.then(([etherBalance, usdcBalance, usdtBalance]) => {
|
||||
compactIDB.readData('contacts', floAddress).then(result => {
|
||||
compactIDB.readData('contacts', floAddress || ethAddress).then(result => {
|
||||
if (result) return
|
||||
compactIDB.addData('contacts', {
|
||||
ethAddress,
|
||||
}, floAddress).then(() => {
|
||||
}, floAddress || ethAddress).then(() => {
|
||||
renderSearchedAddressList()
|
||||
}).catch((error) => {
|
||||
console.error(error)
|
||||
})
|
||||
})
|
||||
getRef('eth_address').value = ethAddress
|
||||
getRef('flo_address').value = floAddress
|
||||
getRef('ether_balance').textContent = `${etherBalance} ETH`
|
||||
getRef('usdc_balance').textContent = `${usdcBalance} USDC`
|
||||
getRef('usdt_balance').textContent = `${usdtBalance} USDT`
|
||||
renderElem(getRef('eth_balance_wrapper'), html`
|
||||
<div class="grid">
|
||||
<div class="label">ETH address</div>
|
||||
<sm-copy id="eth_address" value=${ethAddress}></sm-copy>
|
||||
</div>
|
||||
${floAddress && floAddress !== ethAddress ? html`
|
||||
<div class="grid">
|
||||
<div class="label">FLO address</div>
|
||||
<sm-copy id="flo_address" value=${floAddress}></sm-copy>
|
||||
</div>
|
||||
`: ''}
|
||||
<div class="grid gap-1">
|
||||
<h4>Balance</h4>
|
||||
<ul id="eth_address_balance" class="flex flex-direction-column gap-0-5">
|
||||
<li class="flex align-center space-between">
|
||||
<p>Ether</p>
|
||||
<b id="ether_balance">${etherBalance} ETH</b>
|
||||
</li>
|
||||
<li class="flex align-center space-between">
|
||||
<p>USDC</p>
|
||||
<b id="usdc_balance">${usdcBalance} USDC</b>
|
||||
</li>
|
||||
<li class="flex align-center space-between">
|
||||
<p>USDT</p>
|
||||
<b id="usdt_balance">${usdtBalance} USDT</b>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
`)
|
||||
getRef('eth_balance_wrapper').classList.remove('hidden')
|
||||
getRef('eth_balance_wrapper').animate([
|
||||
{
|
||||
|
||||
@ -1,19 +1,435 @@
|
||||
(function (EXPORTS) { //btcOperator v1.1.3c
|
||||
(function (EXPORTS) { //btcOperator v1.2.10
|
||||
/* BTC Crypto and API Operator */
|
||||
const btcOperator = EXPORTS;
|
||||
const SATOSHI_IN_BTC = 1e8;
|
||||
|
||||
const util = btcOperator.util = {};
|
||||
|
||||
util.Sat_to_BTC = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8));
|
||||
util.BTC_to_Sat = value => parseInt(value * SATOSHI_IN_BTC);
|
||||
|
||||
const checkIfTor = btcOperator.checkIfTor = () => {
|
||||
return fetch('https://check.torproject.org/api/ip')
|
||||
.then(res => res.json())
|
||||
.then(res => {
|
||||
return res.IsTor
|
||||
}).catch(e => {
|
||||
console.error(e)
|
||||
return false
|
||||
})
|
||||
}
|
||||
let isTor = false;
|
||||
checkIfTor().then(result => isTor = result);
|
||||
|
||||
async function post(url, data, { asText = false } = {}) {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
mode: 'no-cors',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
})
|
||||
if (response.ok) {
|
||||
return asText ? await response.text() : await response.json()
|
||||
} else {
|
||||
throw response
|
||||
}
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: some APIs may not support all functions properly hence they are omitted
|
||||
const APIs = btcOperator.APIs = [
|
||||
{
|
||||
url: 'https://api.blockcypher.com/v1/btc/main/',
|
||||
name: 'Blockcypher',
|
||||
balance({ addr }) {
|
||||
return fetch_api(`addrs/${addr}/balance`, { url: this.url })
|
||||
.then(result => util.Sat_to_BTC(result.balance))
|
||||
},
|
||||
async block({ id }) {
|
||||
try {
|
||||
let block = await fetch_api(`blocks/${id}`, { url: this.url })
|
||||
return formatBlock(block)
|
||||
} catch (e) {
|
||||
console.log(e)
|
||||
}
|
||||
},
|
||||
async broadcast({ rawTxHex, url }) {
|
||||
try {
|
||||
const result = await post(`${url || this.url}pushtx`, { tx: rawTxHex })
|
||||
return result.hash
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
url: 'https://blockstream.info/api/',
|
||||
name: 'Blockstream',
|
||||
hasOnion: true,
|
||||
onionUrl: `http://explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion/api/`,
|
||||
balance({ addr, url }) {
|
||||
return fetch_api(`address/${addr}/utxo`, { url: url || this.url })
|
||||
.then(result => {
|
||||
const balance = result.reduce((t, u) => t + u.value, 0)
|
||||
return util.Sat_to_BTC(balance)
|
||||
})
|
||||
},
|
||||
latestBlock() {
|
||||
return fetch_api(`blocks/tip/height`, { url: this.url })
|
||||
},
|
||||
tx({ txid, url }) {
|
||||
return fetch_api(`tx/${txid}`, { url: url || this.url })
|
||||
.then(result => formatTx(result))
|
||||
},
|
||||
txHex({ txid, url }) {
|
||||
return fetch_api(`tx/${txid}/hex`, { url: url || this.url, asText: true })
|
||||
},
|
||||
txs({ addr, url, ...args }) {
|
||||
let queryParams = Object.entries(args).map(([key, value]) => `${key}=${value}`).join('&')
|
||||
if (queryParams)
|
||||
queryParams = '?' + queryParams
|
||||
return fetch_api(`address/${addr}/txs${queryParams}`, { url: url || this.url })
|
||||
},
|
||||
async block({ id, url }) {
|
||||
// if id is hex string then it is block hash
|
||||
try {
|
||||
let blockHash = id
|
||||
if (!/^[0-9a-f]{64}$/i.test(id))
|
||||
blockHash = await fetch_api(`block-height/${id}`, { url: url || this.url, asText: true })
|
||||
const block = await fetch_api(`block/${blockHash}`, { url: url || this.url })
|
||||
return formatBlock(block)
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
},
|
||||
async broadcast({ rawTxHex, url }) {
|
||||
return post(`${url || this.url}tx`, { tx: rawTxHex }, { asText: true })
|
||||
}
|
||||
},
|
||||
{
|
||||
url: 'https://mempool.space/api/',
|
||||
name: 'Mempool',
|
||||
balance({ addr }) {
|
||||
return fetch_api(`address/${addr}`, { url: this.url })
|
||||
.then(result => util.Sat_to_BTC(result.chain_stats.funded_txo_sum - result.chain_stats.spent_txo_sum))
|
||||
},
|
||||
latestBlock() {
|
||||
return fetch_api(`blocks/tip/height`, { url: this.url })
|
||||
},
|
||||
tx({ txid }) {
|
||||
return fetch_api(`tx/${txid}`, { url: this.url })
|
||||
.then(result => formatTx(result))
|
||||
|
||||
},
|
||||
txHex({ txid }) {
|
||||
return fetch_api(`tx/${txid}/hex`, { url: this.url, asText: true })
|
||||
},
|
||||
txs({ addr, ...args }) {
|
||||
let queryParams = Object.entries(args).map(([key, value]) => `${key}=${value}`).join('&')
|
||||
if (queryParams)
|
||||
queryParams = '?' + queryParams
|
||||
return fetch_api(`address/${addr}/txs${queryParams}`, { url: this.url })
|
||||
},
|
||||
async block({ id }) {
|
||||
// if id is hex string then it is block hash
|
||||
try {
|
||||
let blockHash = id
|
||||
if (!/^[0-9a-f]{64}$/i.test(id))
|
||||
blockHash = await fetch_api(`block-height/${id}`, { url: this.url, asText: true })
|
||||
const block = await fetch_api(`block/${blockHash}`, { url: this.url })
|
||||
return formatBlock(block)
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
},
|
||||
async broadcast({ rawTxHex, url }) {
|
||||
return post(`${url || this.url}tx`, { tx: rawTxHex }, { asText: true })
|
||||
}
|
||||
},
|
||||
{
|
||||
url: 'https://blockchain.info/',
|
||||
name: 'Blockchain',
|
||||
balance({ addr }) {
|
||||
return fetch_api(`q/addressbalance/${addr}`, { url: this.url })
|
||||
.then(result => util.Sat_to_BTC(result))
|
||||
},
|
||||
unspent({ addr, allowUnconfirmedUtxos = false }) {
|
||||
return fetch_api(`unspent?active=${addr}`, { url: this.url })
|
||||
.then(result => formatUtxos(result.unspent_outputs, allowUnconfirmedUtxos))
|
||||
},
|
||||
tx({ txid }) {
|
||||
return fetch_api(`rawtx/${txid}`, { url: this.url })
|
||||
.then(result => formatTx(result))
|
||||
},
|
||||
txHex({ txid }) {
|
||||
return fetch_api(`rawtx/${txid}?format=hex`, { url: this.url, asText: true })
|
||||
},
|
||||
txs({ addr, ...args }) {
|
||||
let queryParams = Object.entries(args).map(([key, value]) => `${key}=${value}`).join('&')
|
||||
if (queryParams)
|
||||
queryParams = '?' + queryParams
|
||||
return fetch_api(`rawaddr/${addr}${queryParams}`, { url: this.url })
|
||||
.then(result => result.txs)
|
||||
},
|
||||
latestBlock() {
|
||||
return fetch_api(`q/getblockcount`, { url: this.url })
|
||||
},
|
||||
async block({ id }) {
|
||||
try {
|
||||
let block
|
||||
// if id is hex string then it is block hash
|
||||
if (/^[0-9a-f]{64}$/i.test(id))
|
||||
block = await fetch_api(`rawblock/${id}`, { url: this.url })
|
||||
else {
|
||||
const result = await fetch_api(`block-height/${id}?format=json`, { url: this.url })
|
||||
block = result.blocks[0]
|
||||
}
|
||||
return formatBlock(block)
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
},
|
||||
async blockTxs({ id }) {
|
||||
try {
|
||||
let block
|
||||
// if id is hex string then it is block hash
|
||||
if (/^[0-9a-f]{64}$/i.test(id))
|
||||
block = await fetch_api(`rawblock/${id}`, { url: this.url })
|
||||
else {
|
||||
const result = await fetch_api(`block-height/${id}?format=json`, { url: this.url })
|
||||
block = result.blocks[0]
|
||||
}
|
||||
return block.tx
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
url: 'https://coinb.in/api/?uid=1&key=12345678901234567890123456789012&setmodule=bitcoin&request=sendrawtransaction',
|
||||
name: 'Coinb.in',
|
||||
broadcast({ rawTxHex }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
fetch(this.url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
body: "rawtx=" + rawTxHex
|
||||
}).then(response => {
|
||||
console.log(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
|
||||
if (resultText.includes('<message>')) {
|
||||
error = resultText.match(/<message>.*<\/message>/).pop().replace('<message>', '').replace('</message>', '');
|
||||
} else {
|
||||
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))
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
btcOperator.util.format = {} // functions to homogenize API results
|
||||
const formatBlock = btcOperator.util.format.block = async (block) => {
|
||||
try {
|
||||
const { height, hash, id, time, timestamp, mrkl_root, merkle_root, prev_block, next_block, size } = block;
|
||||
const details = {
|
||||
height,
|
||||
hash: hash || id,
|
||||
time: (time || timestamp) * 1000,
|
||||
merkle_root: merkle_root || mrkl_root,
|
||||
size,
|
||||
}
|
||||
if (prev_block)
|
||||
details.prev_block = prev_block
|
||||
if (next_block)
|
||||
details.next_block = next_block[0]
|
||||
return details
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
const formatUtxos = btcOperator.util.format.utxos = async (utxos, allowUnconfirmedUtxos = false) => {
|
||||
try {
|
||||
if (!allowUnconfirmedUtxos && !utxos || !Array.isArray(utxos))
|
||||
throw {
|
||||
message: "No utxos found",
|
||||
code: 1000 //error code for when issue is not from API but situational (like no utxos found)
|
||||
}
|
||||
return utxos.map(utxo => {
|
||||
const { tx_hash, tx_hash_big_endian, txid, tx_output_n, vout, value, script, confirmations, status: { confirmed } = {} } = utxo;
|
||||
return {
|
||||
confirmations: confirmations || confirmed,
|
||||
tx_hash_big_endian: tx_hash_big_endian || tx_hash || txid,
|
||||
tx_output_n: tx_output_n || vout,
|
||||
value,
|
||||
script
|
||||
}
|
||||
})
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
const formatTx = btcOperator.util.format.tx = async (tx) => {
|
||||
try {
|
||||
let { txid, hash, time, block_height, fee, fees, received,
|
||||
confirmed, size, double_spend, block_hash, confirmations,
|
||||
status: { block_height: statusBlockHeight, block_hash: statusBlockHash, block_time } = {}
|
||||
} = tx;
|
||||
if ((block_height || statusBlockHeight) && confirmations === undefined || confirmations === null) {
|
||||
const latestBlock = await multiApi('latestBlock');
|
||||
confirmations = latestBlock - (block_height || statusBlockHeight);
|
||||
}
|
||||
const inputs = tx.vin || tx.inputs;
|
||||
const outputs = tx.vout || tx.outputs || tx.out;
|
||||
return {
|
||||
hash: hash || txid,
|
||||
size: size,
|
||||
fee: fee || fees,
|
||||
double_spend,
|
||||
time: (time * 1000) || new Date(confirmed || received).getTime() || block_time * 1000 || Date.now(),
|
||||
block_height: block_height || statusBlockHeight,
|
||||
block_hash: block_hash || statusBlockHash,
|
||||
confirmations,
|
||||
inputs: inputs.map(input => {
|
||||
return {
|
||||
index: input.n || input.output_index || input.vout,
|
||||
prev_out: {
|
||||
addr: input.prev_out?.addr || input.addresses?.[0] || input.prev_out?.address || input.addr || input.prevout.scriptpubkey_address,
|
||||
value: input.prev_out?.value || input.output_value || input.prevout.value,
|
||||
},
|
||||
}
|
||||
}),
|
||||
out: outputs.map(output => {
|
||||
return {
|
||||
addr: output.scriptpubkey_address || output.addresses?.[0] || output.scriptpubkey_address || output.addr,
|
||||
value: output.value || output.scriptpubkey_value,
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
const multiApi = btcOperator.multiApi = async (fnName, { index = 0, ...args } = {}) => {
|
||||
try {
|
||||
let triedOnion = false;
|
||||
while (index < APIs.length) {
|
||||
if (!APIs[index][fnName] || (APIs[index].coolDownTime && APIs[index].coolDownTime > new Date().getTime())) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
return await APIs[index][fnName](args);
|
||||
}
|
||||
if (isTor && !triedOnion) {
|
||||
triedOnion = true;
|
||||
index = 0;
|
||||
while (index < APIs.length) {
|
||||
if (!APIs[index].hasOnion || (APIs[index].coolDownTime && APIs[index].coolDownTime > new Date().getTime())) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
return await multiApi(fnName, { index: index + 1, ...args, url: APIs[index].onionUrl });
|
||||
}
|
||||
}
|
||||
throw "No API available"
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
APIs[index].coolDownTime = new Date().getTime() + 1000 * 60 * 10; // 10 minutes
|
||||
return multiApi(fnName, { index: index + 1, ...args });
|
||||
}
|
||||
};
|
||||
|
||||
function parseTx(tx, addressOfTx) {
|
||||
const { txid, hash, time, block_height, inputs, outputs, out, vin, vout, fee, fees, received, confirmed, status: { block_height: statusBlockHeight, block_time } = {} } = tx;
|
||||
let parsedTx = {
|
||||
txid: hash || txid,
|
||||
time: (time * 1000) || new Date(confirmed || received).getTime() || block_time * 1000 || Date.now(),
|
||||
block: block_height || statusBlockHeight,
|
||||
}
|
||||
//sender list
|
||||
parsedTx.tx_senders = {};
|
||||
(inputs || vin).forEach(i => {
|
||||
const address = i.prev_out?.addr || i.addresses?.[0] || i.prev_out?.address || i.addr || i.prevout.scriptpubkey_address;
|
||||
const value = i.prev_out?.value || i.output_value || i.value || i.prevout.value;
|
||||
if (address in parsedTx.tx_senders)
|
||||
parsedTx.tx_senders[address] += value;
|
||||
else parsedTx.tx_senders[address] = value;
|
||||
});
|
||||
parsedTx.tx_input_value = 0;
|
||||
for (let senderAddr in parsedTx.tx_senders) {
|
||||
let val = parsedTx.tx_senders[senderAddr];
|
||||
parsedTx.tx_senders[senderAddr] = util.Sat_to_BTC(val);
|
||||
parsedTx.tx_input_value += val;
|
||||
}
|
||||
parsedTx.tx_input_value = util.Sat_to_BTC(parsedTx.tx_input_value);
|
||||
//receiver list
|
||||
parsedTx.tx_receivers = {};
|
||||
(outputs || out || vout).forEach(o => {
|
||||
const address = o.scriptpubkey_address || o.addresses?.[0] || o.scriptpubkey_address || o.addr;
|
||||
const value = o.value || o.scriptpubkey_value;
|
||||
if (address in parsedTx.tx_receivers)
|
||||
parsedTx.tx_receivers[address] += value;
|
||||
else parsedTx.tx_receivers[address] = value;
|
||||
});
|
||||
parsedTx.tx_output_value = 0;
|
||||
for (let receiverAddr in parsedTx.tx_receivers) {
|
||||
let val = parsedTx.tx_receivers[receiverAddr];
|
||||
parsedTx.tx_receivers[receiverAddr] = util.Sat_to_BTC(val);
|
||||
parsedTx.tx_output_value += val;
|
||||
}
|
||||
parsedTx.tx_output_value = util.Sat_to_BTC(parsedTx.tx_output_value);
|
||||
// tx fee
|
||||
parsedTx.tx_fee = util.Sat_to_BTC(fee || fees || (parsedTx.tx_input_value - parsedTx.tx_output_value));
|
||||
//detect tx type (in, out, self)
|
||||
if (Object.keys(parsedTx.tx_receivers).length === 1 && Object.keys(parsedTx.tx_senders).length === 1 && Object.keys(parsedTx.tx_senders)[0] === Object.keys(parsedTx.tx_receivers)[0]) {
|
||||
parsedTx.type = 'self';
|
||||
parsedTx.amount = parsedTx.tx_receivers[addressOfTx];
|
||||
parsedTx.address = addressOfTx;
|
||||
} else if (addressOfTx in parsedTx.tx_senders && Object.keys(parsedTx.tx_receivers).some(addr => addr !== addressOfTx)) {
|
||||
parsedTx.type = 'out';
|
||||
parsedTx.receiver = Object.keys(parsedTx.tx_receivers).filter(addr => addr != addressOfTx);
|
||||
parsedTx.amount = parsedTx.receiver.reduce((t, addr) => t + parsedTx.tx_receivers[addr], 0) + parsedTx.tx_fee;
|
||||
} else {
|
||||
parsedTx.type = 'in';
|
||||
parsedTx.sender = Object.keys(parsedTx.tx_senders).filter(addr => addr != addressOfTx);
|
||||
parsedTx.amount = parsedTx.tx_receivers[addressOfTx];
|
||||
}
|
||||
return parsedTx;
|
||||
}
|
||||
|
||||
//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 = btcOperator.fetch = function (api, json_res = true) {
|
||||
const fetch_api = btcOperator.fetch = function (api, { asText = false, url = 'https://blockchain.info/' } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.debug(URL + api);
|
||||
fetch(URL + api).then(response => {
|
||||
console.debug(url + api);
|
||||
fetch(url + api).then(response => {
|
||||
if (response.ok) {
|
||||
(json_res ? response.json() : response.text())
|
||||
(asText ? response.text() : response.json())
|
||||
.then(result => resolve(result))
|
||||
.catch(error => reject(error))
|
||||
} else {
|
||||
@ -25,14 +441,7 @@
|
||||
})
|
||||
};
|
||||
|
||||
const SATOSHI_IN_BTC = 1e8;
|
||||
|
||||
const util = btcOperator.util = {};
|
||||
|
||||
util.Sat_to_BTC = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8));
|
||||
util.BTC_to_Sat = value => parseInt(value * SATOSHI_IN_BTC);
|
||||
|
||||
const get_fee_rate = btcOperator.getFeeRate = () => {
|
||||
function get_fee_rate() {
|
||||
return new Promise((resolve, reject) => {
|
||||
fetch('https://api.blockchain.info/mempool/fees').then(response => {
|
||||
if (response.ok)
|
||||
@ -46,6 +455,14 @@
|
||||
}
|
||||
|
||||
const broadcastTx = btcOperator.broadcastTx = rawTxHex => new Promise((resolve, reject) => {
|
||||
console.log('txHex:', rawTxHex)
|
||||
// return multiApi('broadcast', { rawTxHex })
|
||||
// .then(result => {
|
||||
// resolve(result)
|
||||
// })
|
||||
// .catch(error => {
|
||||
// reject(error)
|
||||
// })
|
||||
let url = 'https://coinb.in/api/?uid=1&key=12345678901234567890123456789012&setmodule=bitcoin&request=sendrawtransaction';
|
||||
fetch(url, {
|
||||
method: 'POST',
|
||||
@ -54,6 +471,7 @@
|
||||
},
|
||||
body: "rawtx=" + rawTxHex
|
||||
}).then(response => {
|
||||
console.log(response)
|
||||
response.text().then(resultText => {
|
||||
let r = resultText.match(/<result>.*<\/result>/);
|
||||
if (!r)
|
||||
@ -64,7 +482,12 @@
|
||||
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>', '');
|
||||
let error
|
||||
if (resultText.includes('<message>')) {
|
||||
error = resultText.match(/<message>.*<\/message>/).pop().replace('<message>', '').replace('</message>', '');
|
||||
} else {
|
||||
error = resultText.match(/<response>.*<\/response>/).pop().replace('<response>', '').replace('</response>', '');
|
||||
}
|
||||
reject(decodeURIComponent(error.replace(/\+/g, " ")));
|
||||
} else reject(resultText);
|
||||
}
|
||||
@ -267,10 +690,11 @@
|
||||
}
|
||||
|
||||
//BTC blockchain APIs
|
||||
|
||||
btcOperator.getBalance = addr => new Promise((resolve, reject) => {
|
||||
fetch_api(`q/addressbalance/${addr}`)
|
||||
.then(result => resolve(util.Sat_to_BTC(result)))
|
||||
if (!validateAddress(addr))
|
||||
return reject("Invalid address");
|
||||
multiApi('balance', { addr })
|
||||
.then(result => resolve(result))
|
||||
.catch(error => reject(error))
|
||||
});
|
||||
|
||||
@ -394,12 +818,16 @@
|
||||
}
|
||||
btcOperator.validateTxParameters = validateTxParameters;
|
||||
|
||||
function createTransaction(senders, redeemScripts, receivers, amounts, fee, change_address, fee_from_receiver) {
|
||||
const createTransaction = btcOperator.createTransaction = ({
|
||||
senders, redeemScripts, receivers, amounts, fee, change_address,
|
||||
fee_from_receiver, allowUnconfirmedUtxos = false, sendingTx = false,
|
||||
hasInsufficientBalance = false
|
||||
}) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8));
|
||||
const tx = coinjs.transaction();
|
||||
let output_size = addOutputs(tx, receivers, amounts, change_address);
|
||||
addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver).then(result => {
|
||||
addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver, allowUnconfirmedUtxos).then(result => {
|
||||
if (result.change_amount > 0 && result.change_amount > result.fee) //add change amount if any (ignore dust change)
|
||||
tx.outs[tx.outs.length - 1].value = util.BTC_to_Sat(result.change_amount); //values are in satoshi
|
||||
if (fee_from_receiver) { //deduce fee from receivers if fee_from_receiver
|
||||
@ -427,16 +855,21 @@
|
||||
result.output_amount = total_amount - (fee_from_receiver ? result.fee : 0);
|
||||
result.total_size = BASE_TX_SIZE + output_size + result.input_size;
|
||||
result.transaction = tx;
|
||||
resolve(result);
|
||||
if (sendingTx && result.hasOwnProperty('hasInsufficientBalance') && result.hasInsufficientBalance)
|
||||
reject({
|
||||
message: "Insufficient balance",
|
||||
...result
|
||||
});
|
||||
else
|
||||
resolve(result);
|
||||
}).catch(error => reject(error))
|
||||
})
|
||||
}
|
||||
btcOperator.createTransaction = createTransaction;
|
||||
|
||||
function addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver) {
|
||||
function addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver, allowUnconfirmedUtxos = false) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (fee !== null) {
|
||||
addUTXOs(tx, senders, redeemScripts, fee_from_receiver ? total_amount : total_amount + fee, false).then(result => {
|
||||
addUTXOs(tx, senders, redeemScripts, fee_from_receiver ? total_amount : total_amount + fee, false, { allowUnconfirmedUtxos }).then(result => {
|
||||
result.fee = fee;
|
||||
resolve(result);
|
||||
}).catch(error => reject(error))
|
||||
@ -445,8 +878,8 @@
|
||||
let net_fee = BASE_TX_SIZE * fee_rate;
|
||||
net_fee += (output_size * fee_rate);
|
||||
(fee_from_receiver ?
|
||||
addUTXOs(tx, senders, redeemScripts, total_amount, false) :
|
||||
addUTXOs(tx, senders, redeemScripts, total_amount + net_fee, fee_rate)
|
||||
addUTXOs(tx, senders, redeemScripts, total_amount, false, { allowUnconfirmedUtxos }) :
|
||||
addUTXOs(tx, senders, redeemScripts, total_amount + net_fee, fee_rate, { allowUnconfirmedUtxos })
|
||||
).then(result => {
|
||||
result.fee = parseFloat((net_fee + (result.input_size * fee_rate)).toFixed(8));
|
||||
result.fee_rate = fee_rate;
|
||||
@ -458,7 +891,7 @@
|
||||
}
|
||||
btcOperator.addInputs = addInputs;
|
||||
|
||||
function addUTXOs(tx, senders, redeemScripts, required_amount, fee_rate, rec_args = {}) {
|
||||
function addUTXOs(tx, senders, redeemScripts, required_amount, fee_rate, rec_args = { allowUnconfirmedUtxos: false }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
required_amount = parseFloat(required_amount.toFixed(8));
|
||||
if (typeof rec_args.n === "undefined") {
|
||||
@ -472,17 +905,24 @@
|
||||
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");
|
||||
else if (rec_args.n >= senders.length) {
|
||||
return resolve({
|
||||
hasInsufficientBalance: true,
|
||||
input_size: rec_args.input_size,
|
||||
input_amount: rec_args.input_amount,
|
||||
change_amount: required_amount * -1
|
||||
});
|
||||
}
|
||||
let addr = senders[rec_args.n],
|
||||
rs = redeemScripts[rec_args.n];
|
||||
let addr_type = coinjs.addressDecode(addr).type;
|
||||
let size_per_input = _sizePerInput(addr, rs);
|
||||
fetch_api(`unspent?active=${addr}`).then(result => {
|
||||
let utxos = result.unspent_outputs;
|
||||
multiApi('unspent', { addr, allowUnconfirmedUtxos: rec_args.allowUnconfirmedUtxos }).then(utxos => {
|
||||
//console.debug("add-utxo", addr, rs, required_amount, utxos);
|
||||
for (let i = 0; i < utxos.length && required_amount > 0; i++) {
|
||||
if (!utxos[i].confirmations) //ignore unconfirmed utxo
|
||||
if (utxos.length === 1 && rec_args.allowUnconfirmedUtxos) {
|
||||
console.log('allowing unconfirmed utxos')
|
||||
} else if (!utxos[i].confirmations) //ignore unconfirmed utxo
|
||||
continue;
|
||||
var script;
|
||||
if (!rs || !rs.length) //legacy script
|
||||
@ -525,43 +965,6 @@
|
||||
}
|
||||
btcOperator.addOutputs = addOutputs;
|
||||
|
||||
/*
|
||||
function autoFeeCalc(tx) {
|
||||
return new Promise((resolve, reject) => {
|
||||
get_fee_rate().then(fee_rate => {
|
||||
let tx_size = tx.size();
|
||||
for (var i = 0; i < this.ins.length; i++)
|
||||
switch (tx.extractScriptKey(i).type) {
|
||||
case 'scriptpubkey':
|
||||
tx_size += SIGN_SIZE;
|
||||
break;
|
||||
case 'segwit':
|
||||
case 'multisig':
|
||||
tx_size += SIGN_SIZE * 0.25;
|
||||
break;
|
||||
default:
|
||||
console.warn('Unknown script-type');
|
||||
tx_size += SIGN_SIZE;
|
||||
}
|
||||
resolve(tx_size * fee_rate);
|
||||
}).catch(error => reject(error))
|
||||
})
|
||||
}
|
||||
|
||||
function editFee(tx, current_fee, target_fee, index = -1) {
|
||||
//values are in satoshi
|
||||
index = parseInt(index >= 0 ? index : tx.outs.length - index);
|
||||
if (index < 0 || index >= tx.outs.length)
|
||||
throw "Invalid index";
|
||||
let edit_value = parseInt(current_fee - target_fee), //rip of any decimal places
|
||||
current_value = tx.outs[index].value; //could be BigInterger
|
||||
if (edit_value < 0 && edit_value > current_value)
|
||||
throw "Insufficient value at vout";
|
||||
tx.outs[index].value = current_value instanceof BigInteger ?
|
||||
current_value.add(new BigInteger('' + edit_value)) : parseInt(current_value + edit_value);
|
||||
}
|
||||
*/
|
||||
|
||||
function tx_fetch_for_editing(tx) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof tx == 'string' && /^[0-9a-f]{64}$/i.test(tx)) { //tx is txid
|
||||
@ -784,9 +1187,9 @@
|
||||
|
||||
|
||||
btcOperator.sendTx = function (senders, privkeys, receivers, amounts, fee = null, options = {}) {
|
||||
options.sendingTx = true;
|
||||
return new Promise((resolve, reject) => {
|
||||
createSignedTx(senders, privkeys, receivers, amounts, fee, options).then(result => {
|
||||
// debugger;
|
||||
broadcastTx(result.transaction.serialize())
|
||||
.then(txid => resolve(txid))
|
||||
.catch(error => reject(error));
|
||||
@ -808,7 +1211,7 @@
|
||||
receivers,
|
||||
amounts,
|
||||
fee,
|
||||
change_address: options.change_address
|
||||
...options
|
||||
}));
|
||||
} catch (e) {
|
||||
return reject(e)
|
||||
@ -823,7 +1226,11 @@
|
||||
if (redeemScripts.includes(null)) //TODO: segwit
|
||||
return reject("Unable to get redeem-script");
|
||||
//create transaction
|
||||
createTransaction(senders, redeemScripts, receivers, amounts, fee, options.change_address || senders[0], options.fee_from_receiver).then(result => {
|
||||
createTransaction({
|
||||
senders, redeemScripts, receivers, amounts, fee,
|
||||
change_address: options.change_address || senders[0],
|
||||
...options
|
||||
}).then(result => {
|
||||
let tx = result.transaction;
|
||||
console.debug("Unsigned:", tx.serialize());
|
||||
new Set(wif_keys).forEach(key => tx.sign(key, 1 /*sighashtype*/)); //Sign the tx using private key WIF
|
||||
@ -833,7 +1240,9 @@
|
||||
})
|
||||
}
|
||||
|
||||
btcOperator.createTx = function (senders, receivers, amounts, fee = null, options = {}) {
|
||||
btcOperator.createTx = function (senders, receivers, amounts, fee = null, options = {
|
||||
allowUnconfirmedUtxos: false
|
||||
}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
({
|
||||
@ -854,7 +1263,11 @@
|
||||
if (redeemScripts.includes(null)) //TODO: segwit
|
||||
return reject("Unable to get redeem-script");
|
||||
//create transaction
|
||||
createTransaction(senders, redeemScripts, receivers, amounts, fee, options.change_address || senders[0], options.fee_from_receiver).then(result => {
|
||||
createTransaction({
|
||||
senders, redeemScripts, receivers, amounts, fee,
|
||||
change_address: options.change_address || senders[0],
|
||||
...options
|
||||
}).then(result => {
|
||||
result.tx_hex = result.transaction.serialize();
|
||||
delete result.transaction;
|
||||
resolve(result);
|
||||
@ -890,7 +1303,12 @@
|
||||
return reject(e)
|
||||
}
|
||||
//create transaction
|
||||
createTransaction([sender], [redeemScript], receivers, amounts, fee, options.change_address || sender, options.fee_from_receiver).then(result => {
|
||||
createTransaction({
|
||||
senders: [sender], redeemScripts: [redeemScript],
|
||||
receivers, amounts, fee,
|
||||
change_address: options.change_address || sender,
|
||||
...options
|
||||
}).then(result => {
|
||||
result.tx_hex = result.transaction.serialize();
|
||||
delete result.transaction;
|
||||
resolve(result);
|
||||
@ -965,7 +1383,7 @@
|
||||
}
|
||||
|
||||
const getTxOutput = (txid, i) => new Promise((resolve, reject) => {
|
||||
fetch_api(`rawtx/${txid}`)
|
||||
multiApi('tx', { txid })
|
||||
.then(result => resolve(result.out[i]))
|
||||
.catch(error => reject(error))
|
||||
});
|
||||
@ -1021,93 +1439,39 @@
|
||||
return Crypto.util.bytesToHex(txid);
|
||||
}
|
||||
|
||||
const getLatestBlock = btcOperator.getLatestBlock = () => new Promise((resolve, reject) => {
|
||||
fetch_api(`q/getblockcount`)
|
||||
.then(result => resolve(result))
|
||||
.catch(error => reject(error))
|
||||
})
|
||||
|
||||
const getTx = btcOperator.getTx = txid => new Promise((resolve, reject) => {
|
||||
fetch_api(`rawtx/${txid}`).then(result => {
|
||||
getLatestBlock().then(latest_block => resolve({
|
||||
const getTx = btcOperator.getTx = txid => new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const result = await multiApi('tx', { txid });
|
||||
resolve({
|
||||
confirmations: result.confirmations,
|
||||
block: result.block_height,
|
||||
txid: result.hash,
|
||||
time: result.time * 1000,
|
||||
confirmations: result.block_height === null ? 0 : latest_block - result.block_height, //calculate confirmations using latest block number as api doesnt relay it
|
||||
time: result.time,
|
||||
size: result.size,
|
||||
fee: util.Sat_to_BTC(result.fee),
|
||||
inputs: result.inputs.map(i => Object({ address: i.prev_out.addr, value: util.Sat_to_BTC(i.prev_out.value) })),
|
||||
total_input_value: util.Sat_to_BTC(result.inputs.reduce((a, i) => a + i.prev_out.value, 0)),
|
||||
outputs: result.out.map(o => Object({ address: o.addr, value: util.Sat_to_BTC(o.value) })),
|
||||
total_output_value: util.Sat_to_BTC(result.out.reduce((a, o) => a += o.value, 0)),
|
||||
}))
|
||||
}).catch(error => reject(error))
|
||||
});
|
||||
})
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
}).catch(error => reject(error))
|
||||
|
||||
getTx.hex = btcOperator.getTx.hex = txid => new Promise((resolve, reject) => {
|
||||
fetch_api(`rawtx/${txid}?format=hex`, false)
|
||||
.then(result => resolve(result))
|
||||
.catch(error => reject(error))
|
||||
})
|
||||
getTx.hex = btcOperator.getTx.hex = txid => multiApi('txHex', { txid });
|
||||
|
||||
btcOperator.getAddressData = address => new Promise((resolve, reject) => {
|
||||
fetch_api(`rawaddr/${address}`).then(data => {
|
||||
let details = {};
|
||||
details.balance = util.Sat_to_BTC(data.final_balance);
|
||||
details.address = data.address;
|
||||
details.txs = data.txs.map(tx => {
|
||||
let d = {
|
||||
txid: tx.hash,
|
||||
time: tx.time * 1000, //s to ms
|
||||
block: tx.block_height,
|
||||
}
|
||||
//sender list
|
||||
d.tx_senders = {};
|
||||
tx.inputs.forEach(i => {
|
||||
if (i.prev_out.addr in d.tx_senders)
|
||||
d.tx_senders[i.prev_out.addr] += i.prev_out.value;
|
||||
else d.tx_senders[i.prev_out.addr] = i.prev_out.value;
|
||||
});
|
||||
d.tx_input_value = 0;
|
||||
for (let s in d.tx_senders) {
|
||||
let val = d.tx_senders[s];
|
||||
d.tx_senders[s] = util.Sat_to_BTC(val);
|
||||
d.tx_input_value += val;
|
||||
}
|
||||
d.tx_input_value = util.Sat_to_BTC(d.tx_input_value);
|
||||
//receiver list
|
||||
d.tx_receivers = {};
|
||||
tx.out.forEach(o => {
|
||||
if (o.addr in d.tx_receivers)
|
||||
d.tx_receivers[o.addr] += o.value;
|
||||
else d.tx_receivers[o.addr] = o.value;
|
||||
});
|
||||
d.tx_output_value = 0;
|
||||
for (let r in d.tx_receivers) {
|
||||
let val = d.tx_receivers[r];
|
||||
d.tx_receivers[r] = util.Sat_to_BTC(val);
|
||||
d.tx_output_value += val;
|
||||
}
|
||||
d.tx_output_value = util.Sat_to_BTC(d.tx_output_value);
|
||||
d.tx_fee = util.Sat_to_BTC(tx.fee);
|
||||
//tx type
|
||||
if (tx.result > 0) { //net > 0, balance inc => type=in
|
||||
d.type = "in";
|
||||
d.amount = util.Sat_to_BTC(tx.result);
|
||||
d.sender = Object.keys(d.tx_senders).filter(s => s !== address);
|
||||
} else if (Object.keys(d.tx_receivers).some(r => r !== address)) { //net < 0, balance dec & receiver present => type=out
|
||||
d.type = "out";
|
||||
d.amount = util.Sat_to_BTC(tx.result * -1);
|
||||
d.receiver = Object.keys(d.tx_receivers).filter(r => r !== address);
|
||||
d.fee = d.tx_fee;
|
||||
} else { //net < 0 (fee) & no other id in receiver list => type=self
|
||||
d.type = "self";
|
||||
d.amount = d.tx_receivers[address];
|
||||
d.address = address
|
||||
}
|
||||
return d;
|
||||
})
|
||||
resolve(details);
|
||||
Promise.all([
|
||||
multiApi('balance', { addr: address }),
|
||||
multiApi('txs', { addr: address })
|
||||
]).then(([balance, txs]) => {
|
||||
const parsedTxs = txs.map(tx => parseTx(tx, address));
|
||||
resolve({
|
||||
address,
|
||||
balance,
|
||||
txs: parsedTxs
|
||||
});
|
||||
}).catch(error => reject(error))
|
||||
});
|
||||
|
||||
|
||||
1
scripts/btcOperator.min.js
vendored
Normal file
1
scripts/btcOperator.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
Loading…
Reference in New Issue
Block a user