Overview

WASM wallet client is a thin wrapper around Beam client library build into WASM using Emscripten toolchain. This wrapper allows to run BEAM wallet inside any browser supporting WebAssembly and it provides the regular BEAM wallet API to communicated with it from external(javascript) code. It's available via npm for different network types:

API

WASM wallet client module exports following classes:

  • WasmWalletClient - the main object provides a set of static and member methods to control the wallet. It could be used to implement BEAM wallet as a browser extension
    MethodDescription
    ConstructorCreates new regular wallet object
    Headless constructorCreates new headless wallet object
    startWalletStarts the wallet in the background thread
    stopWalletAsynchronously stops the wallet running in the background
    isRunningChecks if the wallet is running
    isHeadlessChecks if the wallet is headless, i.e. without master and owner keys
    sendRequestSends API request to the wallet
    subscribeSubscribes for API responses
    unsubscribeUnsubscribes from response notifications
    setSyncHandlerSets synchronization handler, allows to track sync progress
    setApproveSendHandlerSets handler which allows to approve or reject any send operation initiated by DAPPs
    setApproveContractInfoHandlerSets handler which allows to approve or reject any operation which requires user's attention from application shader
    createAppAPIAsynchronously creates new application wallet API for given application
    importRecoveryAsynchronously imports recovery data
    GeneratePhraseGenerates new seed phrase
    IsAllowedWordChecks if given word is in the dictionary of the words allowed to be used in seed phrases
    IsValidPhraseValidates given seed phrase
    ConvertTokenToJsonConverts given BEAM address to json
    ConvertJsonToTokenPacks transaction parameters presented as JSON object into BEAM address
    MountFSAsynchronously mounts WASM filesystem to the roor of IndexDB
    CreateWalletCreates new wallet database
    DeleteWalletDeletes given wallet database from IndexDB
    IsInitializedEnsures that database was created
    CheckPasswordTests if given password fits to the database
  • AppAPI - a proxy API object, it gives limited wallet API for external web applications, which want to work with BEAM wallet
    MethodDescription
    callWalletApiAllows to call wallet API methods from application
    setHandlerSets handler to receive response for API request
  • AppAPICallback - a callback object for applications, it allows the wallet to control the action which application want to perform.
    MethodDescription
    sendApprovedApproves send request from application
    sendRejectedRejects send request from application
    contractInfoApprovedApproves contract call
    contractInfoRejectedRejects contract call

WasmWalletClient

GeneratePhrase

WasmWalletClient.GeneratePhrase()

Generates new seed phrase

Return value

  • seed phrase, a string of 12 words from the dictionary separated separated by

Example

 var phrase = Module.WasmWalletClient.GeneratePhrase()
 console.log('seed phrase is: ', phrase);
 // OUTPUT: seed phrase is:  legend hurdle erode ribbon pass exit basket doll sorry version muscle brain

IsAllowedWord

WasmWalletClient.IsAllowedWord(word : String)

Checks if given word is in the dictionary of the words allowed to be used in seed phrases

Parameters

  • word : the word to be checked

Return value

  • true if word is in the dictionary otherwise false

Example

  if (Module.WasmWalletClient.IsAllowedWord('hurdle')) {
      console.log("Word is allowed");
  }

IsValidPhrase

WasmWalletClient.IsValidPhrase(phrase : String)

Validates given seed phrase

Parameters

  • phrase : a string of the words separated by

Return value

  • true if seed phrase is valid otherwise false

ConvertTokenToJson

WasmWalletClient.ConvertTokenToJson(token : String)

Converts given BEAM address to json

Parameters

  • token : address to to unpack data

Return value

  • json object with address parameters unpacked from given string

Notes

  • in beam address(token) is binary packed set the key-value parameters presented as base58 string

ConvertJsonToToken

WasmWalletClient.ConvertJsonToToken(json : String)

Packs transaction parameters presented as JSON object into BEAM address

Parameters

  • json : parameters of the transaction

Return value

  • base58 encoded string of packed parameters

MountFS

WasmWalletClient.MountFS(callback : function)

Asynchronously mounts WASM filesystem to the roor of IndexDB

Parameters

  • callback : mounting completion handler, if an error occurred, it will be provided as a parameter to this function.

Return value

  • none

Notes

  • This method should be called before any action which implies work with filesystem

Example

 Module.WasmWalletClient.MountFS(function(error) {
   if (error != null) {
     console.log("mounted");
     var walletClient = new Module.WasmWalletClient("/beam_wallet/wallet.db",
                                                  "123",
                                                  "eu-node01.masternet.beam.mw:8200");
   }
 }

CreateWallet

WasmWalletClient.CreateWallet(seedPhrase : String, database : String, password : String)

Creates new wallet database

Parameters

  • seedPhrase: seed pharse for the wallet
  • database : path to the database in IndexedDB
  • password : password to the new wallet database

Return value

  • none

Notes

  • Ensure that MountFS() has been called before

Example

 let phrase = Module.WasmWalletClient.GeneratePhrase();
 Module.WasmWalletClient.CreateWallet(phrase, "/beam_wallet/wallet.db", "123");

DeleteWallet

WasmWalletClient.DeleteWallet(database : String)

Deletes given wallet database from IndexDB

Parameters

  • database : path to the database file

Return value

  • none

Notes

  • Ensure that MountFS() has been called before

IsInitialized

WasmWalletClient.IsInitialized(database : String)

Ensures that database was created

Parameters

  • database : the path to the database

Return value

  • true if database is created and initialized, otherwise false

Notes

  • Ensure that MountFS() has been called before

CheckPassword

WasmWalletClient.CheckPassword(database : String, password : String, callback : function)

Tests asynchronously if given password fits to the database

Parameters

  • database : path to the database
  • password : password to test
  • callback : asynchronously returns the result of the test

Return value

  • none

Notes

  • Ensure that MountFS() has been called before

Example

  Module.WasmWalletClient.CheckPassword("/beam_wallet/wallet.db", "13", (res) => {
  if (res)
    console.log("Password is correct")
  else
    console.log("Password is not correct")
  })

Constructor

WasmWalletClient(database : String, password : String, nodeURL : String)

Creates new wallet client object

Parameters

  • database : path to encrypted database in browser's IndexDB
  • password : password to the database
  • nodeURL : URL to BEAM node to communicate with

Return value

  • object of the wallet client

Notes

  • wallet client can communicate with node over Web Sockets only, ensure that node located by nodeURL has WebSocket proxy enabled
  • ensure that MountFS() has been called before

Example

 var walletClient = new Module.WasmWalletClient("/beam_wallet/wallet.db",
                                                "123",

                                                "eu-node01.masternet.beam.mw:8200");

Headless constructor

WasmWalletClient(nodeURL : String)

Creates new headless wallet client object. It doesn't have a master key. The wallet with such a database can communicate with the node, but cannot make transactions or detect any UTXO event. It can generate public keys, but they all are temporary and provided only for the reason to have viewer access to dapps

Parameters

  • nodeURL : URL to BEAM node to communicate with

Return value

  • object of the wallet client

Notes

  • wallet client can communicate with node over Web Sockets only, ensure that node located by nodeURL has WebSocket proxy enabled
  • headless wallet doesn't require MountFS() to be called before

Example

 var walletClient = new Module.WasmWalletClient("eu-node01.masternet.beam.mw:8200");

startWallet

function startWallet()

Starts the wallet in the background thread

Notes

  • wallet client can communicate with node over Web Sockets only, ensure that node located by nodeURL has WebSocket proxy enabled

stopWallet

function stopWallet(callback : function)

Asynchronously stops the wallet running in the background

Parameters

  • callback : calls when wallet has stopped. In this callback it is safe to delete the wallet database

Return value

  • none

Example

  wc.stopWallet(()=> {
    console.log("is running: " + wc.isRunning()) // false
  }

isRunning

function isRunning()

Checks if the wallet is running

Parameters

  • none

Return value

  • true if the wallet is running, false otherwise

isHeadless

function isHeadless()

Checks if the wallet is headless, i.e. without master and owner keys

Parameters

  • none

Return value

  • true if the wallet is headless, false otherwise

sendRequest

function sendRequest(jsonRequest : String)

Sends API request to the wallet

Parameters

  • jsonRequest : API request

Return value

  • none

Notes

Example

 walletClient.sendRequest(JSON.stringify({
     jsonrpc: '2.0',
     id: 5,
     method: 'wallet_status'
 }));

subscribe

function subscribe(callback : function)

Subscribes for API responses

Parameters

  • callback : function which is called when response arrived

Return value

  • index of the subscription

Example

  var i = walletClient.subscribe((r)=> {
      console.log("response: " + r)
  });

unsubscribe

function unsubscribe(index : Number)

Unsubscribes from response notifications

Parameters

  • index : index of the subscription

Return value

  • none

setSyncHandler

function setSyncHandler(handler : function)

Sets synchronization handler, allows to track sync progress

Parameters

  • handler : called each time wallet notifies about sync progress

Return value

  • none

Example

 walletClient.setSyncHandler((done, total) => {
    console.log("sync [" + done + "/" + total + "]");
 });

setApproveSendHandler

function setApproveSendHandler(handler : function)

Sets handler which allows to approve or reject any send operation initiated by DAPPs

Parameters

  • handler : function called each time application wants to send assets from the wallet

Return value

  • none

Example

 walletClient.setApproveSendHandler((request, info, cb)=>{
     console.log("Request: " + request);
     console.log("Info: " + info);
     cb.sendApproved(request);
     //cb.sendRejected(request);
 }) 

setApproveContractInfoHandler

function setApproveContractInfoHandler(handler : function)

Sets handler which allows to approve or reject any operation which requires user's attention from application shader

Parameters

  • handler

Return value

  • none

Example

 walletClient.setApproveContractInfoHandler((request, info, amounts, cb)=>{
     console.log("Request: " + request);
     console.log("Info: " + info);
     cb.contractInfoApproved(request);
     //cb.contractInfoRejected(request);
 }) 

createAppAPI

function createAppAPI(appid : String, appname : String, callback : function)

Asynchronously creates new application wallet API for given application

Parameters

  • appid : ID of the application
  • appname : the name of the app
  • callback : the callback with API object in the case of success

Example

 console.log("calling API...");
 wc.createAppAPI("appid", "appname", (api)=>{
    api.setHandler((r)=> {
       console.log("API response: " + r)
    })
    api.callWalletApi(JSON.stringify({
       jsonrpc: '2.0',
        id: 5,
        method: 'wallet_status'
    }));        
 });

importRecovery

function importRecovery(recoveryData: Uint8Array, callback: function(error, done, total))

Asynchronously imports recovery data

Parameters

  • recoveryData : downloaded recovery data
  • callback : callback function, which allows to handle errors via error parameter and to report progress using done and total

Example

 // download function should be defined by user
 download("recovery.bin", function(error, data) {
    if (error == null) {
        console.log("downloaded recovery")
        walletClient.importRecovery(data, function(error, done, total) {
            if (error == null) {
                console.log(`Restoring ${done}/${total}`)
            } else {
                console.log(`Failed to recover: ${error}`)
            }
        });
        
    } else {
        console.log("failed to download recovery")
    }

});

AppAPI

callWalletApi

setHandler

AppAPICallback

sendApproved

sendRejected

contractInfoApproved

contractInfoRejected