Lyly Sara

Lyly Sara

1550050300

The javascript function is returning a promise and the promise is used in the solidity function which gives the error of invalid arguments

I am trying to make a Dapp which maintains the various versions of a trade(new versions are created when we update the data of trade). I am using javascript we3.js api to call my solidity functions through javascript. I have a function which displays the data when we search using a field called 'client'. When I am clicking the button to search on basis of client, it returns an error. I am using promises in javascript, but it seems to me that the javascript function is returning a promise which is undefined to solidity function. But after the error the javascript function is returning the expected values(I checked using console.log).

I have tried using async/await but that doesnt seems to do the trick.

My Javascript code:-

getVersion:async function(i){

var returnedLatestVersion;

App.contracts.Trades.deployed().then(async function(instance){

await instance.getLatestVersionOfTrade.call(i).then(function(a){      

  returnedLatestVersion = a;
  console.log("test:"+returnedLatestVersion+",a:"+a);

}).catch(function(err){
console.log(err)
})
console.log("test2="+returnedLatestVersion);
return await returnedLatestVersion;    

})
},

searchByClient: function(){

var tradesInstance;

var client = $(‘#clientSearch’).val();

var tradeResults = $(“#tradesResult”);
tradeResults.empty();

App.contracts.Trades.deployed().then(function(instance){
tradesInstance = instance;

return tradesInstance.getClientData.call(client).then(async function(returnValues){

console.log("returnValues Array = "+returnValues);

var returnValuesLength = returnValues.length;   

for(var i=0;i<returnValuesLength;i++){     

  var a = returnValues[i];
  var c = returnValues[i];    
  var j;

  j = await App.getVersion(a);

  console.log("version ="+j);
  console.log("tradeId="+a);

  tradesInstance.trades(c,j).then(function(trade){

    var secId = trade[0];
    var notional = trade [1];
    var price = trade[2];
    var client = trade[3];

    var tradeTemplate = "<tr><td>" + secId + "</td><td>" + notional + "</td><td>" + price + "</td><td>" + client +"</td></tr>" 
    tradeResults.append(tradeTemplate);
  })
}

}).catch(function(err){
console.log(err);
})
}).catch(function(err){
console.warn(err);
})

}

};

My Smart Contract :-

pragma solidity 0.5.0;

contract Trades {
struct Trade {
string secId;
uint notional;
uint price;
string client;
uint version;
uint index;
uint tradeId;
}

mapping(uint =>mapping(uint => Trade)) public trades;

uint public tradeId;
uint[] tradeIndex;
uint[] tradeID;
uint[] public totalNum;

function updateTrade(uint _tradeId, string memory _secId,uint _notional,uint _price,string memory _client) public{

uint j;
j= (getLatestVersionOfTrade(_tradeId)) + 1;
trades[_tradeId][j].secId = _secId;
trades[_tradeId][j].notional = _notional;
trades[_tradeId][j].price = _price;
trades[_tradeId][j].client = _client;
trades[_tradeId][j].version = j;
trades[_tradeId][j].index = tradeIndex.push(tradeIndex[tradeIndex.length-1]+1);

}

function setTrade(string memory _secId,uint _notional,uint _price,string memory _client) public {

uint  version  = 0;
tradeId++;

trades[tradeId][version].secId = _secId;
trades[tradeId][version].notional = _notional;
trades[tradeId][version].price = _price;
trades[tradeId][version].client = _client;
trades[tradeId][version].version = version;
trades[tradeId][version].index = tradeIndex.push(tradeId);
tradeID.push(tradeId);

}

function getAllTradeData()view public returns(uint[] memory){
return tradeIndex;
}

function getAllTradeDataId()view public returns(uint[] memory){
return tradeID;
}

function getTradeById(uint _tradeId,uint version)view public returns(string memory, uint, uint, string memory, uint, uint){
return (trades[_tradeId][version].secId, trades[_tradeId][version].notional, trades[_tradeId][version].price,
trades[_tradeId][version].client,trades[_tradeId][version].version, trades[_tradeId][version].index);
}

function getLatestVersionOfTrade(uint _tradeId) view public returns (uint) {
uint max = 0;

for (uint i = 0; i < tradeIndex.length; i++) {
    uint ver = trades[_tradeId][i].version;
    if (ver > max) {
        max = ver;
    }
}

return max;
}

function getClientData(string memory _client) public returns (uint[] memory) {

if (totalNum.length > 0){
    delete totalNum;
}
    for(uint i=1; i <= tradeID.length;i++){
    uint j;
    j= (getLatestVersionOfTrade(i));
    if(uint(keccak256(abi.encodePacked(trades[i][j].client))) == uint(keccak256(abi.encodePacked(_client)))){
        totalNum.push(i);
    }             
}  
return totalNum;

}

function getTotalNumLength() public returns (uint){
return totalNum.length;
}
}

The error shown on brower console : -

returnValues Array = 3,4,5
app.js:113 version =undefined
app.js:114 tradeId=3
app.js:113 version =undefined
app.js:114 tradeId=4
app.js:113 version =undefined
app.js:114 tradeId=5

3inpage.js:1 Uncaught (in promise) Error: Invalid number of arguments to
Solidity function
at Object.InvalidNumberOfSolidityArgs (inpage.js:1)
at u.validateArgs (inpage.js:1)
at u.toPayload (inpage.js:1)
at u.call (inpage.js:1)
at u.execute (inpage.js:1)
at truffle-contract.js:136
at new Promise (<anonymous>)
at truffle-contract.js:127

app.js:77 test:0,a:0
app.js:82 test2=0
app.js:77 test:0,a:0
app.js:82 test2=0
app.js:77 test:1,a:1
app.js:82 test2=1

The variable ‘j’ in searchByClient is returning an undefined value when it is passed in ‘trades(c,j)’. But in the function getVersion the value returning seems to be fine. Please help me out as I have no other options left. Also I am extremly new to javascript, so please do tell me if I had make any mistakes. I was able to write this code with help of a tutorial.

#javascript #blockchain #solidity

What is GEEK

Buddha Community

Lyly Sara

Lyly Sara

1550050300

The javascript function is returning a promise and the promise is used in the solidity function which gives the error of invalid arguments

I am trying to make a Dapp which maintains the various versions of a trade(new versions are created when we update the data of trade). I am using javascript we3.js api to call my solidity functions through javascript. I have a function which displays the data when we search using a field called 'client'. When I am clicking the button to search on basis of client, it returns an error. I am using promises in javascript, but it seems to me that the javascript function is returning a promise which is undefined to solidity function. But after the error the javascript function is returning the expected values(I checked using console.log).

I have tried using async/await but that doesnt seems to do the trick.

My Javascript code:-

getVersion:async function(i){

var returnedLatestVersion;

App.contracts.Trades.deployed().then(async function(instance){

await instance.getLatestVersionOfTrade.call(i).then(function(a){      

  returnedLatestVersion = a;
  console.log("test:"+returnedLatestVersion+",a:"+a);

}).catch(function(err){
console.log(err)
})
console.log("test2="+returnedLatestVersion);
return await returnedLatestVersion;    

})
},

searchByClient: function(){

var tradesInstance;

var client = $(‘#clientSearch’).val();

var tradeResults = $(“#tradesResult”);
tradeResults.empty();

App.contracts.Trades.deployed().then(function(instance){
tradesInstance = instance;

return tradesInstance.getClientData.call(client).then(async function(returnValues){

console.log("returnValues Array = "+returnValues);

var returnValuesLength = returnValues.length;   

for(var i=0;i&lt;returnValuesLength;i++){     

  var a = returnValues[i];
  var c = returnValues[i];    
  var j;

  j = await App.getVersion(a);

  console.log("version ="+j);
  console.log("tradeId="+a);

  tradesInstance.trades(c,j).then(function(trade){

    var secId = trade[0];
    var notional = trade [1];
    var price = trade[2];
    var client = trade[3];

    var tradeTemplate = "&lt;tr&gt;&lt;td&gt;" + secId + "&lt;/td&gt;&lt;td&gt;" + notional + "&lt;/td&gt;&lt;td&gt;" + price + "&lt;/td&gt;&lt;td&gt;" + client +"&lt;/td&gt;&lt;/tr&gt;" 
    tradeResults.append(tradeTemplate);
  })
}

}).catch(function(err){
console.log(err);
})
}).catch(function(err){
console.warn(err);
})

}

};

My Smart Contract :-

pragma solidity 0.5.0;

contract Trades {
struct Trade {
string secId;
uint notional;
uint price;
string client;
uint version;
uint index;
uint tradeId;
}

mapping(uint =>mapping(uint => Trade)) public trades;

uint public tradeId;
uint[] tradeIndex;
uint[] tradeID;
uint[] public totalNum;

function updateTrade(uint _tradeId, string memory _secId,uint _notional,uint _price,string memory _client) public{

uint j;
j= (getLatestVersionOfTrade(_tradeId)) + 1;
trades[_tradeId][j].secId = _secId;
trades[_tradeId][j].notional = _notional;
trades[_tradeId][j].price = _price;
trades[_tradeId][j].client = _client;
trades[_tradeId][j].version = j;
trades[_tradeId][j].index = tradeIndex.push(tradeIndex[tradeIndex.length-1]+1);

}

function setTrade(string memory _secId,uint _notional,uint _price,string memory _client) public {

uint  version  = 0;
tradeId++;

trades[tradeId][version].secId = _secId;
trades[tradeId][version].notional = _notional;
trades[tradeId][version].price = _price;
trades[tradeId][version].client = _client;
trades[tradeId][version].version = version;
trades[tradeId][version].index = tradeIndex.push(tradeId);
tradeID.push(tradeId);

}

function getAllTradeData()view public returns(uint[] memory){
return tradeIndex;
}

function getAllTradeDataId()view public returns(uint[] memory){
return tradeID;
}

function getTradeById(uint _tradeId,uint version)view public returns(string memory, uint, uint, string memory, uint, uint){
return (trades[_tradeId][version].secId, trades[_tradeId][version].notional, trades[_tradeId][version].price,
trades[_tradeId][version].client,trades[_tradeId][version].version, trades[_tradeId][version].index);
}

function getLatestVersionOfTrade(uint _tradeId) view public returns (uint) {
uint max = 0;

for (uint i = 0; i &lt; tradeIndex.length; i++) {
    uint ver = trades[_tradeId][i].version;
    if (ver &gt; max) {
        max = ver;
    }
}

return max;
}

function getClientData(string memory _client) public returns (uint[] memory) {

if (totalNum.length &gt; 0){
    delete totalNum;
}
    for(uint i=1; i &lt;= tradeID.length;i++){
    uint j;
    j= (getLatestVersionOfTrade(i));
    if(uint(keccak256(abi.encodePacked(trades[i][j].client))) == uint(keccak256(abi.encodePacked(_client)))){
        totalNum.push(i);
    }             
}  
return totalNum;

}

function getTotalNumLength() public returns (uint){
return totalNum.length;
}
}

The error shown on brower console : -

returnValues Array = 3,4,5
app.js:113 version =undefined
app.js:114 tradeId=3
app.js:113 version =undefined
app.js:114 tradeId=4
app.js:113 version =undefined
app.js:114 tradeId=5

3inpage.js:1 Uncaught (in promise) Error: Invalid number of arguments to
Solidity function
at Object.InvalidNumberOfSolidityArgs (inpage.js:1)
at u.validateArgs (inpage.js:1)
at u.toPayload (inpage.js:1)
at u.call (inpage.js:1)
at u.execute (inpage.js:1)
at truffle-contract.js:136
at new Promise (<anonymous>)
at truffle-contract.js:127

app.js:77 test:0,a:0
app.js:82 test2=0
app.js:77 test:0,a:0
app.js:82 test2=0
app.js:77 test:1,a:1
app.js:82 test2=1

The variable ‘j’ in searchByClient is returning an undefined value when it is passed in ‘trades(c,j)’. But in the function getVersion the value returning seems to be fine. Please help me out as I have no other options left. Also I am extremly new to javascript, so please do tell me if I had make any mistakes. I was able to write this code with help of a tutorial.

#javascript #blockchain #solidity

Vincent Lab

Vincent Lab

1605017502

The Difference Between Regular Functions and Arrow Functions in JavaScript

Other then the syntactical differences. The main difference is the way the this keyword behaves? In an arrow function, the this keyword remains the same throughout the life-cycle of the function and is always bound to the value of this in the closest non-arrow parent function. Arrow functions can never be constructor functions so they can never be invoked with the new keyword. And they can never have duplicate named parameters like a regular function not using strict mode.

Here are a few code examples to show you some of the differences
this.name = "Bob";

const person = {
name: “Jon”,

<span style="color: #008000">// Regular function</span>
func1: <span style="color: #0000ff">function</span> () {
    console.log(<span style="color: #0000ff">this</span>);
},

<span style="color: #008000">// Arrow function</span>
func2: () =&gt; {
    console.log(<span style="color: #0000ff">this</span>);
}

}

person.func1(); // Call the Regular function
// Output: {name:“Jon”, func1:[Function: func1], func2:[Function: func2]}

person.func2(); // Call the Arrow function
// Output: {name:“Bob”}

The new keyword with an arrow function
const person = (name) => console.log("Your name is " + name);
const bob = new person("Bob");
// Uncaught TypeError: person is not a constructor

If you want to see a visual presentation on the differences, then you can see the video below:

#arrow functions #javascript #regular functions #arrow functions vs normal functions #difference between functions and arrow functions

Hugo JS

Hugo JS

1599295469

What is Callback-Function in JavaScript? How it is Replaced By Promises?

Let us understand term _Callback _by an real-world example: Suppose, you are calling to your Girlfriend (If you have) and she is busy in another call then she send message to you : “I am busy right now, Call back you later.!!”. After completing her work, she calls you back and this is what call back in JavaScript as well.

In JavaScript, When a function is executing (Girlfriend is talking with someone) then after function execution is completed another function is started for execution this is call back function.

Now you are thinking that its depend upon when, where you are calling function and all function call is “Call-back function”. Image for post

Here, _printWorld() _function is executed after _printHello() _complete its execution but this is not call-back function example because _printHello() _is not Asynchronous function. Suppose, _printHello() _prints after 1 Second then _printWorld() _executes first.

Image for post

What if we want “Hello World” output when Asynchronous function is there. We can pass function as argument and calls it after _printHello() _complete its execution. Here below code snippet of how _function pass as argument _:

Image for post

Callback function can be defined as a function passed by argument and executes when one function completes its execution.

Suppose, If you have API (Application Programming Interface) to get Students Roll numbers and select one of Roll number — getting that roll number’s data and print that data. We don’t have API to get students data so we are using _setTimeout() _Async function and getting roll number after 2s, We are also selecting one of roll number manually after 2s and print Roll number’s data after 2s. This can be done by call back function.

Image for post

The program became complex and complex if we have too many things to do like Getting Students data, Selecting one of them student, get student’s roll number and get result by roll number then it become very complex. If you have any Error in this then debugging is also tedious task, this things is called “Callback Hell”, which is shape like “Pyramid Of Doom”.

To overcome with this problem, Promises is introduced in JavaScript. Promises has three states : Pending, Resolved, Reject. Promises is created by Constructor : new Promise(). It has one executor function which has two arguments (resolve, reject).

Promise object has three methods: then(), catch() & finally().

Image for post

If Promise is successfully executed then its data is transferred through resolve function and if it has error then passed through reject function.

We have implemented same task which is done using call back function in Promises and its easily understandable However it is complicated compare to callback function but when you use promises for sometimes then it’s easy to implement.

In _getRollNumber(), _resolve method’s data is caught by then() functions arguments and reject method’s data is caught by catch() function. Here In Promises, Every task has different promises because of that it is easy to debug and readable compare to call back function. You can see that there is no shape like “Pyramid of Doom” in Promises. This is how Callback function is replaced by Promises.

Thank you for reading!

This article was originally published on Medium.com

#javascript-tips #advanced-javascript #javascript #callback-function #promises

Madyson  Reilly

Madyson Reilly

1601069940

Function Expression vs Function Declaration in JavaScript

Function Expression vs Function Declaration in JavaScript.

It was until during one of the JavaScript mock interviews did I came across the term function expression.

The question was: What is the difference between these two syntax?

function x(){

}

let x = function(){

}

I was clueless for a moment. After thinking a little, I could only come up with: the second syntax invokes an _anonymous _function and is assigned to a variable.

I was alien to the term hoisting.

In this article, we will acquaint ourselves with three simple terms: function declaration,_ function expression, _and hoisting.

What is function declaration?

Function declaration is also known as _function statement. _It contains the name of the function, parameters, and a return statement. **Naming the function **is what sets function declaration apart. Parameters and return statement is optional.

Image for post

Function Declaration

What is function expression?

Function expression also has a name, parameters, and return statement. All of which are optional. The important thing to bear in mind is: the function here is _assigned _to a JavaScript variable.

Image for post

Function Expression

#function-expression #function-declaration #functions-in-javascript #coding #javascript #express

Julie  Donnelly

Julie Donnelly

1602406920

JavaScript Promise: Methods Comparison

Introduction

Promises in JavaScript are used to handle asynchronous operations by keeping track of whether a certain event has happened. If that certain event has taken place, it determines what happens next. Promises return a value which is either a resolved value or a reason why it’s rejected. They can handle multiple asynchronous operations easily and they provide better error handling than callbacks and events.

Callback: A callback is a function that is passed into another function as an argument to be executed later.

Events: Events provide a dynamic interface to a WebPage and are connected to elements in the Document Object Model(DOM), for example: onclick(), onmouseover() etc.

A Promise has four states

Pending: Before the event has happened, the promise is in the pending state.

Settled: Once the event has happened it is then in the settled state.

Fulfilled: Action related to the promise has succeeded.

Rejected: Action related to the promise has failed.

#javascript #javascript-development #javascript-tutorial #promises #javascript-tips