Stellar is a payment network focused on asset movement.Stellar has a particular use case of how money is sent and traded across international borders.Anyone can create assets and trade them.

Stellar has its decentralized exchange where anyone can exchange assets ,also we don’t need to wait to enlist our asset on centralized exchanges with stellar.We can start trading assets from the beginning by stellar decentralized exchange.However we can enlist assets created using stellar network on various exchanges.

Stellar uses Stellar consensus protocol(SCP) to build consensus among nodes.Nodes are known as stellar cores on stellar network.Stellar not using the proof of work or proof of stake mechanism to validate transactions, it’s using federated Byzantine agreement (FBA).

Stellar consensus protocol uses the concept of quorum and quorum slice.A quorum is group of quorum slices .Each node can be a part of an quorum slice and a quorum slice must contain more than two nodes.The node depends on its neighbour nodes in quorum slice for maintaining ledger consistent state.An quorum slice should contain intersecting nodes with other quorum slices.

Lifecycle of a transaction in stellar:-

Creation:

The user creates a transaction, fills out all the fields, gives it the correct sequence number, adds whatever operations it wants.

Signing:

Transaction must be signed with sender’s keys and in complex transactions multiple parties signature can be required.

Submitting:

After signing, the transaction should be valid and can now be submitted to the Stellar network. Transactions are typically submitted using horizon, but you can also submit the transaction directly to an instance of stellar-core.

Propagating:

Once stellar-core receives a transaction, either given to it by a user or another stellar-core, it does preliminary checks to see if the transaction is valid. Among other checks, it makes sure that the transaction is correctly formed and the source account has enough to cover the transaction fee.

Building transactions set:

When it’s time to close the ledger, stellar-core takes all the transactions it has heard about since last ledger close and collects them into a transaction set. If it hears about any incoming transactions now, it puts them aside for next ledger close. Stellar-core nominates the transaction set it has collected. SCP resolves the differences between the various transaction sets proposed and decides on the one transaction set that the network will apply.

Executing the transactions:

Once SCP agrees on a particular transaction set, that set is applied to the ledger. At this point, a fee is taken from the source account for every transaction in that set. Operations are attempted in the order they occur in the transaction. If any operation fails, the whole transaction fails, and the effects of previous operations in that transaction are rolled back. After all the transactions in the set are applied, a new ledger is created and the process starts over.

Now lets move on to coding part!

An stellar application interact with stellar network using horizon api or can be directly to stellar core instance.With horizon api we can create accounts,check balance and subscribe to events on stellar network.Every horizon api server is connected to stellar core (stellar core can be compared to nodes of ethereum,any one set their instance of stellar core on the stellar network).Stellar core does the work of transaction validation on the network using stellar consensus protocol and agreeing with other stellar cores to accept the status of each transactions.The Stellar network itself is a collection of connected stellar Cores run by various individuals and entities around the world.Some instances of stellar core have a Horizon server you can communicate with, while others exist only to add reliability to the overall network and mining can not be done with stellar .

We will create our rest api to to connect with stellar core horizon api via stellar javascript sdk,below a high level diagram of what we will be doing from now:-

Our node Js api are performing four functions:

Getting public key:

Public key is returned as a by using random function of key Pair class in stellar sdk.Random function returns a pair of public key and secret seed.Secret seed is used to generate both the public and private key for account.

var pair = StellarSdk.Keypair.random(); let secret = pair.secret(); let public = pair.publicKey();

Creating account using public key:

To create an account one must have a minimum balance of 1 lumen.In main stellar network we need to buy atleast 1 lumen to create an account.For development purpose we can use testnet friendbot to create account. We just need to send public key as query string to the stellar friendbot url.After creating account we can load the balances of account.An account can contain multiple balances of different assets.

var options = {method: ‘GET’, uri: ‘https://friendbot.stellar.org', qs: { addr:req.body.publickey}, json: true }; rp(options) .then(function (parsedBody) { // POST succeeded… server.loadAccount(req.body.publickey) .then(function(account) { account.balances.forEach(function(balance) { res.render(‘accountInfo’,{AssetType:balance.asset_type ,Balance: balance.balance}); }); }); }) .catch(function (err) { // POST failed… console.log(err); res.send(err); })

Sending lumens to another account:

We need to create a transaction to send lumens to another account.We should implement first three parts of transaction lifecycle here i.e(creation,signing, submitting).Before creating transaction we must check whether receiver account exists or not because stellar protocol doesn’t check for existence of account. To create transaction transactionBuilder class of stellar-sdk is used.An transaction is a collection of operations.We can add appropriate operations ,here we are adding payment operation to send lumens.After creating transaction ,it must be signed using sender keys.Sender keys are generated using sender secret and finally we can submit the transaction after signing it.

var sourceKeys = StellarSdk.Keypair .fromSecret(req.body.secret); server.loadAccount(req.body.destinationKey) .catch(StellarSdk.NotFoundError, function (error) { throw new Error(‘The destination account does not exist!’); }) .then(function() { return server.loadAccount(sourceKeys.publicKey()); }) .then(function(sourceAccount) { transaction = new StellarSdk.TransactionBuilder(sourceAccount) .addOperation(StellarSdk.Operation.payment({ destination: req.body.destinationKey, asset: StellarSdk.Asset.native(), amount: req.body.amount })) .addMemo(StellarSdk.Memo.text(‘Test Transaction’)) .build(); transaction.sign(sourceKeys); return server.submitTransaction(transaction); }) .then(function(result) { console.log(‘Success! Results:’, result); server.loadAccount(sourceKeys.publicKey()) .then(function(account) { account.balances.forEach(function(balance) { res.render(‘accountInfo’,{AssetType:balance.asset_type ,Balance: balance.balance}); }); }); }) .catch(function(error) { console.error(‘Something went wrong!’, error); });

Logging received payments.

If we are receiving payments on behalf of others then we can get the received payments to know the details of received payment.Received payments are sent as events from horizon api server.We can subscribe to these events on client side .Here we are simply logging them.

var payments = server.payments().forAccount(req.query.accountId); payments.stream({ onmessage: function(payment) { if (payment.to !== req.query.accountId) { return; } var asset; if (payment.asset_type === ‘native’) { asset = ‘lumens’; } else { asset = payment.asset_code + ‘:’ + payment.asset_issuer; } console.log(payment.amount + ‘ ‘ + asset + ‘ from ‘ + payment.from); }, onerror: function(error) { console.error(‘Error in payment stream’); }, });

Full snippet of api end points:

You can get the complete code here.

Thanks for reading. Hopefully this guide has been useful to you and will help you to understand the basics of Stellar Network and Also do check out our earlier blog posts.

You can find more information about QuillHash on our Website.

To be up to date with our work, Join Our Community :-

Telegram | Twitter | Facebook | LinkedIn