ReferenceError: halalMeatInstance is not defined - solidity

I was doing a test in truffle. But i encountered this error, "ReferenceError: halalMeatInstance is not defined". I am pretty new in this truffle test thingy, actually this is my first time playing around with smart contracts and truffle test realm. It will be really helpful if anyone can point me out the mistake i made and give a solution. Thank you so much! the test file code is added below.
const { expectedEvent, BN } = require("#openzeppelin/test-helpers");
const HDWalletProvider = require("#truffle/hdwallet-provider");
const Web3 = require("Web3");
const HalalMeat = artifacts.require("HalalMeat");
contract("HalalMeat", (accounts) => {
before(async () => {
this.owner = accounts[0];
this.MEAT_BRANDS = {
GHagro: "Golden Harvest Agro Industries",
Kazifood: "Kazi Food Industries",
AGagro: "Ahsan Group Agro Foods",
Bengalmeat: "Bengal Meat ltd",
Sagro: "Sadek Agro ltd"
};
//enums
this.ModeEnums = {
ISSUER: { val: "ISSUER", pos: 0 },
VERIFIER: { val: "VERIFIER", pos: 1 },
PROVER: { val: "PROVER", pos: 2 }
};
this.StatusEnums = {
//MANUFACTURED, DELIVERING_INTERNATIONAL, STORED, DELIVERING_LOCAL, DELIVERED
manufactured: { val: "IMANUFACTURED", pos: 0 },
delivering1: { val: "DELIVERING_INTERNATIONAL", pos: 1 },
stored: { val: "STORED", pos: 2 },
delivering2: { val: "DELIVERING_LOCAL", pos: 3 },
delivered: { val: "DELIVERED", pos: 4 }
};
this.defaultEntities = {
farmA: { id: accounts[1], mode: this.ModeEnums.PROVER.val },
farmB: { id: accounts[2], mode: this.ModeEnums.PROVER.val },
inspector: { id: accounts[3], mode: this.ModeEnums.ISSUER.val },
distributorGlobal: { id: accounts[4], mode: this.ModeEnums.VERIFIER.val },
distributorLocal: { id: accounts[5], mode: this.ModeEnums.VERIFIER.val },
seller: { id: accounts[6], mode: this.ModeEnums.ISSUER.val },
customer: { id: accounts[7], mode: this.ModeEnums.PROVER.val }
};
this.defaultMeatBatches ={
0: { brand: this.MEAT_BRANDS.Bengalmeat, farm: this.defaultEntities.farmA.id },
1: { brand: this.MEAT_BRANDS.Sagro, farm: this.defaultEntities.farmA.id },
2: { brand: this.MEAT_BRANDS.Kazifood, farm: this.defaultEntities.farmA.id },
3: { brand: this.MEAT_BRANDS.GHagro, farm: this.defaultEntities.farmA.id },
4: { brand: this.MEAT_BRANDS.AGagro, farm: this.defaultEntities.farmA.id },
5: { brand: this.MEAT_BRANDS.Bengalmeat, farm: this.defaultEntities.farmB.id },
6: { brand: this.MEAT_BRANDS.Sagro, farm: this.defaultEntities.farmB.id },
7: { brand: this.MEAT_BRANDS.Kazifood, farm: this.defaultEntities.farmB.id },
8: { brand: this.MEAT_BRANDS.GHagro, farm: this.defaultEntities.farmB.id },
9: { brand: this.MEAT_BRANDS.AGagro, farm: this.defaultEntities.farmB.id }
};
this.halalMeatInstance = await HalalMeat.deployed();
this.providerOrUrl = "http://localhost:8545";
});
it('should add entities successfully', async () => {
for(const entity in this.defaultEntities){
const { id, mode } = this.defaultEntities[entity];
const result = await halalMeatInstance.addEntity(
id,
mode,
{ from: this.owner}
);
console.log(result);
expectedEvent(result.receipt, "AddEntity", {
entityId: id,
entityMode: mode
});
//assert.equal(actual, expected, errorMessage);
}
});
});
i tried truffle test. got reference error but was expecting an emit event.
Contract: HalalMeaton list from solc-bin. Attempt #1
1) should add entities successfullybin. Attempt #1
> No events were emitted
0 passing (99ms)
1 failing
Contract: HalalMeat
should add entities successfully:
ReferenceError: halalMeatInstance is not defined
at Context. (test\halalmeat.js:74:22)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
this is the error message i got when i used truffle test

Related

EIP712: ecrecover returns different address

I am trying to sign typed data via MetaMask "eth_signTypedData_v4". Recovering signer via recoverTypedSignature_v4 returns correct address that I signed my data with. But smart contract returns wrong address every time as ecrecover output. Can't understand what is wrong with the code.
js:
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();// 签名
const signerAddress = (await signer.getAddress()).toLowerCase();
const originalMessage = {
types: {
EIP712Domain: [
{ name: "name", type: "string" },
{ name: "version", type: "string" },
{ name: "chainId", type: "uint256" },
{ name: "verifyingContract", type: "address" }
],
Greeting: [
{ name: 'contents', type: 'string' },
{ name: "sender", type: "address" },
{ name: "x", type: "uint256" }
],
},
primaryType: 'Greeting',
domain: {
name: 'SignatureVerifyTest',
version: '1',
chainId: 31337,
verifyingContract: "0x5fbdb2315678afecb367f032d93f642f64180aa3"
},
message: {
contents: 'Hello',
sender: signerAddress,
x: 123
}
};
const signedMessage = await signer.provider.send("eth_signTypedData_v4", [signerAddress, JSON.stringify(originalMessage)]);
const { v, r, s } = ethers.utils.splitSignature(signedMessage);
console.log('signerAddress:', signerAddress)
console.log("r:", r);
console.log("s:", s);
console.log("v:", v);
bytes32 eip712DomainHash = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("SignatureVerifyTest")),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
bytes32 hashStruct = keccak256(
abi.encode(keccak256("Greeting(string contents,address sender,uint256 x)"), contents, sender, x)
);
bytes32 hash = ECDSA.toTypedDataHash(eip712DomainHash, hashStruct);
address signer = ECDSA.recover(hash, v, r, s);
console.log("sender", sender);
console.log("signer", signer);

Fuzzy search using mongoose from vue client

Getting error unknown top level operator $regex
search.vue `
let questDocuments = await conversation
.find({ query: { $limit: 100, $search: q, skippop: true } })
.then(response => {`
q is the string being passed
service hook
before: {
all: [],
find: [
hookBeforeFind,
search({
fields: ["label"],
deep: true
})
],
Model
const conversation = new Schema(
{
label: { type: String, required: true },
nodeId: { type: String, required: true },
details: { type: String },
url: { type: String },
creator: { type: String },
handle: { type: String },
date: { type: String },
From search bar add expression to search. E.g "the"
Add $regex to the whitelist option of the Mongoose service:
app.use('/messages', service({
Model,
whitelist: [ '$regex' ]
}));
try this
// regex to find records that start with letter any name , example "e"
Model.aggregate([
{
$match: {
field_name: {
$regex: "^" + searchName,
$options: "i"
}
}
}]).exec(function(err, result) {
if (err) { // handle here }
if (result) { // do something }
}

How to declare Vuex gettres return data in a map function

I have declared state and getters in my vuex where I want to get new price and title of the existing products in state.
When I have declared the return data in the getters It is throwing a syntax error and which is ; expected , given.
But from my point of view it is correct so what is the exact error?
state: {
value1: 1,
products: [
{ title: 'Hp1', price: 500 },
{ title: 'Hp2', price: 600 },
{ title: 'Hp3', price: 700 },
]
},
getters: {
saleProducts: state => {
var newProductsList = state.products.map(product => {
return
{
title: '** '+ product.title +' **',
price: product.price/2 + " % Off"
}
});
return newProductsList;
}
}
This is a bit bizzarre. When I copied and pasted your code then it doesn't work. When I type it in by hand myself from your example, then it works. Usually this sort of thing means that you've got an invalid ASCII character in the mix somewhere. The main thing I changed was to using double quotes instead of single quotes:
state: {
value1: 1,
products: [
{ title: 'Hp1', price: 500 },
{ title: 'Hp2', price: 600 },
{ title: 'Hp3', price: 700 },
]
},
getters: {
saleProducts: state => {
var newProductsList = state.products.map(product => {
return {
title: "** " + product.title + " **",
price: product.price/2 + " % Off"
}
})
}
},
See if you can spot the difference. Here's the codesandbox.io link: https://codesandbox.io/s/ywr1v7my19
Browse to /store/modules/main.js to see it in situ.

Mongodb: get count of multiple values in a field grouped by another field

I have a collection as below
{"country":"US","city":"NY"}
{"country":"US","city":"AL"}
{"country":"US","city":"MA"}
{"country":"US","city":"NY"}
{"country":"US","city":"MA"}
{"country":"IN","city":"DL"}
{"country":"IN","city":"KA"}
{"country":"IN","city":"DL"}
{"country":"IN","city":"DL"}
{"country":"IN","city":"KA"}
and expecting an output
{ "data": { "US": {"NY": 2,"AL": 1,"MA": 2 },
"IN": {"DL": 3,"KA": 2 }}
}
Below is the mongodb query I tried, i was able to get to get the count at country level, but not at the state level. please help me in correcting the below query to get data at state level.
db.country_dash.aggregate([
{"$group": {
"_id":"$country",
"state": {"$addToSet": "$state"}
}},
{"$project": {
"_id":0,
"country":"$_id",
"state": {"$size": "$state"}
} }
])
db.country_dash.aggregate(
// Pipeline
[
// Stage 1
{
$group: {
_id: {
city: '$city'
},
total: {
$sum: 1
},
country: {
$addToSet: '$country'
}
}
},
// Stage 2
{
$project: {
total: 1,
country: {
$arrayElemAt: ['$country', 0]
},
city: '$_id.city',
_id: 0
}
},
// Stage 3
{
$group: {
_id: '$country',
data: {
$addToSet: {
city: '$city',
total: '$total'
}
}
}
},
]
);

Mongodb query optimization for where clause

I am using MongoDB version 3.2.8. I am executing db.Member.find({$where: "var d = new Date(this.Birthdate); return d.getUTCDate() === 4 && d.getUTCMonth() === 2 && d.getUTCFullYear() !== 2017" }) It is taking too much time to execute this query on my local mongo. Is there any alternative for this query so query can optimize?
You can try using the MongoDB Aggregation Framework. I tested using the Mingo library for Javascript
Example:
var mingo = require('mingo')
var data = [{
_id: 100,
Birthdate: new Date("1995-02-04")
}]
var pipeline = [
{
$project: { M: { $month: "$Birthdate"}, Y: { $year: "$Birthdate"}, D: { $dayOfMonth: "$Birthdate"}, Birthdate: 1 }
},
{
$match: { $and: [ { D: 4 }, { M: 2 }, {Y: { $ne: 2017 } } ] }
},
{
$project: { M: 0, D: 0, Y: 0 }
}
]
var result = mingo.aggregate(data, pipeline)
console.log(result)
// Output
// [ { Birthdate: 1995-02-04T00:00:00.000Z, _id: 100 } ]
For MongoDB:
db.Member.aggregate(pipeline)