Usage in Dapps

Using COFFEmask in your applications is easy enough

Usage for the browser or desktop applications

If the application is desktop, the "desktop" variable must contain "true", if by the browser, then "false"

The finished example can be downloaded here https://wiki.coffe.io/files/coffemask_example.zip

Local socket connection

const ws = new WebSocket('ws://127.0.0.1:28000');
ws.addEventListener('open', function (event) {
    $('#result_socket').html('WSS connected')
    var data = { req:true, action:'connected' };
    ws.send(JSON.stringify(data), { binary: false });
});

Session creation

let session = make_session();
function make_session(){
   var result           = '';
   var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!?@%';
   var charactersLength = characters.length;
   for ( var i = 0; i < 24; i++){
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   return result;
}

Authorization

function auth(desktop){
    console.log('PAGE send auth');
    var data = { req:true, session:$('#session').val(), action:'auth' };
    if(desktop){
        ws.send(JSON.stringify(data), { binary: false });
    }else{
        window.postMessage(data, '*');
    }
};

Transaction

TRX DATA: {"account":"eosio.token","name":"transfer","data":{"from":"rionass1ffor","memo":"","quantity":"1.0000 CFF","to":"coffe"}}

function transaction(desktop){
    console.log('PAGE send transaction');
    var data = { req:true, session:$('#session').val(), action:'transaction', data:JSON.parse($('#transaction').val()) };
    if(desktop){
        ws.send(JSON.stringify(data), { binary: false });
    }else{
        window.postMessage(data, '*');
    }
};

Action

SMART CONTRACT DATA: {"account":"dappsunity3d","name":"injectdata","data":{"from":"rionass1ffor","value":"TEST ONE val"}}

function transaction_smart(desktop){
    console.log('PAGE send transaction_smart');
    var data = { req:true, session:$('#session').val(), action:'transaction', data:JSON.parse($('#transaction_smart').val()) };
    if(desktop){
        ws.send(JSON.stringify(data), { binary: false });
    }else{
        window.postMessage(data, '*');
    }
};

Receiving messages

window.addEventListener('message', readMessage);
ws.addEventListener('message', readMessage);
function readMessage(event){
    console.log('readMessage', event.data)
    event = event.data
    try{
        if(typeof event == 'string'){
            event = JSON.parse(event)
        }
    }catch(e){
        console.log('readMessage', e)
    }
    if(event.session == $('#session').val() && event.res){
        console.log('PAGE receive message:', event);
        $('#result').html(JSON.stringify(event))
    }
}
Still need help? Get in touch!
Last updated on 31st Dec 2021