The Stellar JS SDK encapsulates the submission of Stellar transactions and the interaction with the Stellar Horizon API server and can be run in the Node.js environment or in a Web browser.js-stellar-sdk has two main roles: 1, querying Stellar block chain data through the Horizon API server 2, building Stellar transactions, signing and submitting to the Stellar network.
Recommendations: Intelligent Network Block Chain Development Series Tutorial
1. Construct Horizon Access Request
js-stellar-sdk uses Builder mode to create requests to be sent to the Horizon API server.Starting from a server object, you can generate the final query request through a chain call.For example:
var StellarSdk = require('stellar-sdk'); var server = new StellarSdk.Server('https://horizon-testnet.stellar.org'); // get a list of transactions that occurred in ledger 1400 server.transactions() .forLedger(1400) .call().then(function(r){ console.log(r); }); // get a list of transactions submitted by a particular account server.transactions() .forAccount('GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW') .call().then(function(r){ console.log(r); });
Once the request is constructed, you can call.call() or.stream() to submit the request.
.call() returns a promise object whose resolution is the response of the Horizon server.
2. Send streaming requests
Many requests can be invoked using.stream().Unlike.call() returning a promise object,.stream() returns an EventSource object.The Horizon API server automatically pushes related data to the requesting client.
For example, the following code shows the transactions that output the specified Stellar account:
var StellarSdk = require('stellar-sdk') var server = new StellarSdk.Server('https://horizon-testnet.stellar.org'); var lastCursor=0; // or load where you left off var txHandler = function (txResponse) { console.log(txResponse); }; var es = server.transactions() .forAccount(accountAddress) .cursor(lastCursor) .stream({ onmessage: txHandler })
3. Processing response from Stellar Horizon API server
3.1 Stellar XDR format decoding
The Horizon API server's transaction access endpoint returns certain fields in the original XDR format.You can use.fromXDR() to convert the XDR to JSON format.
For example, the following code overrides the txHandler in the above example to display the XDR field in JSON format:
var txHandler = function (txResponse) { console.log( JSON.stringify(StellarSdk.xdr.TransactionEnvelope.fromXDR(txResponse.envelope_xdr, 'base64')) ); console.log( JSON.stringify(StellarSdk.xdr.TransactionResult.fromXDR(txResponse.result_xdr, 'base64')) ); console.log( JSON.stringify(StellarSdk.xdr.TransactionMeta.fromXDR(txResponse.result_meta_xdr, 'base64')) ); };
3.2 Link follow in Horizon response results
The links contained in the Horizon response have been translated into corresponding method calls, which allow you to easily view the results page by page using the.next() method, while also making it easier to obtain additional information.For example:
server.payments() .limit(1) .call() .then(function(response){ // will follow the transactions link returned by Horizon response.records[0].transaction().then(function(txs){ console.log(txs); }); });
4. Stellar Transaction Construction and Broadcasting
4.1 Stellar Trading Construction
Stellar's transaction building process is a little more complicated, and we'll cover it in another article, so you can look at it first English original
4.2 Stellar Transaction Submission
Once a transaction has been created, it can be submitted to using the Server.submitTransaction() method
Stellar network.
const StellarSdk = require('stellar-sdk') StellarSdk.Network.useTestNetwork(); const server = new StellarSdk.Server('https://horizon-testnet.stellar.org'); (async function main() { const account = await server.loadAccount(publicKey); /* Right now, we have one function that fetches the base fee. In the future, we'll have functions that are smarter about suggesting fees, e.g.: `fetchCheapFee`, `fetchAverageFee`, `fetchPriorityFee`, etc. */ const fee = await server.fetchBaseFee(); const transaction = new StellarSdk.TransactionBuilder(account, { fee }) .addOperation( // this operation funds the new account with XLM StellarSdk.Operation.payment({ destination: "GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW", asset: StellarSdk.Asset.native(), amount: "20000000" }) ) .setTimeout(30) .build(); // sign the transaction transaction.sign(StellarSdk.Keypair.fromSecret(secretString)); try { const transactionResult = await server.submitTransaction(transaction); console.log(transactionResult); } catch (err) { console.error(err); } })()
Original Link: Stellar JS SDK Concise Tutorial - Smart Network