Web3: My deployment gets stuck over Test Eth Network. [Error: Failed to check for transaction receipt: with contract.deploy()] - deployment

I trying to deploy my contract using node. I am following a youtube tutorial https://www.youtube.com/watch?v=3oaJynB0nKc&list=PLzb46hGUzitDd39YzB1YvZqeIXXtmBrHX&index=26.
I'm following everything according to this tutorial but every time I run "node deploy.js", I either get timeout error: (Note I am not using any truffle framework yet.)
process["on"]("unhandledRejection", function (reason) { throw reason; });
^
Error: Failed to check for transaction receipt:
{}
at Object._fireError (C:\Users\schit\Desktop\Solidity Dapp\inbox\node_modules\web3-utils\lib\index.js:49:17)
at C:\Users\schit\Desktop\Solidity Dapp\inbox\node_modules\web3-core-method\lib\index.js:246:23
My code is as follows:
const HDWalletProvider = require('#truffle/hdwallet-provider');
const Web3 = require('web3');
const interface = require('./compile.js');
let abi = interface.abi;
let bytecode = interface.bytecode;
var mnemonic = '12-word mnemonic';
var endpoint = 'https://ropsten.infura.io/v3/<key>';
const provider = new HDWalletProvider({
mnemonic: {
phrase: mnemonic
},
providerOrUrl: endpoint
});
console.log('********DEBUG*LOG**********2');
const options = {
transactionConfirmationBlocks: 1
};
const web3 = new Web3(provider, null, options);
console.log('********DEBUG*LOG**********3')
const deploy = async () => {
const accounts = await web3.eth.getAccounts();
var balance = await web3.eth.getBalance(accounts[0]);
console.log('Account balance: ', web3.utils.fromWei(balance, "ether"));
console.log('Attempting to deploy from account', accounts[0]);
var contract = new web3.eth.Contract(abi);
**const result = await contract
.deploy({data: '0x' + bytecode, arguments: ['Hi there!']})
.send({from: accounts[0], gas: '1000000'})
.on ('error', console.error)
.on ('transactionHash', console.log)
.on ('receipt', console.log);**
console.log('Contract deployed to', result.options.address);
};
deploy();

Related

How to solve Vercel 500 Internal Server Error?

I have created a project that uses MongoDB to store user info and Next-Auth to authenticate users. On local host this is all working seamlessly. Previously I had a couple errors with my next-auth config, but that seems to be working fine now on Vercel live site. Once the user logs in they are redirected to "my-project/suggestions". On this page I am using getServerSideProps to identify if there is a valid session token. If so, data is pulled from a local json file.
On the live site, when the user logs in, the page is redirected to "/suggestions", yet I am receiving an 500 Internal Server Error page. On the function logs I am getting this error message:
[GET] /_next/data/KpsnuV9k44lUAhQ-0rK-B/suggestions.json
10:10:57:12
2022-05-05T14:10:59.270Z 5b7a7375-045f-4518-864b-7968c3c9385f ERROR [Error: ENOENT: no such file or directory, open '/var/task/public/data/data.json'] {
errno: -2,
syscall: 'open',
path: '/var/task/public/data/data.json',
page: '/suggestions'
}
RequestId: 5b7a7375-045f-4518-864b-7968c3c9385f Error: Runtime exited with error: exit status 1
Runtime.ExitError
This is my first project using MongoDB and Next-Auth.. not so sure what the issue is in this case. In my .env.local file I only have these two variables:
NEXTAUTH_SECRET="MUNKNATION"
NEXTAUTH_URL=http://localhost:3000
How I am pulling the data on local host:
export const getServerSideProps = async (context) => {
const session = await getSession({ req: context.req });
if (!session) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
} else {
let filePath = path.join(process.cwd(), "public", "data", "data.json");
let jsonData = await fs.readFile(filePath);
const data = JSON.parse(jsonData);
const inProgressStatusData = data.productRequests.filter(
(item) => item.status == "in-progress"
);
const liveStatusData = data.productRequests.filter(
(item) => item.status == "live"
);
const plannedStatusData = data.productRequests.filter(
(item) => item.status == "planned"
);
let filterData = filteredData(data, "suggestion");
let feedbackData = {
suggestions: filterData,
progress: inProgressStatusData,
planned: plannedStatusData,
live: liveStatusData,
};
return {
props: { session, feedbackData },
};
}
};
Folder structure:
A simple solution to this problem would be to, inside of your getServerSideProps, instead of calling readFile use readFileSync as follows:
export const getServerSideProps = async (context) => {
...
const file = readFileSync(
join(process.cwd(), "public", "data", "data.json"),
"utf8"
);
const data = JSON.parse(fileData);
...
I have tested this solution with Vercel and it works correctly, in development and production mode.

sendAndConfirmTransaction bug?

In my application I use the signatures returned from web3.sendAndConfirmTransaction to do some offline/async reporting relating to the fees incurred by my transactions.
i.e. i use the signature to retrieve the transaction and then use the transaction?.meta?.fee field.
I have noticed though, when my transaction contains 2 instructions (in my example below) that the signature returned only contains the fee relating to 1 of the instructions. When I check the transaction history of my phantom wallet I can clearly see 2 separate fees - one for each instruction
async createTokenMetadataForToken(
business,
token_type
) {
const mint_authority = web3.Keypair.fromSeed(
derivePath(
`m/44'/501'/0'/0'`,
Bip39.mnemonicToSeedSync(
JSON.parse(business.keys).MINTER_SEED
).toString("hex")
).key
);
const metadata = await Metadata.getPDA(token_type.token_address);
const host = (config.nodeEnv == 'prod') ? 'https://<url>' : 'https://<url>'
const createMetadataTx = new CreateMetadataV2(
{ feePayer: mint_authority.publicKey },
{
metadata,
metadataData: new DataV2({
uri: `${host}/token_type/${token_type.token_type_id}/metadata`,
name: token_type.name,
symbol: token_type.symbol,
sellerFeeBasisPoints: 100,
creators: null,
collection: null,
uses: null,
tokenStandard: TokenStandard.FungibleAsset,
}),
updateAuthority: mint_authority.publicKey,
mint: new web3.PublicKey(token_type.token_address),
mintAuthority: mint_authority.publicKey,
}
);
const connection = getConnection(token_type.cluster);
const transaction = new web3.Transaction();
console.log("creating metadata")
transaction.add(createMetadataTx)
if(token_type?.equity_total_supply > 0){
console.log("also creating equity in same trx..")
//look up token
const token = new Token(
connection,
new web3.PublicKey(token_type.token_address),
TOKEN_PROGRAM_ID,
mint_authority
);
const recipientTokenAddress = await token.getOrCreateAssociatedAccountInfo(
new web3.PublicKey(mint_authority.publicKey)
);
transaction.add(
Token.createMintToInstruction(
TOKEN_PROGRAM_ID,
new web3.PublicKey(token_type.token_address),
recipientTokenAddress.address,
mint_authority.publicKey,
[mint_authority],
token_type?.equity_total_supply
)
)
}
const sig = await web3.sendAndConfirmTransaction(connection, transaction, [mint_authority], {
skipPreflight: false
})
return sig; //This signature only contains fee of one of the parts of the transaction
}

Cypress crashes when test that uses gmail-tester library finished it work

I'm was trying to use "gmail-tester" library to verify the account creation message.
https://www.npmjs.com/package/gmail-tester
It seems that I settled up everything as it was supposed to be done. When my test is finished I supposed to get an assertion in cypress such as this
Instead, cypress is awaiting for a message for 30seconds
, then browser crashes and I got this
Does anyone know what would cause the problem?
I have managed to complete all steps mentioned in this tutorial:
https://levz0r.medium.com/how-to-poll-a-gmail-inbox-in-cypress-io-a4286cfdb888
../cypress/plugins.index.js
/// <reference types="cypress" />
// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************
// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)
/**
* #type {Cypress.PluginConfig}
*/
// eslint-disable-next-line no-unused-vars
const path = require("path");
const gmail = require("gmail-tester");
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
// ...
on("task", {
"gmail:check": async args => {
const { from, to, subject } = args;
const email = await gmail.check_inbox(
path.resolve(__dirname, "credentials.json"), // credentials.json is inside plugins/ directory.
path.resolve(__dirname, "gmail_token.json"), // gmail_token.json is inside plugins/ directory.
subject,
from,
to,
10, // Poll interval (in seconds)
12 // Maximum poll interval (in seconds). If reached, return null, indicating the completion of the task().
);
return email;
}
});
};
testCase.spec.js
import Navigation from '../../../utils/navigation.spec'
import LoginPage from '../../../pageobject/login/login-page'
describe("New user registration", async function() {
beforeEach(() => {
cy.visit(Navigation.Login)
})
it.only("Reset Form: Email is delievered", function() {
const test_id = new Date().getTime();
const incoming_mailbox = `userautomatedtest+${test_id}#gmail.com`;
// const password = uuidv1().split("-")[0];
const login = new LoginPage();
const username = "Cypress" + test_id;
const password = "111#wZOO";
login.registerButton()
.usernameInput(username)
.emailInput(incoming_mailbox)
.firstNameInput("Name")
.lastNameInput("Surname")
.passwordInput(password)
.repeatPasswordInput(password)
.registerButton()
//assert
cy.contains('Registration succeeded').should('be.visible')
cy.task("gmail:check", {
from: "dev.mailer.no.reply#gmail.com",
to: incoming_mailbox,
subject: "Registration confirmation"
})
.then(email => {
assert.isNotNull(email, `Email was not found`);
});
});
});
btw: in documentation is mentioned that by changing this number we can manipulate awaiting time for checking email. In my case, I'm changing this value and nothing is happening.
This is some problem with the OAuth consent screen, probably access given is not correct, or the GMail API isn't enabled.
Using the most recent version of this package, I had the same issue with the plugins/index.js crashing.
I solved this by adjusting the options-parameter to match the gmail task package function check_inbox.
module.exports = (on, config) => {
on("task", {
"gmail:check": async (args) => {
const { from, to, subject } = args;
const email = await gmail.check_inbox(
path.resolve(__dirname, "credentials.json"),
path.resolve(__dirname, "gmail_token.json"),
{
subject: subject,
from: from,
to: to,
wait_time_sec: 10,
max_wait_time_sec: 30,
}
);
return email;
},
});
};

index.js command handler problems

I have a problem, when I debug on visual studio code, it gives me this error message "Uncaught Error: Cannot find module './command/$(files)'
Require stack:
"c:\Users\user\OneDrive\Bureau\himetsubabot\index.js"
however I put the right path and my file is called commande, here is the code
const fs = require('fs');
const Discord = require('discord.js');
const bot = new Discord.Client()
const config = require ("./config.js");
bot.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commande').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require('./commande/$(files)')
client.command.set(command.name, command)
}
bot.on("ready", async message => {
console.log("Le bot démarre")
bot.user.setStatus('online')
bot.user.setActivity("en développement")
})
bot.on('message', async (msg) => {
if(msg.content.startsWith(config.prefix) && !msg.author.bot){
cmdArray = msg.content.substring(config.prefix.length).split(" ");
cmd = cmdArray[0];
args = cmdArray.slice(1);
let command = commands.getCommand(cmd);
if(command) command.run(bot, msg, args);
if(cmd === '8ball'){}
}
})
bot.login(config.token)
Instead of using "('/commande/$(files)')" use "('./commande/${files}')".
What i mean is to use ${files} instead of $(files).

"Unable to connect to the Parse API" using Parse Server on Heroku

I'm getting the error Failed to create new object, with error code: XMLHttpRequest failed: "Unable to connect to the Parse API" when i try to connect to Parse Server API. I deployed ParsePlatform/parse-server-example on Heroku. I can access to my app with a broswser with no problems.I get the error when trying to connect to Parse on Heroku with this code :
var $result=$('#results').html('Testing configuration.....');
Parse.initialize('<MY_APP_ID>', '<MY_JAVASRIPT_KEY>');
Parse.serverURL = '<MY_HEROKU_APP_NAME>.herokuapp.com/'
var ParseServerTest = Parse.Object.extend('ParseServerTest');
var _ParseServerTest = new ParseServerTest();
_ParseServerTest.set('key', 'value');
_ParseServerTest.save(null, {
success: function(_ParseServerTest) {
var txt = 'Yay, your server works! New object created with objectId: ' + _ParseServerTest.id;
$result.html('<div class="alert alert-success" role="alert">' + txt + '</div>');
},
error: function(_ParseServerTest, error) {
var txt = 'Bummer, Failed to create new object, with error code: ' + error.message;
$result.html('<div class="alert alert-danger" role="alert">' + txt + '</div>');
}
});
index.js
// Example express application adding the parse-server module to expose Parse
// compatible API routes.
var express = require('express');
var cors = require('cors');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '', //Add your master key here. Keep it secret!
serverURL: process.env.SERVER_URL || 'https://localhost:1337/parse', // Don't forget to change to https if needed
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var app = express();
app.use(cors());
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
res.status(200).send('I dream of being a website. Please star the parse-server repo on GitHub!');
});
// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
Heroku config :
I followed this post : How can I host my own Parse Server on Heroku using MongoDB? except i didn't use the "Deploy to Eroku" button, i deployed it manually.
Thank you for your help.
Finally I found a way.
I first created another user in my mongo db and change it in Heroku. Try to connect with the same js code code jsfiddle but didn't work...
Then I tried with an android client, this link helped me a lot http://www.robpercival.co.uk/parse-server-on-heroku/
StarterApplication.java
public class StarterApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("BUTYcVjD7nFz4Le")
.clientKey("XgQaeDY8Bfvw2r8vKCW")
.server("https://xxxxx-xxxx-xxxxx.herokuapp.com/parse")
.build()
);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
// defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
ParseObject test = new ParseObject("Test");
test.put("username","pedro");
test.put("age",33);
test.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Log.i("Parse", "Save Succeeded");
} else {
Log.e("Parse", "Save Failed");
}
}
});
}
I really don't know what was the problem with my first user, can't connect with it. I never could connect with the js code... but anyway my goal was to connect with Android client so...