tutorial - HcashOrg/hx.js GitHub Wiki

Steps to write a simple HX dapp website


<script src="./hxjs.min.js"></script>
<script src="./hxPay.min.js></script>

or you can refer to this link: https://github.com/HcashOrg/hxPayment.js/blob/master/examples/todolist_dapp.html. The simple todolist dapp url is: https://hcashorg.github.io/hxPayment.js/examples/todolist_dapp.html

  • install Hx exntension wallet to your Chrome/Opera browser.
build HxExtensionWallet from https://github.com/HcashOrg/hxWebWalletExtension and install it your browser in developer mode
  • write a HX smart contract for your hx dapp

You can use Lua/glua/Java/Kotlin/C# language to write HX contract, and this is a simple TODO list contract on HX chain: https://github.com/HcashOrg/hxPayment.js/blob/master/examples/todolist.lua

type TodoItem = {
    content: string,
    time: int,
    author: string
}

type Storage = {
    items: Map<string> -- address => json list of TodoItem
}

var M = Contract<Storage>()

let function get_from_address()
    var from_address: string
    let prev_contract_id = get_prev_call_frame_contract_address()
    if prev_contract_id and is_valid_contract_address(prev_contract_id) then
        from_address = prev_contract_id
    else
        from_address = caller_address
    end
    return from_address
end

function M:init()
    self.storage.items = {}
end

function M:addTodo(arg: string)
    let from = get_from_address()
    if (not arg) or (#arg < 1) then
        return error("content can't be empty")
    end
    let content = arg
    let todoItem = TodoItem()
    todoItem.content = content
    todoItem.time = get_chain_now()
    todoItem.author = from
    let userItemsJsonStr = tostring(self.storage.items[from] or '[]')
    let userItems = totable(json.loads(userItemsJsonStr))
    table.append(userItems, todoItem)
    self.storage.items[from] = json.dumps(userItems) -- recommend to use fast_map_set/fast_map_get to storage maybe very large storage
    let todoItemStr = json.dumps(todoItem)
    emit AddedTodo(todoItemStr)
    return todoItemStr
end

offline function M:listTodosOfUser(userAddr: string)
    let userItemsJsonStr = tostring(self.storage.items[userAddr] or '[]')
    return userItemsJsonStr
end

return M
  • use anychain.org IDE or HX contract compilers to compile this contract(compiled result file ends with .gpc)

  • register the .gpc file to HX blockchain(using register_contract RPC method, or use HX WebWallet(http://wallet.hx.cash) ), and you can get the created contract address.

  • use hxPay.js(https://github.com/HcashOrg/hxPayment.js) to get using hx node network config.

Example : https://github.com/HcashOrg/hxPayment.js/blob/master/examples/todolist.js#L47

const HxPay = require("hxpay");
const hxPay = new HxPay();
hxPay.getConfig()
            .then((config) => {
                console.log('config', config);
                if (!config) {
                    alert("please install hx extension wallet first");
                    return;
                }

                this.hxConfig = config;
                ChainConfig.setChainId(config.chainId);
                this.apisInstance = Apis.instance(config.network, true);
                this.nodeClient = new NodeClient(this.apisInstance);
                // then you can use this.nodeClient to connect to hx_node rpc services
             });

  • use NodeClient instance to query hx chain info

Example: https://github.com/HcashOrg/hxPayment.js/blob/master/examples/todolist.js#L123

More docs for APIs of hx.js here: https://github.com/HcashOrg/hx.js/blob/master/docs/index.md

this.nodeClient.afterInited()
                .then(() => {
                    this.nodeClient.getContractBalances(this.contractAddress)
                        .then(balances => {
                            console.log("contract balances: ", balances);
                            this.contractHxBalance = 0;
                            for (const balance of balances) {
                                if (balance.asset_id === '1.3.0') {
                                    this.contractHxBalance = balance.amount;
                                }
                            }
                        }).catch(this.showError);
                    const dummyPubKey = 'HX8mT7XvtTARjdZQ9bqHRoJRMf7P7azFqTQACckaVenM2GmJyxLh';
                    this.nodeClient.invokeContractOffline(
                        this.myPubKey || dummyPubKey,
                        this.contractAddress,
                        'listTodosOfUser',
                        this.queryForm.address || this.myAddress
                    ).then(result => {
                        console.log("listTodosOfUser result: ", result);
                        this.myTodoList = JSON.parse(result);
                    }).catch(this.showError);

                }).catch(this.showError);
  • use hxPay to connect to hx extension wallet and send transaction

Example: https://github.com/HcashOrg/hxPayment.js/blob/master/examples/todolist.js#L110

this.hxPayListener = function (serialNumber, resp, name) {
            console.log("resp: " + JSON.stringify(resp));
            this.lastSerialNumber = serialNumber;
            if (name === 'txhash') {
                const txid = resp;
                this.lastTxid = txid;
                hxPay.waitTransaction(this.nodeClient, txid)
                    .then((tx) => {
                        console.log("found tx", tx);
                        alert("transaction successfully");
                        this.loadInfo();
                    }, this.showError);
            } else {
                this.lastResponse = resp;
            }
        };
this.nodeClient.afterInited()
                .then(() => {
                    var assetId = "1.3.0";
                    var to = this.contractAddress;
                    var value = 0;
                    var callFunction = "addTodo"
                    var callArgs = content;
                    // this is a example of using hxPay to notify hxExtensionWallet to send contract-invoke transaction to hx blockchain, you can also use other methods in hxPay like send assets
                    hxPay.simulateCall(assetId, to, value, callFunction, callArgs, {
                        gasPrice: '0.00001',
                        gasLimit: 5000,
                        listener: this.hxPayListener.bind(this)
                    });
                }).catch(this.showError);
  • Deploy your hx dapp website and done.
⚠️ **GitHub.com Fallback** ⚠️