All files / src/services/providers whatsonchain.ts

71.42% Statements 50/70
33.33% Branches 6/18
75% Functions 3/4
72.05% Lines 49/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 16157x 57x   57x 57x                         57x   5x   5x 5x 5x 4x 1x   3x   3x 3x 3x 3x 3x 3x     1x     4x                   57x   12x   12x 12x 12x 8x     8x     4x     12x                   57x     2x   2x   2x   2x   2x   2x   2x   2x 2x 1x 1x 1x   1x 1x 1x 1x 1x                       2x                                     57x                                                    
import { asArray, asString, sdk, validateScriptHash } from '../../index.client'
import { convertProofToMerklePath } from '../../utility/tscProofToMerklePath'
 
import axios from 'axios'
import Whatsonchain from 'whatsonchain'
 
/**
 * WhatOnChain.com has their own "hash/pos/R/L" proof format and a more TSC compliant proof format.
 * 
 * The "/proof/tsc" endpoint is much closer to the TSC specification. It provides "index" directly and each node is just the provided hash value.
 * The "targetType" is unspecified and thus defaults to block header hash, requiring a Chaintracks lookup to get the merkleRoot...
 * Duplicate hash values are provided in full instead of being replaced by "*".
 * 
 * @param txid
 * @param chain 
 * @returns 
 */
export async function getMerklePathFromWhatsOnChainTsc(txid: string, chain: sdk.Chain, services: sdk.WalletServices): Promise<sdk.GetMerklePathResult> {
 
    const r: sdk.GetMerklePathResult = { name: 'WoCTsc' }
 
    try {
        const url = `https://api.whatsonchain.com/v1/bsv/${chain}/tx/${txid}/proof/tsc`
        let { data } = await axios.get(url)
        if (!data || data.length < 1)
           return r 
 
        Iif (!data['target'])
            data = data[0]
        const p = data
        const header = await services.hashToHeader(p.target)
        Iif (!header) throw new sdk.WERR_INVALID_PARAMETER('blockhash', 'a valid on-chain block hash')
        const proof = { index: p.index, nodes: p.nodes, height: header.height }
        r.merklePath = convertProofToMerklePath(txid, proof)
        r.header = header
 
    } catch (err: unknown) {
        r.error = sdk.WalletError.fromUnknown(err)
    }
 
    return r
}
 
interface WhatsOnChainProofTsc {
    index: number,
    txOrId: string,
    target: string,
    nodes: string[]
}
 
export async function getRawTxFromWhatsOnChain(txid: string, chain: sdk.Chain): Promise<sdk.GetRawTxResult> {
 
    const r: sdk.GetRawTxResult = { name: 'WoC', txid: asString(txid) }
 
    try {
        const url = `https://api.whatsonchain.com/v1/bsv/${chain}/tx/${txid}/hex`
        const { data } = await axios.get(url)
        Iif (!data)
            return r
 
        r.rawTx = asArray(data)
 
    } catch (err: unknown) {
        r.error = sdk.WalletError.fromUnknown(err)
    }
 
    return r
}
 
interface WhatsOnChainUtxoStatus {
    value: number
    height: number
    tx_pos: number
    tx_hash: string
}
 
export async function getUtxoStatusFromWhatsOnChain(output: string, chain: sdk.Chain, outputFormat?: sdk.GetUtxoStatusOutputFormat)
: Promise<sdk.GetUtxoStatusResult>
{
    const r: sdk.GetUtxoStatusResult = { name: 'WoC', status: 'error', error: new sdk.WERR_INTERNAL(), details: [] }
 
    for (let retry = 0; ; retry++) {
 
        let url: string = ''
 
        try {
 
            const scriptHash = validateScriptHash(output, outputFormat)
 
            url = `https://api.whatsonchain.com/v1/bsv/${chain}/script/${scriptHash}/unspent`
 
            const { data } = await axios.get(url)
 
            if (Array.isArray(data)) {
                if (data.length === 0) {
                    r.status = 'success'
                    r.error = undefined
                    r.isUtxo = false
                } else {
                    r.status = 'success'
                    r.error = undefined
                    r.isUtxo = true
                    for (const s of <WhatsOnChainUtxoStatus[]>data) {
                        r.details.push({
                            txid: s.tx_hash,
                            satoshis: s.value,
                            height: s.height,
                            index: s.tx_pos
                        })
                    }
                }
            } else E{
                throw new sdk.WERR_INTERNAL("data is not an array")
            }
 
            return r
 
        } catch (eu: unknown) {
            const e = sdk.WalletError.fromUnknown(eu)
            Iif (e.code !== 'ECONNRESET' || retry > 2) {
                r.error = new sdk.WERR_INTERNAL(`service failure: ${url}, error: ${JSON.stringify(sdk.WalletError.fromUnknown(eu))}`)
                return r
            }
        }
    }
    return r
}
 
interface WhatsOnChainScriptHistory {
    fee?: number
    height?: number
    tx_hash: string
}
 
export async function updateBsvExchangeRate(rate?: sdk.BsvExchangeRate, updateMsecs?: number): Promise<sdk.BsvExchangeRate> {
 
    Iif (rate) {
        // Check if the rate we know is stale enough to update.
        updateMsecs ||= 1000 * 60 * 15
        Iif (new Date(Date.now() - updateMsecs) < rate.timestamp)
            return rate
    }
 
    // TODO: Expand to redundant services with caching...
    const woc = new Whatsonchain()
    const r = await woc.exchangeRate()
    const wocrate = <{ rate: number, time: number, currency: string }>r
    Iif (wocrate.currency !== 'USD')
        wocrate.rate = NaN
 
    const newRate: sdk.BsvExchangeRate = {
        timestamp: new Date(),
        base: 'USD',
        rate: wocrate.rate
    }
 
    //console.log(`new bsv rate=${JSON.stringify(newRate)}`)
 
    return newRate
}