diff --git a/package.json b/package.json index 20dfb87a..4bd1a804 100644 --- a/package.json +++ b/package.json @@ -75,6 +75,7 @@ "json-stable-stringify": "^1.0.1", "query-string": "^5.0.0", "sprintf-js": "^1.0.3", + "toposort": "^1.0.6", "tweetnacl": "^1.0.0" }, "keywords": [ diff --git a/src/transaction/utils/topologySorting.js b/src/transaction/utils/topologySorting.js new file mode 100644 index 00000000..54085e97 --- /dev/null +++ b/src/transaction/utils/topologySorting.js @@ -0,0 +1,27 @@ +import toposort from 'toposort' + +function generateGraph(txs) { + const graph = [] + txs.forEach(tx => { + tx.inputs.forEach(input => { + if (input.fulfills) { + graph.push([tx.id, input.fulfills.transaction_id]) + } + }) + }) + + return graph +} + + +/** + * @public + * Topological sort algorithm for transactions + * Used for endpoint: /transactions?assetId + * @param {object} txs Array of transactions + * @returns {object} Returns transactions in order of dependency + */ +export default function topsortTransactions(txs) { + const graph = generateGraph(txs) + return toposort(graph).reverse() +}