Understanding The Basics Of Stellar Network

Understanding The Basics Of Stellar Network

Understanding The Basics Of Stellar Network

Understanding The Basics Of Stellar Network

Understanding The Basics Of Stellar Network

Read Time: 6 minutes

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 use 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 a group of quorum slices.E each node can be a part of a quorum slice and a quorum slice must contain more than two nodes. The node depends on its neighbor nodes in quorum slice for maintaining ledger consistent state. A quorum slice should contain intersecting nodes with other quorum slices.

The lifecycle of a transaction in Stellar Network:-

Creation:

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

Signing:

The transaction must be signed with the 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 let’s move on to coding part!

A stellar application interacts with stellar network using horizon API or can be direct to stellar core instance. With horizon API we can create accounts, check the balance and subscribe to events on the stellar network. Every horizon API server is connected to the 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 transaction. 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 cannot be done with stellar.

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

Getting public key:

The 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 the account.

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

Creating an account using public key:

To create an account one must have a minimum balance of 1 lumen. In the main stellar network, we need to buy at least 1 lumen to create an account. For development purpose, we can use testnet friendbot to create an account. We just need to send public key as a query string to the stellar friendbot url. After creating an 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 the first three parts of transaction lifecycle here i.e(creation, signing, submitting). Before creating transaction we must check whether the receiver account exists or not because stellar protocol doesn’t check for the existence of the account. To create a transaction transactionBuilder class of stellar-sdk is used. A transaction is a collection of operations. We can add appropriate operations, here we are adding payment operation to send lumens. After creating a 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 the client side. Here we are simply logging them.

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’);
},
});

The full snippet of API endpoints:

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.

Launch your blockchain project with Quillhash: https://quillhash.typeform.com/to/KQ5Hhm

Thanks for reading. Also, do check out our earlier blog posts.


At QuillHash, we understand the Potential of Blockchain and have a good team of developers who can develop any blockchain applications like Smart Contracts, dApps,Smart Coins, DeFi, DEX on the any Blockchain Platform like Ethereum, EOS and Hyperledger.

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

Telegram | Twitter | Facebook | LinkedIn

4,724 Views

Blockchain for dog nose wrinkles' Ponzi makes off ~$127M🐶

Project promised up to 150% returns on investment in 100 days, raising about 166.4 billion South Korean won — or about $127 million — from 22,000 people.

Latest blogs for this week

Understanding Fuzzing and Fuzz Testing: A Vital Tool in Web3 Security

Read Time: 5 minutes When it comes to smart contracts, ensuring the robustness and security of code is paramount. Many techniques are employed to safeguard these contracts against vulnerabilities
Read More

How EigenLayer’s Restaking Enhances Security and Rewards in DeFi

Read Time: 7 minutes Decentralized finance (DeFi) relies on Ethereum staking to secure the blockchain and maintain consensus. Restaking allows liquid staking tokens to be staked with validators in
Read More

ERC 404 Standard: Everything You Need to Know

Read Time: 7 minutes Introduction Ethereum has significantly shaped the crypto world with its introduction of smart contracts and decentralized applications (DApps). This has led to innovative developments in
Read More

DNS Attacks:  Cascading Effects and Mitigation Strategies

Read Time: 8 minutes Introduction DNS security is vital for a safe online space. DNS translates domain names to IP addresses, crucial for internet functionality. DNS ensures unique name-value
Read More

EIP-4844 Explained: The Key to Ethereum’s Scalability with Protodanksharding

Read Time: 7 minutes Introduction  Ethereum, the driving force behind dApps, has struggled with scalability. High fees and slow processing have limited its potential. They have kept it from
Read More

QuillAudits Powers Supermoon at ETH Denver!

Read Time: 4 minutes Calling all the brightest minds and leaders in the crypto world! Are you ready to build, connect, and innovate at the hottest event during ETH
Read More

Decoding the Role of Artificial Intelligence in Metaverse and Web3

Read Time: 7 minutes Introduction  Experts predict a transformative shift in global software, driven by AI and ML, marking the dawn of a new era. PwC predicts AI will
Read More

Transforming Assets: Unlocking Real-World Asset Tokenization

Read Time: 7 minutes In the blockchain, real-world assets (RWAs) are digital tokens that stand for tangible and conventional financial assets, including money, raw materials, stocks, and bonds. As
Read More
Scroll to Top

Become a Quiffiliate!
Join our mission to safeguard web3

Sounds Interesting, Right? All you have to do is:

1

Refer QuillAudits to Web3 projects for audits.

2

Earn rewards as we conclude the audits.

3

Thereby help us Secure web3 ecosystem.

Total Rewards Shared Out: $200K+