contract.name() function is not working in ethers js - fork

I need help this is my code and it is not working right I am trying to call the function using ether js kindly help.
I have created WMATIC interface contract but it is not calling its functions
describe("checking deployment address", function () {
const token0Contract = new ethers.Contract(token0, IERC20.abi);
it("cheching now lol ", async () => {
console.log(dodoFlashloan.address);
let balance = await provider.getBalance(dodoFlashloan.address);
console.log("balance before", balance);
});

Related

Ethereum Solidity Contract - Mocha timeouts at web3.eth.Contract send() method

I am currently learning Solidity and trying to build a simple contract. I am also trying to use the Mocha framework to test the smart contract before deploying. The test code is per below:
const assert = require("assert");
const ganache = require("ganache-cli");
const Web3 = require("web3");
const { interface, bytecode } = require("../compile");
const provider = ganache.provider();
const web3 = new Web3(provider);
let accounts;
let inbox;
beforeEach(async () => {
// Get a list of all accounts
accounts = await web3.eth.getAccounts();
// Use one of those accounts to deploy the contract
inbox = await new web3.eth.Contract(JSON.parse(interface))
.deploy({
data: bytecode,
arguments: ["Hi there!"]
})
.send({
from: accounts[0],
gas: "1000000"
});
});
describe("Inbox", () => {
it("deploys a contract", () => {
console.log(inbox);
});
});
The test fails and timeouts:
> mocha
Inbox
1) "before each" hook for "deploys a contract"
0 passing (2s)
1 failing
1) "before each" hook for "deploys a contract":
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
I noticed that the test passes if I comment out the send() argument:
// .send({
// from: accounts[0],
// gas: "1000000"
// });
So the issue must be with using this method. Not sure if it is an async issue.
I solved this by downgrading web3 to 1.0.0-beta.37. Seems like version 1.0.0-beta.51 is buggy.

How do I instantiate a turnContext using the adapter and request as parameters

I would like to instantiate a turnContext to be used in integration testing. How would I be able to instantiate one without calling on the processActivity() method of the adapter?
I am looking at the documentation but it shows that I would need the request of the post call as the parameter. I would like my testing to be independant of the post call. I would then assume that I would need to instantiate the request? How would I go about doing so?
Image of documentation
This is a bit hard to answer without knowing how you are planning to use the code. That being said, it's not that hard to create a new turnContext and also bypass the processActivity(). Given how you are referencing turnContext and processActivity(), I'm assuming you are using the Node SDK. Implementing in C# wouldn't be too different.
Here are two options, both utilizing the creation of a new adapter, however you can also pass in an already established turnContext, if desired:
Use .createContext in server.post in the index.js file, or
Maintain the processActivity() method in the server.post. This calls a new "onTurn" method in the bot.js file. In doing so, this allows you to control when and how the new "onTurn" is accessed.
Option 1: In the index.js file, you will want to create a new adapter or make a copy of the first depending on your needs:
const adapter = new BotFrameworkAdapter({
appId: endpointConfig.appId || process.env.MicrosoftAppId,
appPassword: endpointConfig.appPassword || process.env.MicrosoftAppPassword
});
const newAdapter = adapter;
or
const adapter = new BotFrameworkAdapter({
appId: endpointConfig.appId || process.env.MicrosoftAppId,
appPassword: endpointConfig.appPassword || process.env.MicrosoftAppPassword
});
const newAdapter = new BotFrameworkAdapter({
appId: endpointConfig.appId || process.env.MicrosoftAppId,
appPassword: endpointConfig.appPassword || process.env.MicrosoftAppPassword
});
Include the onTurnError code to catch errors:
// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
console.error(`\n [onTurnError]: ${ error }`);
await context.sendActivity(`Oops. Something went wrong!`);
};
// Catch-all for errors.
newAdapter.onTurnError = async (context, error) => {
console.error(`\n [onTurnError]: ${ error }`);
await context.sendActivity(`Oops. Something went wrong!`);
};
Then, set the new adapters and create the new turnContext:
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (turnContext) => {
await bot.onTurn(turnContext);
});
newAdapter.createContext(req, res);
});
Options 2: In the index.js file, building off of the above code, set the adapters to await the individual "onTurn" methods:
// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (turnContext) => {
await bot.onTurn(turnContext);
});
newAdapter.processActivity(req, res, async (turnContext) => {
await bot.newOnTurn(turnContext);
});
});
In the bot.js file, you will have your two "onTurn" methods. In this example, the different "onTurn" methods are called based on whether a message is sent or I am deleting user data (I am sending this event via the Emulator => Conversation menu item). What you decide to match on is up to you.
async newOnTurn(turnContext) {
if (turnContext.activity.type === ActivityTypes.DeleteUserData) {
const dc = await this.dialogs.createContext(turnContext);
await dc.context.sendActivity(`Looks like you deleted some user data.`);
}
}
async onTurn(turnContext) {
if (turnContext.activity.type === ActivityTypes.Message) {
const dc = await this.dialogs.createContext(turnContext);
await dc.context.sendActivity(`Looks like you sent a message.`);
}
}
Hope of help!

Feathers custom service response works in console but getting empty array on API response

I have a custom service which fetches data from multiple mongoose models and creates an array using these data and gives back to API.
Everything works well.. I can console the new object-array 'result.rolePermissions'. you can see that in the code below.
My problem is when I check the data on the frontend side am getting a blank array as a response.
I have double checked if I missed a variable or used a different API call, but no. I am exactly calling this custom service function but for some reason, I can't get the data.
Is it because of the usage of await/Promise on the 'result.roles', 'result.permission'? Did I use some bad practices?
async find (params) {
let result = {};
result.roles = [];
result.rolePermissions = [];
result.permissionsModules = [];
const permissionGroupModel = this.app.service('permission-groups').Model;
const rolesModel = this.app.service('roles').Model;
const permissionsModel = this.app.service('permissions').Model;
//all permission-groups are getting fine
result.permissionsModules = await new Promise(function(resolve, reject) {
permissionGroupModel.find().populate('permissions').exec((err,response)=>{
resolve(response);
})
});
//all roles are getting fine
result.roles = await new Promise(function(resolve, reject) {
rolesModel.find().then(response=>{
resolve(response);
})
});
//all permissions are getting fine
result.permissions = await new Promise(function(resolve, reject) {
permissionsModel.find().then(response=>{
resolve(response);
})
});
//here is iam having trouble..
result.rolePermissions = await new Promise(function(resolve, reject) {
let rolePerms = [];
result.roles.forEach(role => {
rolePerms[role.name] = {};
result.permissions.forEach(permission => {
rolePerms[role.name][permission.name] = (role.permissions.indexOf(permission._id) > -1)?true:false;
});
});
resolve(rolePerms);
});
//I have consoled result.rolePermissions and it shows the currect data.but when this data getting as null array in api call response
console.log('result.rolePermissions')
console.log(result.rolePermissions)
return {
status:true,
test:data.rolePermissions,
data:result
}
}
There are a couple things that can be done to improve this code. First, anything of the form...
x = await new Promise(function(resolve, reject) {
promiseReturningFunction(params).then(response => {
resolve(response);
});
});
...can be rewritten as...
x = await promiseReturningFunction(params);
...because, when you have a promise-returning-function, there's no need to create another promise (with new Promise).
The code where you indicate trouble doesn't appear to need a promise at all...
//here is iam having trouble..
result.rolePermissions = [];
result.roles.forEach(role => {
rolePerms[role.name] = {};
result.permissions.forEach(permission => {
rolePerms[role.name][permission.name] (role.permissions.indexOf(permission._id) > -1)?true:false;
});
});
Finally, I'm puzzled by the use of data in this code...
return {
status:true,
test:data.rolePermissions,
data:result
}
Is it possible that, while your use of Promises was non-standard and confusing, that code was pretty much working, and the real problem comes from passing data.rolePermissions rather than the object you just built and tested with the log (result.rolePermissions)?
The issue was fixed when i restarted the feathers service. I am not deleting the question because the other answer may share some knowledge

Socket.io sends two messages

I'm trying to setup socket.io and here is part of my server.js
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http, { path: '/websocket', origins:'*:*' });
io.on('connection', (socket) => {
socket.send('Hi');
socket.on('message', (message) => {
console.log(message);
socket.emit('hello', `New: ${message}`);
});
console.log('a user connected');
});
http.listen(3030, function(){
console.log('listening on *:3030');
});
and my simple client:
var socket = io('https://*******.com', {
secure: true,
path: '/websocket'
});
const input = document.getElementById('text');
const button = document.getElementById('button');
const msg = document.getElementById('msg');
button.onclick = () => {
socket.emit('message', input.value);
socket.on('hello', (text) => {
const el = document.createElement('p');
el.innerHTML = text;
msg.appendChild(el);
})
}
And if I'll click for third time I receive a 3 messages back and so on. What I'm doing wrong? I wish to send message to the server and receive modified message back.
I'm new in web sockets.
Any help appreciated.
P.S. socket.io v2.0.1
You are adding a socket.on() event handler each time the button is clicked. So, after the button has been clicked twice, you have duplicate socket.on() event handlers. When the event comes back, your two event handlers will each get called and you will think you are getting duplicate messages. Actually, it's just one message, but with duplicate event handlers.
You pretty much never want to add an event handler inside another event handler because that leads to this sort of build-up of duplicate event handlers. You don't describe (in words) exactly what you're code is trying to do so I don't know exactly what alternative to suggest. Usually, you set up the event handlers first, just once, when the socket is connected and then you will never get duplicate handlers.
So, perhaps it's as simple as changing this:
button.onclick = () => {
socket.emit('message', input.value);
socket.on('hello', (text) => {
const el = document.createElement('p');
el.innerHTML = text;
msg.appendChild(el);
})
}
to this:
button.onclick = () => {
socket.emit('message', input.value);
}
socket.on('hello', (text) => {
const el = document.createElement('p');
el.innerHTML = text;
msg.appendChild(el);
});
If you are using Angular and (probably) embedding the Socket in a Service (simpleton) you are creating a persistent listener in ngOnInit every time you load a page.
You need to create some kind of flag to know if the listener was already created in the Service from another instance of your page.

Socket.io as server, 'standard' javascript as client?

So i've built a simple websocket client implementation using Haxe NME (HTML5 target ofc).
It connects to
ws://echo.websocket.org (sorry no link, SO sees this as an invalid domain)
which works perfectly!
(i'm using xirsys_stdjs haxelib to use the HTML5 websocket stuff.)
I want to have a local (on my own machine) running websocket server.
I'm using Socket.io at the moment, because i cannot find an easier / simpler solution to go with.
I'm currently trying to use socket.io as socket server, but a 'standard' javascript socket implementation as client (Haxe HTML5), without using the socket.io library clientside.
Does anyone know if this should be possible? because i cannot get it working.
Here's my socket.io code:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(1337);
function handler (req, res) {
fs.readFile(__dirname + '/client.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
// WEBSOCKET IMPLEMENTATION
io.sockets.on('connection', function (socket) {
console.log("webSocket connected...");
socket.on('message', function () {
console.log("server recieved something");
// TODO: find out how to access data recieved.
// probably 'msg' parameter, omitted in example?
});
socket.on('disconnect', function () {
console.log("webSocket disconnected.");
});
});
And here's my Haxe (client) code:
static var webSocketEndPoint:String = "ws://echo.websocket.org";
//static var webSocketEndPoint:String = "ws://localhost:1337";
...
private function initializeWebSocket ():Void {
if (untyped __js__('"MozWebSocket" in window') ) {
websocket = new MozWebSocket(webSocketEndPoint);
trace("websocket endpoint: " + webSocketEndPoint);
} else {
websocket = new WebSocket(webSocketEndPoint);
}
// add websocket JS events
websocket.onopen = function (event:Dynamic):Void {
jeash.Lib.trace("websocket opened...");
websocket.send("hello HaXe WebSocket!");
}
websocket.onerror = function (event:Dynamic):Void {
jeash.Lib.trace("websocket erred... " + event.data);
}
websocket.onmessage = function (event:Dynamic):Void {
jeash.Lib.trace("recieved message: " + event.data);
switchDataRecieved(event.data);
}
websocket.onclose = function (event:Dynamic):Void {
jeash.Lib.trace("websocket closed.");
}
}
In case the Haxe code is unclear: it's using 2 extern classes for the webSocket implementation: MozWebSocket and WebSocket. These are just typed 'interfaces' for the corresponding JavaScript classes.
websocket.io! from the same guys. sample shows exact same thing that you are asking about... and something that I spent past 20 hours searching for (and finally found!)
https://github.com/LearnBoost/websocket.io
Update: Jan 2014
The websocket.io repository has not seen any activity for about 2 years. It could be because it is stable, or it could be because it is abandoned.
The same people have another repository called engine.io. In the readme they say that this is isomorphic with websocket.io... It seems that engine.io is where all the action is these days.
https://github.com/LearnBoost/engine.io
While searching for the same thing I just found https://github.com/einaros/ws/ and its server example worked for me with my pre-existing plain javascript client.
http://socket.io/#how-to-use
At the mentioned link, down towards the bottom of the page,
the socket.io documentation demonstrates as it's last
example, how to use their module as a plain
old xbrowser webSocket server.
SERVER
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket)
{
socket.on('message', function () { });
socket.on('disconnect', function () { });
});
BROWSER
<script>
var socket= io.connect('http://localhost/');
socket.on('connect', function ()
{
socket.send('hi');
socket.on('message', function (msg)
{ // my msg
});
});
</script>
Hope that's what your looking for
--Doc

Resources