Skip to content

Commit

Permalink
feat: fix getUnspentsForAddresses in BlockchairApi
Browse files Browse the repository at this point in the history
When we pass an array of addresses we make a single call to the
blockchair API with a comma separated list of addresses. The response
includes the list of all utxos for every address in the list.

Example response

```
  "utxo": [
    {
      "block_id": 838353,
      "transaction_hash": "19a2e26860981413ceab82052738386d72d530333b3a7e0237518e242c65524d",
      "index": 0,
      "value": 42000,
      "address": "34EaQXdjELqWrTFxJWFgmVmF91kPhdP4us"
    },
    {
      "block_id": 838353,
      "transaction_hash": "19a2e26860981413ceab82052738386d72d530333b3a7e0237518e242c65524d",
      "index": 1,
      "value": 657269,
      "address": "bc1qv669qw5tzxsue5qrl36ygqnaahm98n9t68hdz577cz2r8eldyj3q6d90c4"
    }
  ]

```

However, with the code as it is now, for every address we map all the
utxos in the response to the address. In the above example we will have
a return value of an array of size 4 instead of the expected size 2.
Associated unspents to addresses it doesnt belong to.

Ticket: BTC-1084

TICKET: BTC-1084
  • Loading branch information
lcovar committed Apr 12, 2024
1 parent 16518bb commit 48574c4
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions modules/blockapis/src/impl/BlockchairApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type BlockchairUnspent = {
script_hex: string;
spending_transaction_hash: string;
spending_index: number;
address: string;
};

// https://blockchair.com/api/docs#link_300
Expand Down Expand Up @@ -144,19 +145,24 @@ export class BlockchairApi implements AddressApi, UtxoApi {
if (addr.length > 100) {
throw new Error(`invalid size`);
}
// https://blockchair.com/api/docs#link_300
return (
await this.get<BlockchairResponse<{ utxo: BlockchairUnspent[] }>>(`/dashboards/addresses/${addr.join(',')}`)
).map((body) => {
return addr.flatMap((a) => {
return body.data.utxo.map((unspent): Unspent => {
return {
id: formatOutputId({ txid: unspent.transaction_hash, vout: unspent.index }),
address: a,
value: unspent.value,
};
});
});

const response = await this.get<BlockchairResponse<{ utxo: BlockchairUnspent[] }>>(
`/dashboards/addresses/${addr.join(',')}`
);

return response.map((body) => {
return body.data.utxo
.flatMap((unspent): Unspent | undefined => {
if (addr.includes(unspent.address)) {
return {
id: formatOutputId({ txid: unspent.transaction_hash, vout: unspent.index }),
address: unspent.address,
value: unspent.value,
};
}
return undefined;
})
.filter((unspent): unspent is Unspent => unspent !== undefined);
});
}

Expand Down

0 comments on commit 48574c4

Please sign in to comment.