@a4i3ia2/realnet-orders-server
## Start
Last updated 2 years ago by a4i3ia2 .
ISC · Original npm · Tarball · package.json
$ cnpm install @a4i3ia2/realnet-orders-server 
SYNC missed versions from official npm registry.

Realnet Orders Server

Start

npm i @marko.laban/realnet-orders-server

const realnetOrders = require('@marko.laban/realnet-orders-server');

Main dependencies

  • web3
  • crypto-js
  • truffle-contract
  • request

Initializing a module

Load global environment from the process.env:

  • BLOCKCHAIN_ENABLED=true

States whether blockchain is enabled on backend (used in module only as value to be returned).

  • BLOCKCHAIN_DEFAULT_DONATE_TOKENS=10000

Defines the amount of tokens to donate (in wei) by default (used only for testing purposes).

  • BLOCKCHAIN_DEFAULT_DONATE_ETHER=0.5

Defines the amount of gas to donate (in ETH) by default (old version).

  • BLOCKCHAIN_ETH_LOWER_LIMIT=1.5

Defines lower threshold of ETH to fetch users with gas amount under.

BLOCKCHAIN_ENODE_RPC_URL and BLOCKCHAIN_SYNCHRONY_SERVER_URL are semicolon-separated lists of URLs of enodes and intermediate servers respectively. Enodes and intermediate servers with equal indexes in lists are located on the same hardware. This is necessary to synchronize work of blockchain nodes and to change passkey in keystore files.

  • BLOCKCHAIN_MAIN_ENODE_RPC_URL=http://enode.hopto.org:2222

Sets te URL to connect to blockchain main network.

  • BLOCKCHAIN_CONTRACT_COMMISSION=0.01

Defines the default blockchain commission.

  • BLOCKCHAIN_UNLOCK_TIME=10000

Sets the acconunt unlocking timeout (timeout the account is unlocked after).

  • BLOCKCHAIN_GAS_PRICE_LOW=500000000

Defines the lower gasPrice during creation transaction.

  • BLOCKCHAIN_GAS_PRICE_AVERAGE=40000000000

Defines the average gasPrice during creation transaction.

  • BLOCKCHAIN_GAS_PRICE_FAST=0

Defines the fast gasPrice during creation transaction. (mainnet: 40 gwei = 40 000 000 000 wei, private net: 0 by default).

  • BLOCKCHAIN_GAS_CONTRACT_TX=500000

Contains the default value for all transactions to the contract, used in case the estimateGas() does not work.

  • BLOCKCHAIN_GAS_PRIVATE_TX=100000

Contains the default value for all web3 transactions in private network, used in case the estimateGas() does not work.

  • BLOCKCHAIN_GAS_MAIN_TX=21000

Contains the default value for all web3 transactions in main network, used in case the estimateGas() does not work.

  • BLOCKCHAIN_EVENT_BY_GAS_COST=300000

Events cost, added to overall transaction gas for each event (in wei).

Initialization

  1. Initializing logger
  2. Initializing decorator
  3. Initializing artifact (by default)
  4. Initializing truffle contract object
  5. Initializing web3 and web3 of main network objects
  6. Running the synchrony:
    • checking connection to all enode from the BLOCKCHAIN_ENODE_RPC_URL list
    • set server url with alive enode by default.
    • running the keystores synchronization:
      • load all servers from the BLOCKCHAIN_SYNCHRONY_SERVER_URL list
      • compare all files from keystores on all servers (like a many to many).
      • copying keystore files to the server when it does not exist there.

Functionality

Properties:

  1. web3 - contains a web3 object with connection to alive enode.
  2. truffleWeb3 - contains a web3 object from truffle version.
  3. defaultDonateTokens - contains amount of tokens to donate by default (in wei from $BLOCKCHAIN_DEFAULT_DONATE_TOKENS).
  4. defaultDonateEther - contains a web3 object with connection to alive enode.
  5. accounts - contains list of account (should be initialized before).
  6. commission - contains amount of contract commission by default.
  7. InvestmentContract() - returns the initialized truffle contract object.
  8. initContract(artifactJSON) - initializes truffle contract object by "artifactJSON".

note: artifactJSON is a result of compilation of the "*.sol" file of contract and contains keys like "abi", "network", "contractName", "bytecode" and others.

Transactions:

1. Creates transaction of setOrder to set the new order to blockchain

setOrder(buyerAddress, 
         buyerPrivatKey, 
         sellerAddress, 
         escrowAddress, 
         orderUuid, 
         amount, 
         personId, 
         handlers = {}, 
         sig = signature)
  • Function parameters:

    • "buyerAddress" - address of buyer which pays for a transaction and order
    • "buyerPrivatKey" - passkey from buyerAddress
    • "sellerAddress" - address of the seller which gives a product to sell (this address gets tokens by order without commission after order complete)
    • "escrowAddress" - address of escrow which has access to "complete" or "cashback" this order and which stores awaiting tokens of the order and gets commission after the order receives "complete" status
    • "orderUuid" - uuid of new order
    • "amount" - token amount of new order (main value)
    • "personId" - this parameter is necessary to update the tokens balance on DB by handlers
    • "handlers" - object of handlers (in this case required
      {
          userBalanceUpdate: userBalanceUpdate, 
          updateTimeLine: updateTimeLine, 
          publishToBroker: publishToBroker, 
          userUpdateAccountsFromOrderContract: userUpdateAccountsFromOrderContract
      }
      
      where values of keys are functions)
    • "sig" - object, necessary to set the signature of order (for example
      {
          sig: "0x0", 
          protocol: ""
      }
      
      by default)
  • Body of function:

    (return typeof Promise())

    Function in its body:

    • creates instance of contract
    • creates watch for the LogNewOrder() event from the setOrder() function of contract
    • gets an estimate of the transaction gas
    • creates body and config of transaction according to input parameters
    • creates transaction to setOrder() function of contract in blockchain
    • gets result of the created transaction, as a hash of transaction
    • if "handlers" has a userBalanceUpdate function, then starts it with parameters
  • Function results:

    • starts lockAccount function
    • exit as "resolve(hash)" or some error.

    for example:
    hash = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"

2. Creates transaction of cashBack order to the blockchain (returns the full cost of order to buyer in tokens).

cashback(orderUuid, ownerAddress, ownerKey, handlers = {})
  • Function parameters:

    • "orderUuid" - uuid of new order
    • "ownerAddress" - address of escrow which has access to "complete" or "cashback" order
    • "ownerKey" - passkey from ownerAddress
    • "handlers" - object of handlers (in this case required
      {
          updateTimeLine: updateTimeLine, 
          publishToBroker: publishToBroker, 
          userUpdateAccountsFromOrderContract: userUpdateAccountsFromOrderContract
      }
      
      where values of keys are functions)
  • Body of function:

    (return typeof Promise())

    Function in its body:

    • creates instance of contract
    • creates watch for the CashBack() event from the cashBack() function of contract
    • gets an estimate of the transaction gas
    • creates body and config of transaction according to input parameters
    • creates transaction to cashBack() function of contract in blockchain
    • gets result of the created transaction, as a hash of transaction
  • Function results:

    • starts lockAccount function
    • exit as "resolve(hash)" or some error.

    for example:
    hash = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"

3. Creates transaction of completed order to the blockchain (sends order tokens amount to seller and send the commission to escrow address).

closeOrder(orderUuid, commission, ownerAddress, ownerKey, handlers = {})
  • Function parameters:

    • "orderUuid" - uuid of new order
    • "commission" - commission for this order in wei
    • "ownerAddress" - address of escrow which has access to "complete" or "cashback" order
    • "ownerKey" - tpasskey from ownerAddress
    • "handlers" - object of handlers (in this case required
      {
          updateTimeLine: updateTimeLine, 
          publishToBroker: publishToBroker, 
          userUpdateAccountsFromOrderContract: userUpdateAccountsFromOrderContract
      }
      
      where values of keys are functions)
  • Body of function:

    (return typeof Promise())

    Function in its body:

    • creates instance of contract
    • creates watch for the Completed() event from the completed() function of contract
    • gets an estimate of the transaction gas
    • creates body and config of transaction according to input parameters
    • creates transaction to completed() function of contract in blockchain
    • gets result of the created transaction, as a hash of transaction
  • Function results:

    • starts lockAccount function
    • exit as "resolve(hash)" or some error.

    for example:
    hash = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"

4. Creates transaction of transfer tokens to the blockchain.

send(addressFrom, privateKey, addressTo, amount, handlers = {})
  • Function parameters:

    • "addressFrom" - sender address
    • "privateKey" - passkey from sender
    • "addressTo" - recipient address
    • "amount" - volume of tokens to send (in wei)
    • "handlers" - object of handlers (in this case required
      {
          publishToBroker: publishToBroker,
          updateTimeLine: userBalanceSynchronize, 
      }
      
      where values of keys are functions)
  • Body of function:

    (return typeof Promise())

    Function in its body:

    • creates instance of contract
    • creates watch for the Transfer() event from the transfer() function of contract
    • gets an estimate of of transaction gas
    • creates body and config of transaction according to input parameters
    • creates transaction to transfer() function of contract in blockchain
    • gets result of the created transaction, as a hash of transaction
  • Function results:

    • starts lockAccount function
    • exit as "resolve(hash)" or some error.

    for example:
    hash = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"

5. Creates transaction of gas sending in the blockchain.

donate(ownerAddress, ownerKey, addressTo, amount)
  • Function parameters:

    • "ownerAddress" - address of the owner of the contract (or another users having a lot of gas)
    • "ownerKey" - passkey from owner
    • "addressTo" - recipient address
    • "amount" - amount of gas to send (in ether)
  • Body of function:

    (return typeof Promise())

    Function in its body:

    • creates body and config of transaction according to input parameters
    • creates transaction in blockchain
    • gets result of the created transaction, as a hash of transaction
  • Function results:

    • starts lockAccount function
    • exit as "resolve(hash)" or some error.

    for example:
    hash = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"

6. Creates transaction of mint tokens to the blockchain.

topup(ownerAddress, ownerKey, addressTo, amount, handlers = {})
  • Function parameters:

    • "ownerAddress" - address of the owner of the contract
    • "ownerKey" - passkey from owner
    • "addressTo" - recipient address
    • "amount" - amount of tokens to send (in wei)
    • "handlers" - object of handlers (in this case required
      {
          publishToBroker: publishToBroker,
          updateTimeLine: userBalanceSynchronize, 
      }
      
      where values of keys are functions)
  • Body of function:

    (return typeof Promise())

    Function in its body:

    • creates instance of contract
    • creates watch for the Mint() event from the mint() function of contract
    • gets an estimate of the transaction gas
    • creates body and config of transaction according to input parameters
    • creates transaction to mint() function of contract in blockchain
    • gets result of the created transaction, as a hash of transaction
  • Function results:

    • starts lockAccount function
    • exit as "resolve(hash)" or some error.

    for example:
    hash = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"

7. Creates transaction of transferOwnership to the blockchain.

transferOwnership(ownerAddress, ownerKey, newOwnerAddress)
  • Function parameters:

    • "ownerAddress" - address of the owner of the contract
    • "ownerKey" - passkey from owner
    • "newOwnerAddress" - new owner address
  • Body of function:

    (return typeof Promise())

    Function in its body:

    • creates instance of contract
    • gets an estimate of the transaction gas
    • creates body and config of transaction according to input parameters
    • creates transaction to transferOwnership() function of contract in blockchain
    • gets result of the created transaction, as a hash of transaction
  • Function results:

    • starts lockAccount function
    • exit as "resolve(hash)" or some error.

    for example:
    hash = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"

8. Creates transaction of withdrawEth to the blockchain.

withdrawEth(address, key, amount, recipientAddress, handlers = {})
  • Function parameters:

    • "address" - address of the user, which withdraws tokens
    • "key" - passkey from user address
    • "amount" - amount of tokens to withdraw (in wei)
    • "recipientAddress" - address of recipient from the main network, to send the real ETH to
    • "handlers" - object of handlers (in this case required
      {
          changeBalanceByAddress: changeBalanceByAddress,
          updateTimeLine: userBalanceSynchronize, 
      }
      
      where values of keys are functions)
  • Body of function:

    (return typeof Promise())

    Function in its body:

    • sends tokens from user to owner in private network (by send() function)
    • creates transaction of ETH transfer in main network
    • if transaction in main network was created, then returns its hash, otherwise sends tokens from owner back to user in private network (by send() function)
    • gets result of the created transaction, as a hash of transaction from main network
  • Function results:

    • starts lockAccount function
    • exit as "resolve(hash)" or some error.

    for example:
    hash = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"

Calls:

  1. Get tokens balance getBalance(address, handlers = {})

    • Function parameters:

      • "address" - user address
      • "handlers" - object of handlers (in this case required
        {
            userBalanceSynchronize: userBalanceSynchronize, 
        }
        
        where values of keys are functions)
    • Body of function:

      (return typeof Promise())

      Function in its body:

      • creates instance of contract
      • creates body and config of call according to input parameters
      • puts call to balanceOf() function of contract in blockchain
      • receives results of balanceOf
      • if "handlers" has a userBalanceSynchronize function, then starts it with parameters
    • Function reluts:

      • exit as "resolve(balance)" or some error.

      note: balance is of BigNumber type (from bignumber.js)

  2. Get order signature orderSignature(orderUuid)

    • Function parameters:

      • "orderUuid" - uuid of existing order
    • Body of function:

      (return typeof Promise())

      Function in its body:

      • creates instance of contract
      • creates body and config of call according to input parameters
      • puts call to getSignature() function of contract in blockchain
      • receives results of getSignature
    • Function results:

      • exit as "resolve({signature: result})" or some error.

      note (as example):
      result = ["0x1234abcdef123", "list,of,keys"]

       0 - hash of signature
       1 - comma-separated list of keys of protocol as string
      
  3. Get accounts list getAccounts()

    • Body of function:

      (return typeof Promise())

      Function in its body:

      • puts call to getAccounts() function of web3.eth
      • receives results of getAccounts
      • saves list of accounts to "accounts" variable
    • Function results:

      • exit as "resolve({accs: accs})" or some error.

      note (as example):
      accs = ["0x1234abcdef123", "0x2234abcdef123", .....].
      More can be found in the official docs

  4. Get order object getOrder(orderUuid)

    • Function parameters:

      • "orderUuid" - uuid of existing order
    • Body of function:

      (return typeof Promise())

      Function in its body:

      • creates instance of contract
      • creates body and config of call according to input parameters
      • puts call to getOrder() function of contract in blockchain
      • receives results of getOrder
    • Function results:

      • exit as "resolve({order: result})" or some error.

      note (as example):
      result =
      [
      "0xaf827946fbcc35457fa3a1b6541b9961c60b13ef",
      "0x3123622a72daaf932539801f07c4b39b605d0892",
      "0x0000000072daaf932539801f07c4b39b605d0892",
      "100000000000",
      false,
      false,
      "0x962118611f1cdc7bb19877ff73b01f9e9df90443",
      ]

       0 - seller address
       1 - buyer address
       2 - order uuid
       3 - amount, of a BigNumber type (from bignumber.js)
       4 - flag of completed
       5 - flag of cashback
       6 - escrow address
      
  5. Get contract address getContractAddress()

    • Body of function:

      (return typeof Promise())

      Function in its body:

      • creates instance of contract
      • creates body and config of call according to input parameters
      • puts call to getContractAddress() function of contract in blockchain
      • receives results of getContractAddress
    • Function results:

      • exit as "resolve({contract: result})" or some error.

      note (as example):
      result = "0xaf827946fbcc35457fa3a1b6541b9961c60b13ef"

  6. Get owner address getOwner()

    • Body of function:

      (return typeof Promise())

      Function in its body:

      • creates instance of contract
      • creates body and config of call according to input parameters
      • puts call to getOwner() function of contract in blockchain
      • receives results of getOwner
    • Function results:

      • exit as "resolve(result)" or some error.

      note (as example):
      result = "0xaf827946fbcc35457fa3a1b6541b9961c60b13ef"

Others

  1. Synthesize a private key synthesizePrivateKey(passkey)

    • Function results:

      • "passkey" - user password to synthesize a private key
    • Body of function:

      Function in its body:

      • use cryptojs.HmacSHA512 to create complex key
    • Function results:

      • exit as "return hash" or "return false".

      for example:
      hash = "c6d21e16e10f85eb7150750c403fe31a8cfb33b6f9dc5612939409b1dbf9356e 538a8ebddc78bcc4ffb5fd481b8c9a0db07d150c153e35558a402a217bb9eca8"

  2. Synthesize a private key productSignature(fullProtocol)

    • Function parameters:

      • "fullProtocol" - object of protocol. For example:
        {
            color: "red",
            size: 2, 
            price: 1.5, 
            count: 7, 
            name: "apple", 
        }
        
    • Body of function:

      (return typeof Promise())

      Function in its body:

      • use cryptojs.HmacSHA512 to translate protocol object into protocol product with format for blockchain
    • Function results:

      • exit as "resolve({sig: sig, protocol: protocol})" or "resolve({sig: "0x0", protocol: ""})".

      note (as example):
      protocol = "color,size,price,count,name"
      sig = "0x1234abcdef123...."

  3. Synthesize a private key signatureCheck(protocol, blockchainSign)

    • Function parameters:

      • "protocol" - object of protocol. For example:
        {
            color: "red",
            size: 2, 
            price: 1.5, 
            count: 7, 
            name: "apple", 
        }
        
      • "blockchainSign" - hash of signature
    • Body of function:

      (return typeof Promise())

      Function in its body:

      • runs productSignature() with protocol to generate signature and compare with blockchainSign
    • Function results:

      • exit as "resolve(true)", "resolve(false)" or some error.
  4. Change passkey changePasskey(address, oldKey, newKey)

    • Function parameters:

      • "address" - users address
      • "oldKey" - old user passkey
      • "newKey" - new user passkey
    • Body of function:

      (return typeof Promise())

      Function in its body:

      • synthesizes keys
      • creates body for request to synchrony server to change passkey
      • runs the correcting function and updates all enodes in the environment list
    • Function results:

      • exit as "resolve({status: true})", "resolve({status: false})" or some error.
  5. Waits transaction complete waitTransactionComplete(hash, interval)

    • Function parameters:

      • "hash" - transaction hash
      • "interval" - interval for request to blockchain to get transaction data
    • Body of function:

      (return typeof Promise())

      Function in its body:

      • gets transaction data
      • searchs the blockNumber key in transaction data
      • runs the recursive function or exits
    • Function results:

      • exit as "resolve(data)" or some error.

      note: more about this data can be found here

  6. Validate blockchain address isAddress(address)

    • Function parameters:

      • "address" - users address
    • Body of function:

      Function in its body:

      • uses web3.isAddress() to check address
    • Function results:

      • exit as "return true" or "return false".
  7. Unlock account unlockAccount(address, key, mainNetwork = false)

    • Function parameters:

      • "address" - user address
      • "key" - key from users address
      • "mainNetwork" - flag to select network for web3-blockchain connection (private or main).
    • Body of function:

      Function in its body:

      • uses personal.unlockAccount() to unlock address
    • Function results:

      • exit as "resolve({status: true})" or "reject(err)".
  8. Lock account lockAccount(address, mainNetwork = false)

    • Function parameters:

      • "address" - user address
      • "mainNetwork" - flag to select network for web3-blockchain connection (private or main).
    • Body of function:

      Function in its body:

      • uses personal.lockAccount() to lock address
  9. Create address on blockchain createAddress(passkey)

    • Function parameters:

      • "passkey" - synthesized password
    • Body of function:

      (return typeof Promise())

      Function in its body:

      • uses "passkey" or synthesizes passkey from "password" (by default) to create account
    • Function results:

      • exit as "resolve(address)" or some error.

      note (as example):
      address = "0xb323c437c12f5c3c7dce2145cfc92ef0a1d65566"

Handlers

handlers - an object containing functions for callback processings. Its main purpose is DB data updating, updating status of order, or may be other local data updatings.

Used in this version

  let handlers = {
    changeBalanceByAddress: changeBalanceByAddress,
    userBalanceSynchronize: userBalanceSynchronize,
    userBalanceUpdate: userBalanceUpdate,
    userUpdateAccountsFromOrderContract: userUpdateAccountsFromOrderContract,
    updateTimeLine: updateTimeLine,
    publishToBroker: process.env.KAFKA_ENABLED === 'true' ? shared.publishToBroker : null
  };
  1. changeBalanceByAddress - function with parameters (address, amount, type). This function is used to increase or decrease user balance (move its value "up" od "down").

    • Function header:

      • "address" - user address from private blockchain network
      • "amount" - value (in wei) by which the balance is about to be changed (this amount is to be added to or substracted from the user balance in local DB)
      • "type" - string containing type of changes being made (either "up" or "down" only)
    • Example:

        function changeBalanceByAddress(address, amount, type) {
          findUserFromAddress(address).then(function (userId) {
            userBalanceUpdate(userId.id, amount, type).then(function (updated) {
              logger.debug("* user balance updated by address");
            }).catch(function (err) {
              logger.debug('* updated DB balance before withdraw, error: ' + err);
            });
          }).catch(function (err) {
            logger.debug("* " + err);
          });
        }
      
  2. userBalanceSynchronize - function with parameter (address), returns Promise type. This function is used to synchronize balance of user from blockchain to DB

    • Function header:
      • "address" - user address in private blockchain network

    In returned promise "resolve" and "reject" should be used for correct functioning of .then() and .catch()

    • Example:
        function userBalanceSynchronize(address) {
          return new Promise(function (resolve, reject) {
            realnetOrders.getBalance(address).then(function (balance) {
              findUserFromAddress(address).then(function (personId) {
                if (personId.id) {
                  models.Entity.findOne({where: {id: personId.id}}).then(person => {
                    if (person) {
                      let updatedData = person.data;
                      if (Number(updatedData.balance) !== Number(balance)) {
                        updatedData.balance = balance;
                        person.update({
                          data: updatedData
                        }).then(updated => {
                          logger.debug('* ' + address + ' balance updated');
                          resolve({status: 'user balance updated'});
                        });
                      } else {
                        logger.debug('* ' + address + ' not need to update balance');
                        resolve({status: 'not need to update balance'});
                      }
                    } else {
                      logger.debug('* user not found');
                      reject("User not found");
                    }
                  }).catch(function (err) {
                    logger.debug('* models.Entity.findOne err : ', err);
                    reject('User not found; err : ' + err);
                  });
                } else {
                  logger.debug('* findUserFromAddress user not found');
                  reject('findUserFromAddress error; user not found !!!');
                }
              }).catch(function (err) {
                logger.debug('* findUserFromAddress error: ', err);
                reject('find user from address error: ' + err);
              });
            }).catch(function (err) {
              logger.debug('* getBalance error: ', err);
              reject('get token balance error: ' + err);
            });
          });
        }
      
  3. userBalanceUpdate - function with parameter (userId, amount, type), returns Promise type. This function is used to increase or decrease user balance (changing it "up" or "down").

    • Function header:
      • "userId" - user id from DB
      • "amount" - value (in wei) by which the balance is about to be changed (this amount is to be added to or substracted from the user balance in local DB)
      • "type" - string containing type of changes being made (either "up" or "down" only)

    In returned promise "resolve" and "reject" should be used for correct functioning of .then() and .catch()

    • Example:
        function userBalanceUpdate(personId, amount, type) {
          return new Promise(function (resolve, reject) {
            models.Entity.findOne({where: {id: personId}})
              .then(person => {
                if (person) {
                  let updatedData = person.data;
                  if (type === 'up') {
                    updatedData.balance = Number(updatedData.balance) + Number(amount);
                  }
                  if (type === 'down' && Number(updatedData.balance) >= Number(amount)) {
                    updatedData.balance = Number(updatedData.balance) - Number(amount);
                  }
                  person.update({
                    data: updatedData
                  }).then(updated => {
                    resolve(updated);
                  }).catch(function (err) {
                    reject("Error user updated ");
                  });
                } else {
                  reject("User not found");
                }
              })
              .catch(function (err) {
                reject("User not found");
              });
          });
        }
      
  4. userUpdateAccountsFromOrderContract - function with parameter (orderUuid), returns Promise type. This function is used to get data of order from blockchain and to update buyer and seller balances in DB

    • Function header:
      • "orderUuid" - uuid of order from DB

    In returned promise "resolve" and "reject" should be used for correct functioning of .then() and .catch()

    • Example:
        function userUpdateAccountsFromOrderContract(orderUuid) {
          return new Promise(function (resolve, reject) {
            let sellerComplete = false;
            let buyerComplete = false;
            // get order by uuid from blockchain
            realnetOrders.getOrder(orderUuid).then(function (orderObj) {
              // architecture for synchronize seller token balance
              userBalanceSynchronize(orderObj.order[0]).then(function (sellerUpdate) {
                if (buyerComplete) resolve(sellerUpdate);
                sellerComplete = true;
              }).catch(function (err) {
                if (buyerComplete) reject('buyer update balance error : ' + err);
                sellerComplete = true;
              });
              // architecture for synchronize buyer token balance
              userBalanceSynchronize(orderObj.order[1]).then(function (buyerUpdate) {
                if (sellerComplete) resolve(buyerUpdate);
                buyerComplete = true;
              }).catch(function (err) {
                if (sellerComplete) reject('seller update balance error : ' + err);
                buyerComplete = true;
              });
            }).catch(function (err) {
              reject('order from blockchain error: ' + err);
              logger.debug('* order from blockchain error: ', err);
            });
          });
        }
      
  5. updateTimeLine - function with parameter (orderUuid) This function is used to update status after getting events from blockchain (in our case it updates timeline list)

    • Function header:

      • "orderUuid" - uuid of order from DB
    • Example:

        function updateTimeLine(orderUuid) {
          models.Entity.findOne({where: {id: orderUuid}})
            .then(order => {
              if (order) {
                logger.debug("* found order ");
                let updatedData = order.data;
                let timeline = {
                  message: order.data && order.data.status === 'open' ?
                    'Transaction confirmation in blockchain on opened order.' :
                    'Transaction confirmation in blockchain closed order.',
                  time: new Date()
                };
                if (updatedData.timeline) {
                  updatedData.timeline.push(timeline);
                } else {
                  updatedData.timeline = [timeline];
                }
                order.update({
                  data: updatedData
                }).then(updated => {
                  logger.debug('* ' + orderUuid + ' order timeline updated');
                });
              } else {
                logger.debug("* " + orderUuid + " order not found");
              }
            })
            .catch(function (err) {
              logger.debug("* " + orderUuid + " order not found; error: " + err);
            });
        }
      
  6. publishToBroker - function with parameter (key, value) This function is used to send the object from event.

    • Function header:

      • "key" - key of the event
      • "value" - value of the event (object type)
    • Available keys are:

      • "blockchain_event_order_open": from setOrder() -> LogNewOrder<blockchain event>().watch() -> instanceOfContract.setOrder()
      • "blockchain_event_order_cashback": from cashback() -> CashBack<blockchain event>().watch() -> instanceOfContract.cashBack()
      • "blockchain_event_order_complete": from closeOrder() -> Completed<blockchain event>().watch() -> instanceOfContract.completed()
      • "blockchain_event_mint": from topup() -> Mint<blockchain event>().watch() -> instanceOfContract.mint()
      • "blockchain_event_transfer": from send() -> Transfer<blockchain event>().watch() -> instanceOfContract.transfer()
    • Example:

        // doing something to initialize the "socket"
        
        function publishToBroker(key, value) {
          if(socket) {
            socket.emit(key, value);
          }
        }
      

Current Tags

  • 1.0.3                                ...           latest (2 years ago)

2 Versions

  • 1.0.3                                ...           2 years ago
  • 1.0.2                                ...           2 years ago
Maintainers (1)
Downloads
Today 0
This Week 2
This Month 6
Last Day 0
Last Week 0
Last Month 2
Dependencies (8)
Dev Dependencies (2)
Dependents (0)
None

Copyright 2014 - 2016 © taobao.org |