I'm trying to run a js script on the blockchain using hardhat. After running it in the command line it throws an error - blockchain

This is the following error I get when running the command "npx hardhat --network localhost scripts/1_deploy.js"
HeadersTimeoutError: Headers Timeout Error
at Timeout.onParserTimeout [as _onTimeout] (/mnt/g/ONLINE_COURSE/project/blockchain-developer-bootcamp/node_modules/undici/lib/client.js:902:28)
at listOnTimeout (node:internal/timers:561:11)
at processTimers (node:internal/timers:502:7) {
code: 'UND_ERR_HEADERS_TIMEOUT'
I dont know the fix to this Kindly help.
The script I'm trying to run
async function main() {
console.log(`Preparing deployment...\n`)
// Fetch contract to deploy
const Token = await ethers.getContractFactory('Token')
const Exchange = await ethers.getContractFactory('Exchange')
// Fetch accounts
const accounts = await ethers.getSigners()
console.log(`Accounts fetched:\n${accounts[0].address}\n${accounts[1].address}\n`)
// Deploy contracts
const edge = await Token.deploy('EDGE University', 'EDGE', '1000000')
await edge.deployed()
console.log(`EDGE Deployed to: ${edge.address}`)
const mETH = await Token.deploy('mETH', 'mETH', '1000000')
await mETH.deployed()
console.log(`mETH Deployed to: ${mETH.address}`)
const mDAI = await Token.deploy('mDAI', 'mDAI', '1000000')
await mDAI.deployed()
console.log(`mDAI Deployed to: ${mDAI.address}`)
const exchange = await Exchange.deploy(accounts[1].address, 10)
await exchange.deployed()
console.log(`Exchange Deployed to: ${exchange.address}`)
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

Related

Problem with AWS API Gateway websocket- Lambda postToConnection

I've been trying to solve this problem all day, looking everywhere on the web, even in the official AWS documentation, why does this error keep appearing when I try to send a message to the client through this code?
PS. i use SDK v3 with node.js 18
import {
ApiGatewayManagementApiClient,
PostToConnectionCommand,
} from "#aws-sdk/client-apigatewaymanagementapi";
export const handler = async (event) => {
const domain = event.requestContext.domainName;
const stage = event.requestContext.stage;
const connectionId = event.requestContext.connectionId;
const callbackUrl = `https://${domain}/${stage}`;
const client = new ApiGatewayManagementApiClient({ endpoint: callbackUrl });
const requestParams = {
ConnectionId: connectionId,
Data: "Hello!",
};
const command = new PostToConnectionCommand(requestParams);
try {
await client.send(command);
} catch (error) {
console.log(error);
}
return {
statusCode: 200,
};
};
fef17825-58ce-4ca7-8f38-85857f1aef0a Task timed out after 3.01 seconds
i tried any online guide or video, can anyone help me?

Unable to access the Hyperledger Fabric Network using API Error : "DiscoveryService: mfd-prd-channel error: access denied"

I have implemented hyperledger fabric network using v2.2 with 5 organizations. Chaincode implementation is accessible using cli but when using API it gives error "DiscoveryService: mfd-prd-channel error: access denied"
SDK used :
fabric-network: ^2.2.15
Note : Using cryptogen for certificate generation
Function used to invoke transaction
const invokeTransaction = async (
channelName,
chaincodeName,
fcn,
args,
username,
org_name
) => {
try {
const ccp = await registerUser.getCCP(org_name);
const walletPath = await registerUser.getWalletPath(org_name);
const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
let identity = await wallet.get(username);
if (!identity) {
console.log(
`An identity for the user ${username} does not exist in the wallet, so registering user`
);
await registerUser.registerEnrollUser(username, org_name);
identity = await wallet.get(username);
console.log("Run the registerUser.js application before retrying");
return;
}
const connectOptions = {
wallet,
identity: username,
discovery: { enabled: true, asLocalhost: true },
// eventHandlerOptions: EventStrategies.NONE
};
const gateway = new Gateway();
await gateway.connect(ccp, connectOptions);
const network = await gateway.getNetwork(channelName);
const contract = network.getContract(chaincodeName);
let result;
let message;
switch (fcn) {
case "availableStock":
result = await contract.submitTransaction(fcn);
result = { txid: result.toString() };
break;
default:
break;
}
await gateway.disconnect();
let response = {
message: message,
result,
};
return response;
} catch (error) {
console.log(`Getting error: ${error}`);
return error.message;
}
};
The above function is called using
app.get('/producer/storage', async(req,res,next)=>{
let message = await invoke.invokeTransaction("mfd-prd-channel", "pmcc", "availableStock", "", "user1 ", "teafarm");
res.json(message);
})
I have tried to recreate the crypto-config material using cryptogen.
Tried to recreate identities
Cross checked the network, channel names
Previous answer didn't solved the query https://stackoverflow.com/questions/71705611/channelmychannel-received-discovery-erroraccess-denied-failed-to-evaluate-tran

Ethereum Hardhat Testing Expect Not Catching Revert Reason

I'm using Hardhat framewrok and doing some testing with an erc20 contract:
it("testing with second", async () => {
const amount = ethers.utils.parseEther("1");
await expect(
ERC20Contract.connect(second).transferFrom(
ERC20Contract.address,
second,
amount
)
).to.be.revertedWith("ERC20: insufficient allowance");
});
I'm expecting the contract to revert with an error of : ERC20: insufficient allowance, and this is the error I'm getting:
Error: cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ] (error={"name":"ProviderError","_stack":"ProviderError: HttpProviderError\n at HttpProvider.request (/home/kadiemq/hh-tut/erc20-tut/node_modules/hardhat/src/internal/core/providers/http.ts:78:19)\n at LocalAccountsProvider.request (/home/kadiemq/hh-tut/erc20-tut/node_modules/hardhat/src/internal/core/providers/accounts.ts:187:34)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async EthersProviderWrapper.send (/home/kadiemq/hh-tut/erc20-tut/node_modules/#nomiclabs/hardhat-ethers/src/internal/ethers-provider-wrapper.ts:13:20)","code":-32000,"_isProviderError":true,"data":{"stack":"RuntimeError: VM Exception while processing transaction: revert ERC20: insufficient allowance\n at Function.RuntimeError.fromResults (/tmp/.mount_ganachAQrIFW/resources/static/node/node_modules/ganache-core/lib/utils/runtimeerror.js:94:13)\n at module.exports (/tmp/.mount_ganachAQrIFW/resources/static/node/node_modules/ganache-core/lib/utils/gas/guestimation.js:142:32)","name":"RuntimeError"}}, tx={"data":"0x23b872dd000000000000000000000000624daf7e06c04e0ab541323b3d3e95b629745a6000000000000000000000000033757dfeda24de8dc2b46d348a035ad60bbc3a3f0000000000000000000000000000000000000000000000000de0b6b3a7640000","to":{},"from":"0x2c93fc47DC6aaF30CD5a6C47F59bD898842B0190","gasPrice":{"type":"BigNumber","hex":"0x04a817c800"},"type":0,"nonce":{},"gasLimit":{},"chainId":{}}, code=UNPREDICTABLE_GAS_LIMIT, version=abstract-signer/5.7.0)
in the error message I can see ERC20: insufficient allowance but the expect function is not getting it and failing the test.
Here is the contract:
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
contract OurToken is ERC20 {
constructor(uint256 initialSupply) ERC20("OurToken", "OT") {
_mint(address(this), initialSupply);
_approve(address(this), msg.sender, initialSupply);
}
}
Deploy:
import { DeployFunction } from "hardhat-deploy/dist/types";
import { HardhatRuntimeEnvironment } from "hardhat/types";
import {
developmentChains,
INITIAL_SUPPLY,
networkConfig,
} from "../helper-hardhat-config";
const DeployToken: DeployFunction = async (hre: HardhatRuntimeEnvironment) => {
const { getNamedAccounts, deployments, network } = hre;
const { deploy, log } = deployments;
const { deployer } = await getNamedAccounts();
const chainId = network.config.chainId!;
const args = [INITIAL_SUPPLY];
const OurToken = await deploy("OurToken", {
from: deployer,
args: args,
log: true,
waitConfirmations: networkConfig[network.name].blockConfirmations || 1,
});
};
export default DeployToken;
DeployToken.tags = ["all", "token"];
Test:
import { deployments, ethers, getNamedAccounts } from "hardhat";
import { ERC20 } from "../typechain-types";
import { assert, expect } from "chai";
describe("Testing", async () => {
let deployer: string;
let second: string;
let ERC20Contract: ERC20;
beforeEach(async () => {
deployer = (await getNamedAccounts()).deployer;
second = (await getNamedAccounts()).second;
await deployments.fixture(["all"]);
});
it("testing with deployer", async () => {
ERC20Contract = await ethers.getContract("OurToken", deployer);
const amount = ethers.utils.parseEther("1");
const previousBalance = await ERC20Contract.balanceOf(deployer);
const tx = await ERC20Contract.transferFrom(
ERC20Contract.address,
deployer,
amount
);
tx.wait(1);
const newBalance = await ERC20Contract.balanceOf(deployer);
assert.equal(
previousBalance.add(amount).toString(),
newBalance.toString()
);
});
it("testing with second", async () => {
ERC20Contract = ERC20Contract.connect(second);
const amount = ethers.utils.parseEther("1");
await expect(
ERC20Contract.transferFrom(ERC20Contract.address, deployer, amount)
).to.be.revertedWith("ERC20: insufficient allowance");
});
});
So after almost a day of debugging it turns out that I need another plugin to use revertedWith() I need to install npm install --save-dev #nomiclabs/hardhat-waffle 'ethereum-waffle#^3.0.0' #nomiclabs/hardhat-ethers 'ethers#^5.0.0' and import it in the config file, otherwise I need to use rejectedWith("ERC20: insufficient allowance").
if anyone can explain this further it would be better because still I don't whats the difference between revertedWith and rejectedWith and why we need to install hardhat-waffle to be able to use revertedWith.
more info about hardhat-waffle in this page: https://hardhat.org/hardhat-runner/plugins/nomiclabs-hardhat-waffle

Error: Expected private key to be an Uint8Array with length 32

Following the guide from https://ethereum.org/vi/developers/tutorials/hello-world-smart-contract/
I am getting this error when trying to run my deploy script. I am absolutely lost as to why this is not working as I have copied every piece of code directly from the guide.
My hardhat.config.js
require('dotenv').config();
require("#nomiclabs/hardhat-ethers");
const { API_URL, PRIVATE_KEY } = process.env;
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.7.3",
defaultNetwork: "ropsten",
networks: {
hardhat: {},
ropsten: {
url: API_URL,
accounts: [`0x${PRIVATE_KEY}`]
}
},
}
My deploy.js
async function main() {
const HelloWorld = await ethers.getContractFactory("HelloWorld");
// Start deployment, returning a promise that resolves to a contract object
const hello_world = await HelloWorld.deploy("Hello World!");
console.log("Contract deployed to address:", hello_world.address);}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
my .env
API_URL = "https://eth-ropsten.alchemyapi.io/v2/[REDACTED]"
PRIVATE_KEY = "[REDACTED]". // my private key goes here, not including the 0x
It compiles fine but gives me the error when I use the command
npx hardhat run scripts/deploy.js --network ropsten
You don't need the 0x in the private key, just put the exact key you got from metamask :)
https://github.com/ethereumjs/ethereumjs-tx
As per usage example we need to add chain name while creating Transaction.
const tx = new Tx(txObject , { chain: 'rinkeby' })

AWS Cognito client SDK v3 returns 'byteLength' of undefined when running Admin disable user command

I am trying to disable users from my node JS backend using the AWS SDK v3. everything works normally except for the disable/enable user command.
I have tried everything I know but here is my code snippet:
const aws_creds = {
accessKeyId: process.env.ACCESS_KEY_ID,
secretAccessKey: process.env.SECRET_ACCESS_KEY,
};
const cognitoConfig = {
region: process.env.REGION,
credentials: aws_creds,
};
const cognito_v3 = new CognitoIdentityProviderClient(cognitoConfig);
Then in my route I am running this try / catch block
try {
if (status === "enable") {
const enableUserCommand = new AdminEnableUserCommand(userDetails);
const enableUserResults = await cognito_v3.send(enableUserCommand);
return res.status(200).json(enableUserResults);
}
const disableUserCommand = new AdminDisableUserCommand(userDetails);
const disableUserResults = await cognito_v3.send(disableUserCommand);
return res.status(200).json(disableUserResults);
} catch (err) {
console.log(err);
return res.status(400).json(err);
}
However, the err console log returns this:
TypeError: Cannot read property 'byteLength' of undefined
at Object.fromArrayBuffer (C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\node_modules\#aws-sdk\util-buffer-from\dist\cjs\index.js:6:60)
at castSourceData (C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\node_modules\#aws-sdk\hash-node\dist\cjs\index.js:29:31)
at Hash.update (C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\node_modules\#aws-sdk\hash-node\dist\cjs\index.js:12:26)
at hmac (C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\node_modules\#aws-sdk\signature-v4\dist\cjs\credentialDerivation.js:60:10)
at Object.getSigningKey (C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\node_modules\#aws-sdk\signature-v4\dist\cjs\credentialDerivation.js:32:29)
at SignatureV4.getSigningKey (C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\node_modules\#aws-sdk\signature-v4\dist\cjs\SignatureV4.js:139:39)
at SignatureV4.signRequest (C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\node_modules\#aws-sdk\signature-v4\dist\cjs\SignatureV4.js:98:73)
at async C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\node_modules\#aws-sdk\middleware-signing\dist\cjs\middleware.js:14:22
at async StandardRetryStrategy.retry (C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\node_modules\#aws-sdk\middleware-retry\dist\cjs\defaultStrategy.js:56:46)
at async C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\node_modules\#aws-sdk\middleware-logger\dist\cjs\loggerMiddleware.js:6:22
at async C:\Users\SER-01\Documents\ctr\simsim\simsim-backend\lambdas\simsim-auth\src\routes\auth.js:232:33 {
'$metadata': { attempts: 1, totalRetryDelay: 0 }
}
Any idea why?