天天看點

用JavaScript開發Stellar區塊鍊應用

Stellar JS SDK封裝了Stellar交易的送出,以及與Stellar Horizon API伺服器的互動過程,可以運作在Node.js環境或Web浏覽器中。js-stellar-sdk主要有兩個作用:1、通過HorizonAPI伺服器查詢Stellar區塊鍊資料 2、建構Stellar交易、簽名并送出到Stellar網絡中。

相關推薦: 彙智網 區塊鍊開發系列教程

1、構造Horizon通路請求

js-stellar-sdk使用Builder模式來建立要發送給Horizon API伺服器的請求。從一個server對象開始,你可以通過鍊式調用來生成最終的查詢請求。例如:

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

一旦請求構造好了,就可以調用

.call()

.stream()

來送出請求。

.call()

将傳回一個promise對象,其解析結果為Horizon伺服器的響應。

2、發送流式請求

許多請求可以使用

.stream()

來調用。與

.call()

傳回promise對象不同,

.stream()

将傳回一個

EventSource

對象。Horizon API伺服器會自動推送相關的資料給請求的用戶端。

例如,下面的代碼顯示輸出指定的Stellar賬戶的交易:

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、處理Stellar Horizon API伺服器的響應

3.1 Stellar XDR格式解碼

Horizon API伺服器的交易通路端結點會以原始XDR格式傳回某些字段。你可以使用

.fromXDR()

将XDR轉換為JSON格式。

例如,下面的代碼重寫了上面示例中的

txHandler

來将XDR字段顯示為JSON格式:

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 Horizon響應結果中的連結跟随

在Horizon響應中包含的連結已經被轉換為對應的方法調用,這讓你可以簡單地通過

.next()

方法來逐頁檢視結果,同時也讓擷取額外資訊更加輕松。例如:

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交易建構與廣播

4.1 Stellar交易建構

Stellar的交易建構過程稍微複雜一點,我們将在另一篇文章中介紹,你可以先檢視

英文原文

4.2 Stellar交易送出

一旦建立好了交易,就可以使用

Server.submitTransaction()

方法将其送出到

Stellar網絡中。

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);
    }
})()           

原文連結:

Stellar JS SDK簡明教程 - 彙智網

繼續閱讀