web3 getAccounts doesn't get resolved - ethereum

web3.eth.getAccounts() is not working for me. The code below shows "error" on execution (gets rejected). I am using web3 1.0.0 beta-46. I am learning from Stephen Grider's tutorial videos and he used beta-26, is it version related issue or am i doing something wrong?
const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());
web3.eth.getAccounts()
.then(fetchedAccounts => {
console.log(fetchedAccounts);
},() => {
console.log("error");
});

Haven't tried it myself but this seems to be a bug with the latest versions of web3. Try with 1.0.0 beta-37.

Related

Google Functions v2 and NestJs

I'm looking into spinning up an api with nest using google cloud functions v2, looks like some people is doing it using nx: https://itnext.io/a-perfect-match-nestjs-cloud-functions-2nd-gen-nx-workspace-f13fb044e9a4, can this be done using nx?
I'm looking into a more vanilla example just using functions-framework and nest. Can somebody point me to any repo or example?
Thanks!
Nx is just tooling. It should be the same as you implement without NX. Can you try it in a normal Nestjs project?
// main.ts
const server = express()
import { http } from '#google-cloud/functions-framework'
export const createNestServer = async (expressInstance) => {
const app = await NestFactory.create(AppModule, new ExpressAdapter(expressInstance))
const globalPrefix = 'api'
app.setGlobalPrefix(globalPrefix)
app.enableCors()
return app.init()
}
createNestServer(server)
.then((v) => {
if (environment.production) {
Logger.log('🚀 Starting production server...')
} else {
Logger.log(`🚀 Starting development server on http://localhost:${process.env.PORT || 3333}`)
v.listen(process.env.PORT || 3333)
}
})
.catch((err) => Logger.error('Nest broken', err))
http('apiNEST', server)

browser.executeScript("return arguments[0].shadowRoot") not working with chromedriver 96 and higher

I extensively use this method to locate element inside shadowRoot using Protractor framework.
But after the chromedriver was updated to 96, it has stopped working.
Does anyone knows how to do work around for this in protractor framework
This solution worked for me with Chrome 97:
async function getShadowElement(shadowDomContainer: ElementFinder): Promise<any> {
const shadowRootObject = await browser.executeScript<any>('return arguments[0].shadowRoot', shadowDomContainer);
const rootKey = Object.keys(shadowRootObject)[0];
const rootId = shadowRootObject[rootKey];
return new WebElement(browser, rootId);
}
could thinks working using queryselector:
async expandUsingQuerySelector(sRoot,sElement){
var script="document.querySelector('"+sRoot+"').shadowRoot.querySelector('"+sElement+"')";
try{
return await browser.executeScript("return "+script );
} catch( error ) {
throw error;
}
}

How to connect ethers.js library with Rinkeby programmatically?

According to official docs of ethers.js, this should be the way how to connect to a specific network like Rinkeby-testnet with custom data:
const provider = ethers.getDefaultProvider(network, {
etherscan: ETHERSCAN_API_KEY,
infura: INFURA_API_KEY,
Also, this would be the way to get a signer in order to sign transactions:
const signer = provider.getSigner()
However, there is now method "getSigner" available on the default provider.
TypeError: provider.getSigner is not a function
How to achieve that using ethers.js?
getSigner() for InfuraProvider doesn't work, use this:
const infuraProvider = new ethers.providers.InfuraProvider(network, API_KEY);
const wallet = new ethers.Wallet(privateKey, infuraProvider);
const signer = wallet.connect(infuraProvider);
contract = new ethers.Contract(smartContractAddress, abi, signer);
ethers.getDefaultProvider seems to be somehow broken or outdated. Instead,
you should connect directly to a specific Provider, like this for Alchemy:
const provider = new ethers.providers.AlchemyProvider("rinkeby", apiKey)
or for Infura:
const provider = new ethers.providers.InfuraProvider("rinkeby", apiKey)
After this, it is easy to get a signer:
const signer = provider.getSigner()
or
const walletSigner = wallet.connect(provider);
You can read more about this here.
This works for me:
const provider = new ethers.providers.JsonRpcProvider(url)
const signer = provider.getSigner()
Got to know about this from the Alchemy docs
ethers.js doc

DialogflowSDK middleware return after resolving a promise

I'm currently playing around with the actions-on-google node sdk and I'm struggling to work out how to wait for a promise to resolve in my middleware before it then executes my intent. I've tried using async/await and returning a promise from my middleware function but neither method appears to work. I know typically you wouldn't override the intent like i'm doing here but this is to test what's going on.
const {dialogflow} = require('actions-on-google');
const functions = require('firebase-functions');
const app = dialogflow({debug: true});
function promiseTest() {
return new Promise((resolve,reject) => {
setTimeout(() => {
resolve('Resolved');
}, 2000)
})
}
app.middleware(async (conv) => {
let r = await promiseTest();
conv.intent = r
})
app.fallback(conv => {
const intent = conv.intent;
conv.ask("hello, you're intent was " + intent );
});
It looks like I should at least be able to return a promise https://actions-on-google.github.io/actions-on-google-nodejs/interfaces/dialogflow.dialogflowmiddleware.html
but I'm not familiar with typescript so I'm not sure if I'm reading these docs correctly.
anyone able to advise how to do this correctly? For instance a real life sample might be I need to make a DB call and wait for that to return in my middleware before proceeding to the next step.
My function is using the NodeJS V8 beta in google cloud functions.
The output of this code is whatever the actual intent was e.g the default welcome intent, rather than "resolved" but there are no errors. So the middleware fires, but then moves onto the fallback intent before the promise resolves. e.g before setting conv.intent = r
Async stuff is really fiddly with the V2 API. And for me only properly worked with NodeJS 8. The reason is that from V2 onwards, unless you return the promise, the action returns empty as it has finished before the rest of the function is evaluated. There is a lot to work through to figure it out, here's some sample boilerplate I have that should get you going:
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {BasicCard, MediaObject, Card, Suggestion, Image, Button} = require('actions-on-google');
var http_request = require('request-promise-native');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function handleMyIntent(agent) {
let conv = agent.conv();
let key = request.body.queryResult.parameters['MyParam'];
var myAgent = agent;
return new Promise((resolve, reject) => {
http_request('http://someurl.com').then(async function(apiData) {
if (key === 'Hey') {
conv.close('Howdy');
} else {
conv.close('Bye');
}
myAgent.add(conv);
return resolve();
}).catch(function(err) {
conv.close(' \nUh, oh. There was an error, please try again later');
myAgent.add(conv);
return resolve();
})})
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('myCustomIntent', handleMyIntent);
agent.handleRequest(intentMap);
});
A brief overview of what you need:
you have to return the promise resolution.
you have to use the 'request-promise-native' package for HTTP requests
you have to upgrade your plan to allow for outbound HTTP requests (https://firebase.google.com/pricing/)
So it turns out my issue was to do with an outdated version of the actions-on-google sdk. The dialogflow firebase example was using v2.0.0, changing this to 2.2.0 in the package.json resolved the issue

Using Artoo.js with Google Puppeteer for Web Scraping

I can't seem to be able to use Artoo.js with Puppeteer.
I tried using it through npm install artoo-js, but it did not work.
I also tried injecting the build path distribution using the Puppeteer command page.injectFile(filePath), but I had no luck.
Was anyone able to implement these two libraries successfully?
If so, I would love a code snippet of how Artoo.js was injected.
I just tried Puppeteer for another answer, I figured I could try Artoo too, so here you go :)
(Step 0 : Install Yarn if you don't have it)
yarn init
yarn add puppeteer
# Download latest artoo script, not as a yarn dependency here because it won't be by the Node JS runtime
wget https://medialab.github.io/artoo/public/dist/artoo-latest.min.js
Save this in index.js:
const puppeteer = require('puppeteer');
(async() => {
const url = 'https://news.ycombinator.com/';
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Go to URL and wait for page to load
await page.goto(url, {waitUntil: 'networkidle'});
// Inject Artoo into page's JS context
await page.injectFile('artoo-latest.min.js');
// Sleeping 2s to let Artoo initialize (I don't have a more elegant solution right now)
await new Promise(res => setTimeout(res, 2000))
// Use Artoo from page's JS context
const result = await page.evaluate(() => {
return artoo.scrape('td.title:nth-child(3)', {
title: {sel: 'a'},
url: {sel: 'a', attr: 'href'}
});
});
console.log(`Result has ${result.length} items, first one is:`, result[0]);
browser.close();
})();
Result:
$ node index.js
Result has 30 items, first one is: { title: 'Headless mode in Firefoxdeveloper.mozilla.org',
url: 'https://developer.mozilla.org/en-US/Firefox/Headless_mode' }
This is too funny to miss: right now the top article of HackerNews is about Firefox Headless...