Stellar区块链JS应用开发简明教程

534 阅读2分钟

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简明教程 - 汇智网