Tutorials

Transactions as XDR encoded strings

Recently, I was working on something and came across a function I felt might be useful to some. If you have ever created transactions with the Stellar laboratory, you can’t help but notice the output XDR string and the awesome XDR Viewer. For the stellar app I was working on, I needed to store the transactions in a database, hence an XDR string will be most suitable for this. How do we do this? Say we have the following transaction:

var txObj = new StellarSdk.TransactionBuilder(srcAcct)                   .addOperation(StellarSdk.Operation.createAccount({                                   destination: destAcct,                                   startingBalance: startingBalance.toString(),                                   source: srcAcct                     }));

txObj holds our current TransactionBuilder object.To build the transaction we call the .build() method

txObj = txObj.build()

Now txObj holds our Transaction object. We can call the .toEnvelope() method on this object to return type xdr.envelope. However this will still be in object form and not a string. To get the encoded string we can do the following

var xdrString = txObj.toEnvelope().toXDR().toString("base64");

That’s all. It will return a string like

AAAAAAAAAAAAAHp6IGPoi0M4iR6+5zFW92G9NZs5/AoAAAAXSHAAAAAAAA

Hope you found this useful. Got some other tips? leave them in the comments

Leave a Comment