Fetch & Filter Blocks using WoC API

Code
Joshua Henslee

11 days ago by joshua

TX text/javascript
<script>
    var txObj = [];
    const getBlock = async(height, hash) => {
        let res, tx = [];
        if (height) {
            res = await (await fetch(`https://api.whatsonchain.com/v1/bsv/main/block/height/${height}`)).json();
        }
        else if (hash) {
            res = await (await fetch(`https://api.whatsonchain.com/v1/bsv/main/block/hash/${hash}`)).json();
        }
        res.tx.forEach(t => {
            tx.push(t)
        })
        if (res.pages?.uri.length) {
            const pages = res.pages.uri;
            for (let p of pages) {
                const res = await (await fetch(`https://api.whatsonchain.com/v1/bsv/main${p}`)).json();
                console.log({res})
                res.forEach(t => {
                    tx.push(t)
                })
            }
        }
        console.log({tx})
        const looptimes = parseInt(tx.length / 20);
        const remainder = tx.length % 20;
        console.log({looptimes}, {remainder})
        let x = 0;
        let temp = [];
        for (let i = 0; i < looptimes; i++) {
            for (let j = 0; j < 20; j++) {
                temp.push(tx[x]);
                x++;
            }
            const res = await (await fetch('https://api.whatsonchain.com/v1/bsv/main/txs/hex', {
                method: 'post',
                body: JSON.stringify({
                    txids: temp
                })
            })).json();
            console.log({res})
            temp = []
            res.forEach(t => {
                if (t.hex.includes('73656e7369626c65')) {
                    txObj.push({
                        txid: t.txid,
                        hex: t.hex
                    })
                }
            })
            console.log({txObj})
        }
        temp = [];
        for (let k = tx.length - 1; k >= tx.length - remainder; k--) {
            temp.push(tx[k])
        }
        const remainderRes = await (await fetch('https://api.whatsonchain.com/v1/bsv/main/txs/hex', {
            method: 'post',
            body: JSON.stringify({
                txids: temp
            })
        })).json();
        console.log({remainderRes})
        temp = []
        remainderRes.forEach(t => {
            if (t.hex.includes('73656e7369626c65')) {
                txObj.push({
                    txid: t.txid,
                    hex: t.hex
                })
            }
        })
        console.log({txObj})
        if (res.nextblockhash) {
            await getBlock(null, res.nextblockhash)
        }
    }
    getBlock(706041)
</script>