Getting invalid address Web3 when creating a new task - javascript

I’m developing a basic TodoList based on a tutorial of DAppUviersity on Youtube using Ethereum Blockchain, Solidity, and truffle , and I found this error when excepting the creatTask function, I tried every solution without any result, Any help, please
app.js Code:
App = {
web3Provider: null,
contracts: {},
init: async function () {
await App.initWeb3();
},
initWeb3: async function () {
if (typeof web3 !== "undefined") {
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
App.web3Provider = new Web3.providers.HttpProvider(
"http://localhost:7545"
);
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: async function () {
$.getJSON("TodoList.json", function (TodoList) {
const todoList = TodoList;
App.contracts.TodoList = TruffleContract(TodoList);
App.contracts.TodoList.setProvider(App.web3Provider);
return App.render();
});
},
render: async function () {
if (App.loading) {
return;
}
App.setLoading(true);
App.account = web3.eth.accounts[0];
$("#account").html("Your Account: " + App.account);
const todoList = await $.getJSON("TodoList.json");
App.contracts.TodoList = TruffleContract(todoList);
App.contracts.TodoList.setProvider(App.web3Provider);
App.todoList = await App.contracts.TodoList.deployed();
App.setLoading(false);
return App.renderTask();
},
renderTask: async () => {
const taskCount = await App.todoList.taskCount();
const $taskTemplate = $(".taskTemplate");
const submitButton = $("#submitButton");
for (var i = 1; i <= taskCount; i++) {
const task = await App.todoList.tasks(i);
const taskId = task[0].toNumber();
const taskContent = task[1];
const taskCompleted = task[2];
const $newTaskTemplate = $taskTemplate.clone();
$newTaskTemplate.find(".content").html(taskContent);
$newTaskTemplate
.find("input")
.prop("name", taskId)
.prop("checked", taskCompleted)
.on("click", App.toggleCompleted);
if (taskCompleted) {
$("#completedTaskList").append($newTaskTemplate);
} else {
$("#taskList").append($newTaskTemplate);
}
$newTaskTemplate.show();
submitButton.show();
}
},
createTask: async () => {
try {
App.setLoading(true);
const task = $("#newTask").val();
console.log(task);
await App.todoList.addTask(task);
window.location.reload();
} catch (error) {
console.log(error);
}
},
setLoading: function (boolean) {
App.loading = boolean;
const loader = $("#loader");
const content = $("#content");
if (boolean) {
loader.show();
content.hide();
} else {
loader.hide();
content.show();
}
},
};
$(function () {
$(window).load(function () {
App.init();
});
});
Solidity Code:
pragma solidity 0.5.16;
contract TodoList {
uint256 public taskCount = 0;
struct Task {
uint256 id;
string description;
bool complete;
}
event TaskCreated(uint256 id, string content, bool completed);
mapping(uint256 => Task) public tasks;
constructor() public {
addTask("Morning Coffee");
}
function addTask(string memory _description) public {
taskCount++;
tasks[taskCount] = Task(taskCount, _description, false);
emit TaskCreated(taskCount, _description, false);
}
}
Hello Everyone,
I’m developing a basic TodoList based on a tutorial of DAppUviersity on Youtube using Ethereum Blockchain, Solidity, and
truffle , and I found this error when excepting the creatTask
function, I tried every solution Hello Everyone,
I’m developing a basic TodoList based on a tutorial of DAppUviersity on Youtube using Ethereum Blockchain, Solidity, and
truffle , and I found this error when excepting the creatTask
function, I tried every solution

Related

How to initialize App Data in node js and access it without being undefined in jest test?

i am initializing a node js app with crucial data for the app to work from a database in index.js.
index.ts
import {getInitialData} from 'initData.ts';
export let APP_DATA: AppData;
export const initializeAppData = async () => {
try {
APP_DATA = (await getInitialData()) as AppData;
if (process.env.NODE_ENV !== 'test') {
initializeMongoose();
startServer();
}
} catch (error) {
console.log(error);
}
};
initData.ts
let dbName: string = 'initialData';
if (process.env.NODE_ENV === 'test') {
dbName = 'testDb';
}
const uri = `${process.env.MONGODB_URI}/?maxPoolSize=20&w=majority`;
export async function getInitialData() {
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db(dbName);
const configCursor = database
.collection('config')
.find({}, { projection: { _id: 0 } });
const config = await configCursor.toArray();
const aaoCursor = database
.collection('aao')
.find({}, { projection: { _id: 0 } });
const aao = await aaoCursor.toArray();
return { config, aao };
} catch {
(err: Error) => console.log(err);
} finally {
await client.close();
}
}
I'm using this array in another file and import it there.
missionCreateHandler
import { APP_DATA } from '../index';
export const addMissionResources = (
alarmKeyword: AlarmKeyword,
newMission: MissionDocument
) => {
const alarmKeywordObject = APP_DATA?.aao.find(
(el) => Object.keys(el)[0] === alarmKeyword
);
const resourceCommand = Object.values(alarmKeywordObject!);
resourceCommand.forEach((el) => {
Object.entries(el).forEach(([key, value]) => {
for (let ii = 1; ii <= value; ii++) {
newMission.resources?.push({
initialType: key,
status: 'unarranged',
});
}
});
});
};
I'm setting up a mongodb-memory-server in globalSetup.ts for Jest and copy the relevant data to the database from json-files.
globalSetup.ts
export = async function globalSetup() {
const instance = await MongoMemoryServer.create({
instance: { dbName: 'testDb' },
});
const uri = instance.getUri();
(global as any).__MONGOINSTANCE = instance;
process.env.MONGODB_URI = uri.slice(0, uri.lastIndexOf('/'));
process.env.JWT_SECRET = 'testSECRET';
const client = new MongoClient(
`${process.env.MONGODB_URI}/?maxPoolSize=20&w=majority`
);
try {
await client.connect();
const database = client.db('testDb');
database.createCollection('aao');
//#ts-ignore
await database.collection('aao').insertMany(aao['default']);
} catch (error) {
console.log(error);
} finally {
await client.close();
}
};
missionCreateHandler.test.ts
test('it adds the correct mission resources to the array', async () => {
const newMission = await Mission.create({
address: {
street: 'test',
houseNr: 23,
},
alarmKeyword: 'R1',
});
const expected = {
initialType: 'rtw',
status: 'unarranged',
};
addMissionResources('R1', newMission);
expect(newMission.resources[0].initialType).toEqual(expected.initialType);
expect(newMission.resources[0].status).toEqual(expected.status);
});
When runing the test, i get an 'TypeError: Cannot convert undefined or null to object at Function.values ()'. So it seems that the APP_DATA object is not set. I checked that the mongodb-memory-server is set up correctly and feed with the needed data.
When i hardcode the content of APP_DATA in index.ts, the test runs without problems.
So my questions are: How is the best practice to set up initial data in a node js app and where to store it (global object, simple variable and import it in the files where needed)? How can the test successfully run, or is my code just untestable?
Thank you!

Invalid state Error on websockets when sending message

I'm working on app which send message via websockets (managed by django channels) and in return it receives json from django db as a message and renders frontend based on that json.
I have Invalid State Error when I try to send message by websocket, why? Messages send are usually Json. I works properly all the time but commented part doesn't and I don't know why please explain me.
function main() {
configGame();
}
function configGame() {
const socket = "ws://" + window.location.host + window.location.pathname;
const websocket = new WebSocket(socket);
const playerName = document.querySelector(".playerName_header").textContent;
function asignEvents() {
const ready_btn = document.querySelector(".--ready_btn");
const start_btn = document.querySelector(".--start_btn");
ready_btn.addEventListener("click", () => {
let mess = JSON.stringify({
player: playerName,
action: "ready",
});
sendMess(mess);
});
start_btn.addEventListener("click", () => {
let mess = JSON.stringify({
player: playerName,
action: "start",
});
sendMess(mess);
});
}
function openWebsocket() {
console.log("Establishing Websocket Connection...");
websocket.onopen = () => {
console.log("Websocket Connection Established!");
};
}
function setWebsocket() {
websocket.onmessage = (mess) => {
console.log(`Message: ${mess.data}`);
dataJson = JSON.parse(mess.data);
dataJson = JSON.parse(dataJson.message);
//Player Ready (jeszcze z max_players zrobic kontrolke)
if (dataJson.action === "player_ready") {
const playersReadyText = document.querySelector(".players_ready_text");
playersReadyText.textContent = `Players ready: ${dataJson.players_ready}`;
}
};
websocket.onclose = () => {
console.log("Websocket Connection Terminated!");
};
}
/*
function checkState() {
let mess = JSON.stringify({
player: playerName,
action: "game state",
});
sendMess(mess);
}
*/
function sendMess(messText) {
websocket.send(messText);
}
openWebsocket();
checkState(); //This one doesn't work
asignEvents();
setWebsocket();
}
// Asigning Event Listneres to DOM ELEMENTS
function asignEvents() {
const ready_btn = document.querySelector(".--ready_btn");
const start_btn = document.querySelector(".--start_btn");
ready_btn.addEventListener("click", () => {
console.log("Ready");
});
start_btn.addEventListener("click", () => {
console.log("Start");
});
}
main();
Error:
Console (Safari) returns InvalidState error and points to
method checkState and sendMess.
InvalidStateError: The object is in an invalid state.
Is the websocket connected?
sendMess(messText) {
if (websocket.readyState === WebSocket.OPEN) {
websocket.send(messText);
} else {
console.warn("websocket is not connected");
}
}

Handle multiple calls to async function

I have a imported component, she calls a function every time that user do something (lets say press on button), in the function i must to fetch some data in async order, i would like to run the function calls as async way, the calls to the function will wait until the function is finished and then call the function again.
code example- if i trigger the function 3 times fast:
hadlechange = async(type:string) => {
console.log(1111111)
let storage = await getData("G");
console.log(22222222)
await bla1();
await bla2();
console.log(333333)
await storeData('blabla');
console.log(4444444)
};
render() {
return (
<BlaBla onChange ={this.hadlechange}>)
}
Expected results
11111
22222
3333
4444
1111
2222
3333
4444
1111
2222
3333
4444
What i get
1111
1111
2222
2222
1111
3333
2222
4444
3333
3333
4444
4444
I use JavaScript- React for the client
Thanks to #Proximo i thought about this solution and it's works fine.
Maybe someone else will find it helpful so i share my code :)
constructor() {
this.notHandling = true;
this.saves = [];
}
onChange = async (status: string) => {
this.saves.push(status);
if (this.notHandling) {
this.notHandling = false;
while (saves.length > 0) {
await blabla1(saves.pop());
...
}
this.notHandling = true;
}
};
render() {
return (
<BlaBla onChange ={this.hadlechange}>)
}
Edit
As a help function
export const handleMultiAsyncCalls = func => {
let notHandling = true;
let saves = [];
return async function() {
const args = arguments;
const context = this;
saves.push(args);
if (notHandling) {
notHandling = false;
while (saves.length > 0) {
await func.apply(context, saves.pop());
}
notHandling = true;
}
};
};
In your class you call it this way-
constructor(props) {
super(props);
this.handleMultiCalls = handleMultiAsyncCalls(blablaFunc);
handleChange = (data: string) => {
this.handleMultiCalls(data);
};
What's happening is that multiple changes are happening at once. An easy fix is to set a global flag to prevent the event method while the current action is in-progress.
constructor() {
this.notHandling = true;
}
hadlechange = async(type:string) => {
if (this.notHandling) {
this.notHandling = false;
console.log(1111111)
let storage = await getData("G");
console.log(22222222)
await bla1();
await bla2();
console.log(333333)
await storeData('blabla');
console.log(4444444)
this.notHandling = true;
}
};
Edit: Helper class example
class AsyncQueue {
private queue: Function[];
private processing: boolean;
constructor() {
this.queue = [];
this.processing = false;
}
push = (method:any) => {
this.queue.push(method);
this.process();
}
private process = async () => {
if (!this.processing) {
this.processing = true;
for (let action of this.queue) {
await action();
}
this.processing = false;
}
}
}
export const asyncQueue = new AsyncQueue;
Using Helper
// import example...
import { asyncQueue } from '~/common/helpers';
// Async test method
const tester = (message: string, seconds: number = 1) => {
return new Promise((resolve) => {
console.log('start ' + message);
setTimeout(() => {
console.log(message);
resolve(message);
}, seconds * 1000);
});
};
// Method calls
asyncQueue.push(() => tester('FIRST'));
setTimeout(() => asyncQueue.push(() => tester('SECOND', 2)), 50);
asyncQueue.push(() => tester('THIRD', 4));

How to test promises chain using jest?

I have module executer that will be executed on every api request now i am trying to write cases to unit test that executer. I have promise that returns chain that is being executed based on response. I see issue executing promise in test case , any help here to proper test this use case will be apprecaited.
main.ts
export class Executor {
private passedParam: ILogParams = {} as ILogParams;
constructor(public identity: Identity) {
this._ajv = new Ajv();
}
public execute(moduleName: string): (param1, param2) => any {
const self = this;
// getting rid of the tslint issue with Function
return function(params: any, responseCallback: (param: any , param2: any) => any) {
let _mod;
let _httpRequest;
let _params;
Promise.resolve(getApiModule(self.identity, moduleName))
.then((mod: ModuleBase<any, any>) => {
_mod = mod;
mod.ExecStage = ExecStage.Init;
return mod.init(getHttpModule(self.identity), params);
})
.then((httpRequest: HttpRequestBase) => {
_httpRequest = httpRequest;
if (_mod.Response().Summary.Header) {
throw _mod.Response().Summary;
}
return httpRequest;
})
.then(() => {
// empty the error stack
_mod.objErrorHandler.RemoveAllError();
_mod.ExecStage = ExecStage.Before;
return _mod.before(params);
})
.then((params1: any) => {
const _validators = _mod.getValidators();
let _failed: boolean = false;
return params1;
})
.then((params2: any) => {
_params = params2;
_mod.ExecStage = ExecStage.Core;
return _mod.core(_params, _httpRequest);
})
.catch((data: any) => {
const error: IHeader = {} as IHeader;
})
.then((data: any) => {
responseCallback(data, moduleName.substr(moduleName.indexOf('/') + 1));
});
};
}
}
main.spec.ts
import * as sinon from "sinon";
import {ModuleExecutor} from "./main.ts";
import {ExecStage, Identity} from "../../src/ts/common/Enums";
import ValidateRequestSchema from "../../src/ts/validation/requestSchema.js";
describe("ModuleExecuter", () => {
const sandbox = sinon.createSandbox();
afterEach(function afterTests() {
sandbox.restore();
});
let executer;
let executerSpy;
let results;
let stubbedExecutor;
let apiModule;
let _this;
const stubbedExecutorReturnFuction = sandbox.spy(function(args) {
executer = new ModuleExecutor(Identity.node);
executerSpy = executer.execute();
_this = this;
return new Promise(function(resolve) {
// moduleExecutor.execute(params, callback function)
executerSpy(args, function(data) {
resolve(data.Details);
});
});
});
const stubbedExecutorReturn = sandbox.spy(function(args, innerFunc) {
return innerFunc({Details: successResponse});
});
beforeEach(function() {
stubbedExecutor = sandbox.stub(ModuleExecutor.prototype, "execute").callsFake(function() {
return stubbedExecutorReturn;
});
apiModule = new GetAccountBalance();
const execute = sandbox.spy(stubbedExecutorReturnFuction);
results = execute("Payments/accountBalance/GetAccountBalance", {test:"test"});
});
describe("ModuleExecutor", function() {
it('should call ModuleExecutor.execute', function () {
sinon.assert.calledOnce(stubbedExecutor);
});
it('should return a promise', function() {
results.then(function(data) {
expect(data).toBe(successResponse);
});
});
it('should check validate AJV schema', function() {
let _mod;
results.then((mod: ModuleBase<any, any>) => {
_mod = mod;
mod.ExecStage = ExecStage.Before;
const requestSchema = "I" + _mod.__proto__.constructor.name + "Param";
const classSchema = ValidateRequestSchema[requestSchema];
const valid = _this._ajv.validate(classSchema, {test:"test"});
console.log("BOOLEAN>>>>>>>", valid);
expect(valid).toBeTruthy();
});
});
});
});

How can I call provider method from global service method in ionic 2, angular

I am trying to insert data from an API call to the database. The API call is done from the global services. When I tried to do it within the constructor method it is working. But if I try it from an other outside method from service I am getting an error “ERROR TypeError: Cannot read property 'setMetadataKey' of undefined(…)”.
import { Database } from './../providers/database/database';
import {Injectable} from '#angular/core';
#Injectable()
export class mAppService{
showValue: string;
public database;
userLoggedIn: boolean = false;
constructor(database: Database) {
//If i call the database method from here its working**
}
getConnect(ipaddress,portnumber){
try {
var t = ipaddress;
var p = portnumber;
client = new linear.client({transports: [
{type: 'websocket',
host: t, port: p}
]});
client.connect();
client.transport.onopen=this.onopen;
client.transport.onclose=this.onclose;
client.onconnect = client.ondisconnect = this.getStatus;
client.onnotify = this.recvNotify;
let stream$ = new Observable(observer => {
let interval = setInterval(() =>{
observer.next(client.transport.state);
/*observer.error(client.transport.onclose);
observer.complete();*/
},1000);
return() =>{
clearInterval(interval);
}
}).share();
return stream$;
} catch (error) {
console.log("catch.."+error);
}
}
recvNotify(m) {
var method = m.name;
var value = m.data;
var buttonType = "EFT_PAN";
this.database.setMetadataKey(value,buttonType).then((result) => {
console.log("Successfully saved the setMetadataKey.")
}, (error) => {
alert("ERROR: "+ error);
});
}
}
Can anyone help me to solve this please

Categories