I have an issue with Firebase cloud function. The connexion to infura fails when my function is called. I have upgraded to Blaze plan as mention here, but it didn't change.
Here is my code:
const Web3 = require('web3')
exports.getInstructorOnBlock = functions.database.ref('/services/{serviceId}').onUpdate((snapshot, context) => {
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/MyKey"));
}
var abi = [{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"instructorAccts","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"fName","type":"string"},{"indexed":false,"name":"lName","type":"string"},{"indexed":false,"name":"age","type":"uint256"}],"name":"instructorInfo","type":"event"},{"constant":false,"inputs":[{"name":"_address","type":"address"},{"name":"_age","type":"uint256"},{"name":"_fName","type":"string"},{"name":"_lName","type":"string"}],"name":"setInstructor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getInstructors","outputs":[{"name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_address","type":"address"}],"name":"getInstructor","outputs":[{"name":"","type":"uint256"},{"name":"","type":"string"},{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"countInstructors","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}];
var address = "address of the contract";
var MyContract = web3.eth.contract(abi);
var SmartContract = MyContract.at(address);
web3.eth.defaultAccount = web3.eth.accounts[0];
SmartContract.getInstructor(web3.eth.defaultAccount,"address", (err, res) => {
console.log("+++ res +++ " + res);
if (err) {
console.log("getInstructor fail" + err);
}
});
return 0
});
I've also tried to reinstall npm package. This is my package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"ansicolor": "^1.1.72",
"axios": "^0.18.0",
"dotenv": "^6.0.0",
"eth": "^4.0.1",
"ethereumjs-tx": "^1.3.6",
"ethereumjs-util": "^5.2.0",
"express": "^4.16.3",
"firebase-admin": "^5.12.1",
"firebase-functions": "^1.0.4",
"npm": "^6.1.0",
"ololog": "^1.1.103",
"personal": "^1.0.1",
"web3": "github:ethereum/web3.js"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.8.0"
},
"private": true
}
and the error returned by firebase:
Error: CONNECTION ERROR: Couldn't connect to node https://rinkeby.infura.io/key.
at Object.InvalidConnection (/user_code/node_modules/web3/lib/web3/errors.js:31:16)
at HttpProvider.send (/user_code/node_modules/web3/lib/web3/httpprovider.js:93:18)
at RequestManager.send (/user_code/node_modules/web3/lib/web3/requestmanager.js:58:32)
at Eth.get [as accounts] (/user_code/node_modules/web3/lib/web3/property.js:107:62)
at exports.getInstructorOnBlock.functions.database.ref.onUpdate (/user_code/index.js:112:39)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36
Does anyone have an idea of my problem?
Note that I can access to my smart contract "getInstructor" function through the same infura/rinkeby on a html page
Thanks
Related
While trying to redeploy a function I now get this error message: Error parsing triggers: Cannot find module 'core-js / fn / reflect'.
Here's my package.json:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "14"
},
"main": "index.js",
"dependencies": {
"#google-cloud/logging": "^9.1.0",
"#woocommerce/woocommerce-rest-api": "^1.0.1",
"algoliasearch": "^4.8.5",
"cors": "^2.8.5",
"csvtojson": "^2.0.10",
"express": "^4.17.1",
"firebase-admin": "^9.2.0",
"firebase-functions": "^3.14.1",
"mkdirp": "^1.0.4",
"stripe": "^8.137.0"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
In index.js i use
const cors = require('cors')({origin: true});
....
exports.StripeEvents = functions.https.onRequest((req, res) => {
cors(req, res, () => {
//// some code that worked great
}
}
I do not use cors-js package at all...
Where does the problem comes from?
Thank you
depending the browser that you are using and the Javascript that you are using in some cases they do not support all the features required by Firebase so you need to at the Polyfills, in this documentation they show you the way to add the Polyfills to your app, the no recommended way to do it is with the core-js library, feel free to do it what you want.
I quick way to solve the error could be go to the directory where your functions live and execute:
solution install core-js#2.6.5
Can't for the life of me figure out why my app suddenly won't start. I keep getting this error:
Unable to resolve module fs from
node_modules\firebase-admin\lib\firebase-namespace.js: fs could not
be found within the project.
If you are sure the module exists, try these steps:
Clear watchman watches: watchman watch-del-all
Delete node_modules and run yarn install
Reset Metro's cache: yarn start --reset-cache
Remove the cache: rm -rf /tmp/metro-*
whenever I run expo start in the root folder. I've even tried expo start -c to reset the cache.
I've also tried removing node_modules and npm installing it back for both the {myapp}/functions/node_modules and {myapp}/node_modules.
I've tried updating firebase-admin and all dependencies.
It's weird because my app was working a couple days ago and this came out of the blue. I've never had to install fs before.
Anyone got any idea what's going on here? It feels like a simple environment fix, but I'm not sure.
My app dependencies if it helps:
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject",
"test": "jest"
},
"dependencies": {
"#react-native-async-storage/async-storage": "^1.13.0",
"#react-native-community/masked-view": "0.1.10",
"algoliasearch": "^4.8.3",
"axios": "^0.21.1",
"buffer": "^6.0.3",
"expo": "^41.0.0",
"expo-font": "~9.1.0",
"expo-image-picker": "~10.1.4",
"expo-linear-gradient": "~9.1.0",
"expo-notifications": "~0.11.6",
"expo-status-bar": "~1.0.4",
"expo-web-browser": "~9.1.0",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-41.0.0.tar.gz",
"react-native-elements": "^3.0.0-alpha.1",
"react-native-gesture-handler": "~1.10.2",
"react-native-keyboard-aware-scroll-view": "^0.9.3",
"react-native-linear-gradient": "^2.5.6",
"react-native-paper": "^4.7.0",
"react-native-reanimated": "^1.13.3",
"react-native-screens": "^2.10.1",
"react-native-snap-carousel": "^3.9.1",
"react-native-svg": "12.1.0",
"react-native-svg-transformer": "^0.14.3",
"react-native-vector-icons": "^7.1.0",
"react-navigation": "^4.4.3",
"react-navigation-drawer": "^2.6.0",
"react-navigation-header-buttons": "^6.3.1",
"react-navigation-stack": "^2.9.0",
"react-navigation-tabs": "^2.10.1",
"react-redux": "^7.2.2",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"firebase": "8.2.3",
"jest": "^26.6.3",
"jest-expo": "^41.0.0",
"react-test-renderer": "^17.0.2"
},
"private": true,
"jest": {
"preset": "jest-expo",
"transformIgnorePatterns": [
"./node_modules/(?!(react-navigation-header-buttons|react-native|react-native-gesture-handler|#expo)|expo-font|#unimodules|expo-asset|expo-constants|expo-file-system|expo-web-browser|react-navigation|react-navigation-stack|unimodules-permissions-interface|expo-permissions|expo-image-picker|expo-linear-gradient/)"
],
"setupFiles": [
"./node_modules/react-native-gesture-handler/jestSetup.js"
],
"verbose": true,
"updateSnapshot": true
}
}
and .babelrc:
{
"presets": [
"babel-preset-expo"
]
}
and firebase functions dependencies:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "12"
},
"main": "index.js",
"dependencies": {
"algoliasearch": "^4.8.3",
"axios": "^0.21.0",
"cloudinary": "^1.23.0",
"crypto": "^1.0.1",
"events": "^3.3.0",
"express": "^4.17.1",
"firebase": "^8.7.0",
"firebase-admin": "^9.10.0",
"firebase-functions": "^3.14.1"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
firebase-admin is then intialized in my {myapp}/functions/index.js as:
const admin = require("firebase-admin");
admin.initializeApp();
and then used as (for example):
// Called for toggling Tutorial Prompt on ProfileScreen
exports.setTutorialPrompt = functions.https.onRequest(async (req, res) => {
res.set("Access-Control-Allow-Origin", "*");
if (req.method === "OPTIONS") {
// Send response to OPTIONS requests
res.set("Access-Control-Allow-Methods", "GET, POST");
res.set("Access-Control-Allow-Headers", "Content-Type");
res.set("Access-Control-Max-Age", "3600");
res.status(201).send("CORS preflight options set!");
} else {
const db = admin.firestore(); // <--------------------------- here
const { exampleId, ExampletwoId, value, screen } = req.body;
const updatedProfile = {
tutorialPrompt: value,
};
const index = await client.initIndex(ALGOLIA_INDEX_NAME);
index
.partialUpdateObject({
objectID: ExhibitUId,
tutorialPrompt: value,
})
.wait();
db.collection("users").doc(localId).update(updatedProfile);
res.status(201).send(`Successfully toggled tutorialing prompt`);
}
});
I managed to fix it.
It was a random import error within the root app folder. Somehow one of my imports got mixed up, and was trying to call a cloud function instead of a redux-action function.
The wrong import:
import { setTutorialPrompt } from "../../functions/index.js";
The correct import:
import { setTutorialPrompt } from "../../store/actions/user";
Since it was trying to import my functions folder, it gave me the fs error. Similar to what #brentvatne was talking about.
If anyone else runs into this error, I recommend moving your cloud functions folder to your desktop or something, and try running your app without it. That's how I found the right error code.
I found this because I ran into pretty much exactly this same issue.
I discovered that there are (weirdly) two ways you can import firebase-admin into react native projects. I was doing import { firestore } from "firebase-admin" and I needed to be doing import firestore from '#react-native-firebase/firestore'
A pretty easy-to-miss difference, so I thought I’d leave a comment here in case anyone else has this issue.
I am getting this error when trying to use #google-cloud/logging with Firebase Functions. If I remove the logging stuff everything works fine. I also tried using #google-cloud/logging-winston however, causing the same error along with an additional error.
Here is my code:
const functions = require('firebase-functions')
const mongoose = require('mongoose')
const Tag = require('../../models/tag')
const { Logging } = require('#google-cloud/logging')
const logging = new Logging({projectId: 'circle-fc687'})
const log = logging.log('tags')
const METADATA = {
resource: {
type: 'cloud_function',
labels: {
function_name: 'tags-getTags',
region: 'us-central1'
}
}
}
const uri = 'mongoURL'
module.exports = functions.https.onRequest(async (req, res) => {
try {
console.log('getTags : start')
const logOne = log.entry(METADATA, { event: 'getTags:mongodb:started', value: 'started', message: 'tags-getTags:started' })
log.write(logOne) // I've also tried with an await here thinking maybe it was trying to do something after the function terminates but that didn't fix anything
console.log('getTags : after first logging statement') // doesn't work
await mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
const result = await Tag.find({})
res.send(result)
} catch (err) {
res.send(err)
}
})
Here is the error:
Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:161:19)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
Edit 1: adding package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "10"
},
"dependencies": {
"#google-cloud/logging": "^6.0.0",
"#google-cloud/logging-winston": "^3.0.2",
"axios": "^0.19.0",
"cors": "^2.8.5",
"firebase-admin": "^8.9.0",
"firebase-functions": "^3.3.0",
"mongoose": "^5.8.3",
"mongoose-unique-validator": "^2.0.3",
"winston": "^3.2.1"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.1.7"
},
"private": true
}
I am trying to test my cloud functions locally. I am using the command firebase functions:shell which starts the emulator successfully. I have the following cloud function in my index.ts:
export const stripeCharge = functions.region('europe-west1').database
.ref('/payments/{userId}/{paymentId}')
.onWrite(async (change, context) => {
someCode;
});
I read that you should invoke an onWrite firestore function the following way (https://firebase.google.com/docs/functions/local-shell):
stripeCharge({before: "oldData", after: "newData"})
However, this results in the following error:
'Successfully invoked function.'
firebase > ! TypeError: Cannot read property 'eventType' of undefined
at cloudFunction (C:\Users\Jesper\intergun\functions\node_modules\firebase-functions\lib\cloud-functions.js:80:40)
at Run (C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:458:20)
at C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:442:19
at Generator.next (<anonymous>)
at C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:7:71
at new Promise (<anonymous>)
at __awaiter (C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:3:12)
at Run (C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:435:12)
at C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:457:15
at Generator.next (<anonymous>)
! Your function was killed because it raised an unhandled error.
The error happens in some other file and I'm not sure why. What am I missing?
Edit: My package.json:
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"main": "lib/index.js",
"dependencies": {
"#google-cloud/storage": "^2.5.0",
"#types/fs-extra": "^7.0.0",
"firebase-admin": "^8.1.0",
"firebase-functions": "^3.0.1",
"fs-extra": "^8.0.1",
"mailgun-js": "^0.22.0",
"sharp": "^0.22.1",
"stripe": "^7.1.0"
},
"devDependencies": {
"#types/sharp": "^0.22.2",
"#types/stripe": "^6.30.0",
"firebase-functions-test": "^0.1.6",
"tslint": "^5.12.0",
"typescript": "^3.2.2"
},
"private": true
}
After replicating this I've found this thread it looks there is an open case for this issue.
The similar setup works fine for Firestore, but the issue seems to to be with the RTDB, I assume we have to wait until they solve it, sorry :(
Hi there I'm trying to deploy a simple function using firebase hosting and the following error arises in my firebase log when I do:
TypeError: Cannot set property 'content-type' of undefined
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:365:22)
at ServerResponse.header (/user_code/node_modules/express/lib/response.js:767:10)
at ServerResponse.contentType (/user_code/node_modules/express/lib/response.js:595:15)
at ServerResponse.send (/user_code/node_modules/express/lib/response.js:145:14)
at app.get (/user_code/lib/index.js:10:22)
at Layer.handle [as handle_request] (/user_code/node_modules/express/lib/router/layer.js:95:5)
at next (/user_code/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/user_code/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/user_code/node_modules/express/lib/router/layer.js:95:5)
at /user_code/node_modules/express/lib/router/index.js:281:22
Seeing as I've just started with firebase hosting, I have no idea what could be causing this; here are my files:
src > index.ts:
import * as functions from 'firebase-functions';
import * as express from 'express';
// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
const app = express();
export const getTime = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
firebase.json:
{
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites":[{
"source": "/timestamp",
"function": "getTime"
}]
},
"functions": {
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint",
"npm --prefix \"$RESOURCE_DIR\" run build"
]
}
}
package.json:
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"main": "lib/index.js",
"dependencies": {
"express": "^4.16.4",
"firebase-admin": "~6.0.0",
"firebase-functions": "^2.1.0"
},
"devDependencies": {
"tslint": "^5.12.0",
"typescript": "^3.2.2"
},
"private": true
}
As you could see here, your index.ts should be :
import * as functions from 'firebase-functions';
import * as express from 'express';
// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
const app = express();
app.get("*", (request, response) => {
response.send("Hello from Firebase!");
});
export const getTime = functions.https.onRequest(app);