Skip to content

Instantly share code, notes, and snippets.

@dolcalmi
Last active January 1, 2019 20:20
Show Gist options
  • Save dolcalmi/5b3f04250a8df7aeb9a470e88d6a3dd5 to your computer and use it in GitHub Desktop.
Save dolcalmi/5b3f04250a8df7aeb9a470e88d6a3dd5 to your computer and use it in GitHub Desktop.
Stellar Payment Parser
/*
* parser modified to handle only payments: please check original in https://github.com/orbitlens/stellar-notifier/blob/552b58d976080322abba8833c73567a517c6b250/logic/stream-processor.js
*/
/* eslint-disable no-underscore-dangle */
import { Transaction } from 'stellar-base';
import BigNumber from 'bignumber.js';
const debug = require('debug')('yourproject:stellar:parser');
/**
* Retrieve an object with unified parameter names from operation.
* @param {StellarBase.Operation} operation
* @returns {*}
*/
function normalizeOperation(operation) {
switch (operation.type) {
case 'payment':
return {
to: operation.destination,
asset_code: operation.asset.code,
asset_issuer: operation.asset.issuer,
amount: operation.amount,
};
case 'pathPayment':
return {
to: operation.destination,
asset_code: operation.destAsset.code,
asset_issuer: operation.destAsset.issuer,
amount: operation.destAmount,
};
default:
return null;
}
}
function processOperation(operation, txDetails, applicationOrder) {
const normalized = normalizeOperation(operation, txDetails.source);
if (normalized) {
// assign operation generic ID
// see https://github.com/stellar/go/blob/6a367049e8f9ad52798f5c8f69df8b875fde4a1a/services/horizon/internal/toid/main.go
normalized.id = new BigNumber(txDetails.paging_token)
.plus(new BigNumber(applicationOrder + 1)).toString();
normalized.from = operation.source || txDetails.source;
normalized.txHash = txDetails.hash;
normalized.memo = txDetails.memo;
return normalized;
}
return null;
}
/**
* Normalize transaction memo
* @param {StellarBase.Memo} rawMemo - raw XDR memo
* @returns {*}
*/
function processMemo(rawMemo) {
switch (rawMemo._type) {
case 'id':
case 'text':
return rawMemo._value.toString('UTF-8');
case 'hash':
case 'return':
return rawMemo._value.toString('base64');
default:
return '';
}
}
/**
* Retrieve extended information from transaction object.
* @param {StellarBase.Transaction} transaction
* @returns {Object}
*/
function parsePayments(transaction) {
let xdrTx;
try {
xdrTx = new Transaction(transaction.envelope_xdr);
} catch (e) {
debug(e);
debug(`Tx envelope: ${transaction.envelope_xdr}`);
return null;
}
const txDetails = {
hash: transaction.hash,
source: xdrTx.source,
paging_token: transaction.paging_token,
memo: processMemo(xdrTx.memo),
};
return xdrTx.operations.map((op, i) => processOperation(op, txDetails, i)).filter(Boolean);
}
module.exports = parsePayments;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment