Trying to deploy smart contract without truffle (a manual route) - angular5

I am a beginner and want to integrate front-end (angular js) with blockchain.
I have successfully compiled and deployed smart contract using Truffle.
Can I deploy the smart contract without using truffle i.e manual route.
I have searched many blogs but couldn't find a better source for this question. If you have a better source, please help me out

I have created the plan contract deployer using nodeJS. Please find below code.
Step 1: Install the nodeJS and NPM in your computer.
Step 2: Create "deployer" folder and add package.json in same folder
Step 3: Create "contracts" & "compiled" folder under "deployer" folder
Step 4: created deployer.js file in "deployer" folder.
Step 5: Run $npm install command
Step 6: Keep your smart contract ".sol" file in "contracts" folder.
Step 7: Run $node deployer.js command to deploy contract on local Ganache client (truffle). If you have other client or blockchain node. Please update rpc url in "deployer.js" file. OR install Ganache RPC client, you will find truffle site.
Files:
package.json:
{
"name": "deployer",
"version": "1.0.0",
"description": "Test deployer",
"main": "deployer.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Mahesh Patil",
"license": "ISC",
"dependencies": {
"async": "^2.6.0",
"body-parser": "1.15.2",
"express": "4.14.0",
"request": "2.79.0",
"solc": "0.4.8",
"web3": "0.18.2"
}
}
==========
deployer.js:
var Web3 = require("web3");
// Replace the blockchain node url, I am installed Ganache client very easy for testing
var web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545/"));
var fs = require('fs');
var solc = require('solc');
var async = require('async');
var cDir = fs.readdirSync("./contracts");
console.log(cDir);
var contracts = cDir.reduce(function (acc, file) {
acc[file] = fs.readFileSync("./contracts/" + file, { encoding: "utf8" });
return acc;
}, {});
var output = solc.compile({ sources: contracts }, 1);
if (output.errors) {
throw output.errors;
};
var owner = web3.eth.coinbase;
web3.eth.defaultAccount = owner;
var contracts = [];
web3.personal.unlockAccount(owner, "", 120000, function (err, success) {
var all = [];
Object.keys(output.contracts).forEach(function (name) {
var contract = output.contracts[name];
contract.interface = JSON.parse(contract.interface);
deployContract(contract, name).then(res => {
console.log(name, " Address: ", res);
})
});
});
function deployContract(contract, fileName) {
return new Promise((resolve, reject) => {
web3.eth.contract(contract.interface).new({
data: "0x" + contract.bytecode,
gas: 900000, // If you get gas issue please change this value according error
// privateFor: [],
from: owner,
}, function (err, myContract) {
if (err) {
console.log(err);
reject(err);
}
if (!err) {
if (!myContract.address) {
console.log(fileName + " : " + myContract.transactionHash); // The hash of the transaction, which deploys the contract
} else {
contract.address = myContract.address;
fs.writeFileSync("./compiled/" + fileName + ".json", JSON.stringify(contract, null, 4));
//cb(null, myContract.address); // the contract address
resolve(myContract.address);
}
}
});
});
}

While not ideal, you could technically use the Remix online IDE (http://remix.ethereum.org/) if you have Metamask installed.

Related

How do I integrate cucumber-js with selenium webdriver

I'm kinda new to cucumber and selenium and I've been running into an issue with selenium webdriver where it doesn't connect or gets a "Error: ECONNREFUSED connect ECONNREFUSED "127.0.0.1:50546". I've tried both chromedriver and geckodriver for Firefox but still doesn't want to connect. I've been using the npm versions of each one as well as the downloaded ones. I've also tried simple synchronous code to get rid of the errors. I've also tried to specify the selenium-webdriver's port but that still doesn't work. Do I have to have the selenium stand-alone server? What am I missing here?
Gecko Driver Error: https://i.stack.imgur.com/oDtJB.png
Chrome Driver Error: https://i.stack.imgur.com/YhqhC.png
My .feature file:
Feature: Testing With Selenium
Scenario: Finding some cheese
Given I am on the Google search page
When I search for "Cheese!"
Then the page title should start with "cheese"
My step Definitions:
const {Given, When, Then, AfterAll} = require('#cucumber/cucumber');
const { Builder, By, Capabilities, Key } = require('selenium-webdriver');
const { expect } = require('chai');
const assert = require('assert');
//Driver and Browser setup
require('chromedriver');
const driver = new Builder().forBrowser('chrome').build();
function isItFriday(today) {
if(today == "Friday"){
return "TGIF";
}else{
return "Nope"
}
}
Given('today is {string}', function (givenDay) {
this.today = givenDay;
});
When('I ask whether it\'s Friday yet', function () {
this.actualAnswer = isItFriday(this.today);
});
Then('I should be told {string}', function (expectedAnswer) {
assert.strictEqual(this.actualAnswer, expectedAnswer);
});
Given('I am on the Google search page', {timeout: 60 * 1000}, async() => {
await driver.get('http://www.google.com');
});
When('I search for {string}', {timeout: 1000 * 1000}, async(searchTerm) => {
const element = await driver.findElement(By.name('q'));
element.sendKeys(searchTerm, Key.RETURN);
element.submit();
});
Then('the page title should start with {string}', function (string) {
const title = driver.getTitle();
const isTitleStartWithCheese = title.toLowerCase().lastIndexOf(`${searchTerm}`, 0) === 0;
expect(isTitleStartWithCheese).to.equal(true);
});
AfterAll(async () => {
await driver.quit();
});
My package.json file:
{
"name": "cucumberdemo",
"version": "1.0.0",
"description": "This is a demo project to understand the basics of Cucumber's BDD Testing Framework",
"main": "app.js",
"dependencies": {
"#cucumber/cucumber": "^8.0.0",
"chai": "^4.3.6",
"chromedriver": "^100.0.0",
"geckodriver": "^3.0.1",
"pactum": "^3.1.5",
"selenium-webdriver": "^4.1.1"
},
"scripts": {
"test": "cucumber-js"
},
"author": "Shahroz Noorani",
"license": "ISC"
}

Error deploying smart contract using Hardhat -- Error HH9: Error while loading Hardhat's configuration

Trying to deploy a smart contract using Hardhat but getting configuration error.
Here is the complete error details
Error HH9: Error while loading Hardhat's configuration.
You probably tried to import the "hardhat" module from your config or a file imported from it.
This is not possible, as Hardhat can't be initialized while its config is being defined.
All the plug-ins seem to be have been installed correctly.
deploy.js
const hre = require("hardhat");
async function main() {
const TestContract = await hre.ethers.getContractFactory("TestContract");
const superInstance = await TestContract.deploy("TestContractHAT", "SMC");
await superInstance.deployed();
console.log("contract was deployed to:", superInstance.address());
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
package.json
{
"name": "Test",
"version": "1.0.0",
"description": "This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, a sample script that deploys that contract, and an example of a task implementation, which simply lists the available accounts.",
"main": "hardhat.config.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.5",
"#nomiclabs/hardhat-waffle": "^2.0.3",
"chai": "^4.3.6",
"ethereum-waffle": "^3.4.4",
"ethers": "^5.6.2"
},
"dependencies": {
"dotenv": "^16.0.0",
"hardhat": "^2.9.3"
}
}
Hardhat.config
const { ethers } = require("hardhat");
require('#nomiclabs/hardhat-waffle');
require("#nomiclabs/hardhat-ethers");
require('#openzeppelin/hardhat-upgrades');
require("dotenv").config();
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.2",
networks: {
mumbai: {
url: process.env.MUMBAI_URL,
account: process.env.PRIVATE_KEY
}
}
};
Any pointers are helpful. Thanks
As the error states, you are importing hardhat module in your hardhat configuration.
You probably tried to import the "hardhat" module from your config or a file imported from it. This is not possible, as Hardhat can't be initialized while its config is being defined.
Remove the line
const { ethers } = require("hardhat");
and the error should disappear
Just remove
const { ethers } = require("hardhat");
or
const { hardhatArguments } = require("hardhat");
or any other that requires hardhat

Can't deploy smart contract to hardhat network

I set up a project with hardhat for an NFT app. I modify hardhat.config.js like this:
const { ALCHEMY_KEY, ACCOUNT_PRIVATE_KEY } = process.env;
module.exports = {
solidity: "0.8.0",
defaultNetwork: "hardhat",
networks: {
hardhat: {},
rinkeby: {
url: `https://eth-rinkeby.alchemyapi.io/v2/${ALCHEMY_KEY}`,
accounts: [`0x${ACCOUNT_PRIVATE_KEY}`]
},
// ethereum: {
// chainId: 1,
// url: `https://eth-mainnet.alchemyapi.io/v2/${ALCHEMY_KEY}`,
// accounts: [`0x${ACCOUNT_PRIVATE_KEY}`]
// },
},
}
then I created a deploy script in the scripts folder with the deploy task
// scripts/deploy.js
const { task } = require("hardhat/config");
const { getAccount } = require("./helpers");
task("deploy", "Deploys the TokenV2.sol contract").setAction(async function (taskArguments, hre) {
const tokenFactory = await hre.ethers.getContractFactory("TokenV2", getAccount());
const token = await tokenFactory.deploy();
await token.deployed()
console.log(`Contract deployed to address: ${token.address}`);
});
The problem it's when I run npx hardhat deploy it's shows this error in terminal: Error: unsupported getDefaultProvider network (operation="getDefaultProvider", network="hardhat", code=NETWORK_ERROR, version=providers/5.5.3) What I missed? I will appreciate any help.
I never used defaultNetwork in my works so I just had the following hardhat.config File and had no issues at all:
{
"solidity":"0.8.4",
"networks":{
"rinkeby":{
"url":"`https://eth-rinkeby.alchemyapi.io/v2/${ALCHEMY_KEY}`",
"accounts":[
"`0x${ACCOUNT_PRIVATE_KEY}`"
]
}
}
}

Agora.io client joining the channel is not working properly in vuejs

created() {
let $ = this;
// init AgoraRTC local client
const config = {
mode: "rtc",
codec:"h264",
areaCode: [AgoraRTC.AREAS.GLOBAL]
};
$.client = AgoraRTC.createClient(config);
$.client.init($.appId, () => {
console.log("AgoraRTC client initialized");
$.subscribeStreamEvents();
$.client.join($.appId, $.channel, $.uid, function(uid) {
console.log("User " + uid + " join channel successfully");
console.log("At " + new Date().toLocaleTimeString());
// create local stream
// It is not recommended to setState in function addStream
$.localStream = this.streamInit(uid, $.attendeeMode, $.videoProfile);
$.localStream.init(
() => {
if ($.attendeeMode !== "audience") {
$.addStream($.localStream, true);
$.client.publish($.localStream, err => {
console.log("Publish local stream error: " + err);
});
}
$.readyState = true;
},
err => {
console.log("getUserMedia failed", err);
$.readyState = true;
}
);
},function(err) {
console.error("client join failed", err);
});//end join
});//end init
},
Agora installed using npm
npm i agora-rtc-sdk
"agora-rtc-sdk": "^3.1.2",
"vue": "^2.5.17",
"vuetify": "^2.2.9"
in the above code
$.client.join($.appId, $.channel, $.uid, function(uid) {
this line keep joining but did not succeed and also do not gives failure error. it just keep trying to connect to server.
here is the screenshot of errors/warnings
Please help me I'm stuck on it for 2 days
And Sorry for bad english
I think the documentation is a bit tricky on this one. The client.join() function accepts 4 arguments as follows:
client.join(APPID, CHANNEL, TOKEN(can be null), UID(optional), function(uid){
// uid returned
})
So update your code to read:
$.client.join($.appId, $.channel, null, function(uid) {
I'm actually using the AgoraWebSDK NG for my VueJS project. You can checkout the guide to migration here: https://agoraio-community.github.io/AgoraWebSDK-NG/docs/en/migration_guide.

How to keep my keys in safe in react native (expo)?

I have 3 release channels - dev, qa, prod.
const ENV_MODES = {
dev: {
},
prod: {
},
qa: {
}
}
ENV_MODES.default = ENV_MODES.prod
const getEnvVars = channel => {
if (process.env.NODE_ENV !== 'production') return ENV_MODES.dev
if (channel === null || channel === undefined || channel === '') return ENV_MODES.prod
if (channel.startsWith(ENV_DEV)) return ENV_MODES.dev
if (channel.startsWith(ENV_QA)) return ENV_MODES.qa
if (channel.startsWith(ENV_PROD)) return ENV_MODES.prod
return ENV_MODES.default
}
const ENV = getEnvVars(Constants.manifest.releaseChannel)
But I don't want to put keys into the repo.
How should I handle this? As I understand I can't expect that I will have NODE_ENV === 'qa' when I will publish in QA channel
You could use react-native-dotenv and add your keys to a .env file and add it to .gitignore. This way you won't be pushing keys to your repo and you can change your variables depending on the environment your code is running on.
To use the lib you only need to add it to your devDependencies and add it to you babel.config.js file, like so:
module.exports = function (api) {
api.cache(true);
return {
presets: [
'babel-preset-expo',
'module:react-native-dotenv',
],
};
};
EDIT:
NODE_ENV won't be the same as your release channel. If you want to load configs based on the release channel use Expo.Constants.manifest.releaseChannel.
However have in mind this variable doesn't exist in Dev mode, as per expo's docs.
Expo.Constants.manifest.releaseChannel does NOT exist in dev mode. It does exist, however when you explicitly publish / build with it.
EDIT 2:
Here's an example on how you can achieve both individual configurations for each release channel and use react-native-dotenv to avoid pushing secrets to your Git repo (since this is a big no no).
Remember: add your .env file to your .gitignore.
Constants.js
// eslint-disable-next-line import/no-extraneous-dependencies
import { AWS_KEY } from 'react-native-dotenv';
import { Constants as ExpoConstants } from 'expo';
const getChannelConfigs = (releaseChannel = '') => {
switch (releaseChannel) {
case 'qa':
return {
API_URL: 'https://qa.com/api',
...
};
case 'prod':
return {
API_URL: 'https://prod.com/api/',
...
};
default:
return {
API_URL: 'https://dev.com/api/',
...
};
}
};
const CHANNEL_CONFIGS = Object.freeze(getChannelConfigs(ExpoConstants.manifest.releaseChannel));
export default { AWS_KEY, CHANNEL_CONFIGS };
.env
AWS_KEY='superSecretKeyDoNOTStealThx'
In this example we are configuring which API URL the app will call based on its release channel. We're also avoiding commiting keys to our Git repo, since we now have them in a cozy .env file.
It's also worth mentioning this setup works when building a standalone app in your CI, but handing secret keys to your users might not be the best idea.
Expo now has eas.json file that sits in root of your app. That file can define all the build profiles and variables if needed. The submit feature of the configuration helps manage all the app store related configs.
Sensitive secrets (prod ids and paths) , feature flags are all possible to configure.
https://docs.expo.dev/build-reference/variables/
{
"build": {
"production": {
"node": "16.13.0",
"env": {
"API_URL": "https://company.com/api"
}
},
"preview": {
"extends": "production",
"distribution": "internal",
"env": {
"API_URL": "https://staging.company.com/api"
}
}
}
"submit": {
"production": {
"android": {
"serviceAccountKeyPath": "../path/to/api-xxx-yyy-zzz.json",
"track": "internal"
},
"ios": {
"appleId": "john#turtle.com",
"ascAppId": "1234567890",
"appleTeamId": "AB12XYZ34S"
}
}
}
}