Loading..

Developers: Unichain - Example & Demo 0 0

Last updated on Nov 22, 2020 16:27 in Developers
Posted By Yamamoto Kudo

In this page, We will guide you how to work with UniChain using UniChain-Js. The examples and functions below may be suitable for creating a wallet or working with exchanges.

Prepare Environment

  • Setup UniChain local nodes . Refer this link, or simply run the following commands
java -jar unichain-core.jar
java -jar relay-node.jar

You need to wait for the synchronization to complete before start working with.

  • Install UniChain-JS
npm install @uniworld/unichain-js 

Construct UniChain-JS

const Unichain = require('@uniworld/unichain-js')
const host = 'http://127.0.0.1:6636' 
const relayHost = 'http://127.0.0.1:7749' 

const unichain = new Unichain({fullHost: host, solidityNode: relayHost})

Check if the node is connected

unichain.isConnected((err, data) => {
    if (err) console.log('Error: ', err)
    else console.log('UniChain node is connected, info:', data)
})

Utility Functions

You can check more utility functions in this link. The codes below demostrate on how to create wallet, send UNW coin and load the transaction history ... in NodeJS

Example for wallet functions

const Unichain = require('@uniworld/unichain-js')
const crypto = require('crypto')

const host = 'http://127.0.0.1:6636' 
const relayHost = 'http://127.0.0.1:7749' 

const unichain = new Unichain({fullHost: host, solidityNode: relayHost})

//Create a random private key 
const generateRandomKey = () => {
    const length = 32
    const randomBytes = crypto.randomBytes(length)
    const privateKey = randomBytes.toString('hex')
    return privateKey
}

//convert UNW to Ginza
const toGinza = (unw) => unw*1000000

//Send UNW coin 
const sendCoin = async (fromAddress, toAddress, amount) => {
  if (fromAddress == toAddress) {
      console.log('cannot send to your own address')
      return null
  }

  amount = toGinza(amount) 
  const data = {
      to_address: unichain.address.toHex(toAddress),
      owner_address: unichain.address.toHex(fromAddress),
      amount: parseInt(amount) 
  }
  let unsingedTx = await unichain.currentProviders().fullNode.request('wallet/createtransaction', data, 'post')
  let signedTx = await unichain.unx.signTransaction(unsingedTx, privateKey, 0)
  let res = await unichain.unx.sendRawTransaction(signedTx)
  return res
}


//const privateKey = generateRandomKey()
const privateKey = '57a47e242dece5a6ec6351a60784a1d9abb9cae175d4fc22475122ede47e7d11'
const fromAddress = unichain.address.fromPrivateKey(privateKey)
console.log('fromAddress:', fromAddress)
//fromAddress: UZ1XxkZEQru4dJjjQfxVMG42SGSxpPrhRu
//You need to deposit to fromAddress before sending UNW to another address
const toAddress = 'UP4DP51jR2U5n5XaoaxKQ9TG2kvmh3Cy8X' //for test

sendCoin(fromAddress, toAddress, 1)
.then(res => {console.log(res)})
.catch(err => console.log('error:', err))

Result should look like this

{
    result:true,
    transaction:{
        visible:false,
        txID:'232176ccd94b079bbc1afe8687f656a2708ee29e4aea254699f0323bbb8ab530',
        raw_data:{
        contract:[
            Array
        ],
        ref_block_bytes:'c0f3',
        ref_block_hash:'9af2438cd42944e7',
        expiration:1603211226000,
        timestamp:1603211167488
    },
    raw_data_hex:'0a02c0f322089af2438cd42944e74090d7d7b6d42e5a67080112630a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412320a154478f2d8fc9a88eec78c1fd95873bd4b02177065cd1215440bc353c683213030a0525cb76169442d3c729f0118c0843d70808ed4b6d42e',
    signature:[
    'a9fe1b28a35ffcb2cf6ed46f25926978f76df0ac166bf0c22e84db2e23d3a7b901d856582da97081ab3b1a2b7c97daaaa85f1ca760bb568d0c73a3bb30b4e8d701'
    ]
}
}

Get transaction by txid

const txid = '232176ccd94b079bbc1afe8687f656a2708ee29e4aea254699f0323bbb8ab530'
unichain.unx.getTransaction(txid, (err, tx) => {
    console.log(tx)
})

Result should be following

{
    ret: [
        {
            contractRet: 'SUCCESS'
        }
    ],
    signature: [
        'a9fe1b28a35ffcb2cf6ed46f25926978f76df0ac166bf0c22e84db2e23d3a7b901d856582da97081ab3b1a2b7c97daaaa85f1ca760bb568d0c73a3bb30b4e8d701'
    ],
    txID: '232176ccd94b079bbc1afe8687f656a2708ee29e4aea254699f0323bbb8ab530',
    raw_data: {
        contract: [
            {
                parameter: {
                    value: {
                        amount: 1000000,
                        owner_address: '4478f2d8fc9a88eec78c1fd95873bd4b02177065cd',
                        to_address: '440bc353c683213030a0525cb76169442d3c729f01'
                    },
                    type_url: 'type.googleapis.com/protocol.TransferContract'
                },
                type: 'TransferContract'
            }
        ],
        ref_block_bytes: 'c0f3',
        ref_block_hash: '9af2438cd42944e7',
        expiration: 1603211226000,
        timestamp: 1603211167488
    },
    raw_data_hex: '0a02c0f322089af2438cd42944e74090d7d7b6d42e5a67080112630a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412320a154478f2d8fc9a88eec78c1fd95873bd4b02177065cd1215440bc353c683213030a0525cb76169442d3c729f0118c0843d70808ed4b6d42e'
}

Get account information including balance and other resources, permissions

//Get account information, can use async/await style
const accountAddress = 'UZ1XxkZEQru4dJjjQfxVMG42SGSxpPrhRu'
unichain.unx.getAccount(accountAddress)
.then(account => {
    console.log('account information: ', account)})
.catch(err => {
    console.log(err)
})

Result:

{ 
    address: '4478f2d8fc9a88eec78c1fd95873bd4b02177065cd',
    balance: 8999000,
    create_time: 1603210485000,
    latest_opration_time: 1603211166000,
    account_resource: {},
    owner_permission: { permission_name: 'owner', threshold: 1, keys: [ [Object] ] },
    active_permission: [
        { 
       			  
** The time is base on America/New_York timezone