VM Exception while processing transaction: revert error while testing createRequest method - reactjs

I am doing the following test from a udemy ethereum course.
I found VM Exception while processing transaction: revert error while testing the following method in Campaign.test.js file.
it('allows a manager to make a payment request', async () => {
const recipientAddress = accounts[1];
await campaign.methods
.createRequest('Buy batteries', '100', recipientAddress)
.send({
from: accounts[0],
gas: '1000000'
});
const request = await campaign.methods.requests(0).call();
console.log(request.description);
assert(true);
});
method in campaign.sol file is given below
function createRequest(string description, uint value, address recipient) public restricted {
Request memory newRequest = Request({
description: description,
value: value,
recipient: recipient,
complete: false,
approvalCount: 0
});
requests.push(newRequest);
}

Related

WalletConnect :- Rainbow always show MATIC when transfer other coins by WalletConnect sendTransaction in react native

I am developing react native mobile application where user can transfer their amount by external wallet (Rainbow, MetaMask).
I am using 'polygon-rpc' network for my users.
The thing is working as expected but when execute transfer method by my contract by WalletConnect sendTransaction(txObj) library it navigate me to connected wallet and prompted the confirmation pop, where it show the my currency in MetaMask, but in Rainbow it always show Matic instead of POZ.
However it works well in Metamask and show the POZ, instead of MATIC.
I am using this code to procced transaction by WalletConnect external wallet
let toAddress = pozPouchFundWallet; // end address to transfer amount
let decimals = BigNumber(18);
let amount1 = new BigNumber(amountValue);
let value = amount1.times(new BigNumber(10).pow(decimals));
let contract = new Web3js.eth.Contract(App_ABI, POZ_TOKEN!);
try {
let dataa = await contract.methods
.transfer(toAddress, value.toString())
.encodeABI();
let txObj = {
// gas: Web3js.utils.toHex(100000),
data: Web3js.utils.toHex(dataa),
from: userWallet,
to: POZ_TOKEN, // Contractor token address
};
try {
const transactionHash = await connector
.sendTransaction(txObj)
.catch((_err: any) => {
Toast.show({
autoHide: true,
text1: t('topUpPoz.transactionFailed'),
type: 'error',
});
});
console.log('transactionHash is =', transactionHash);
resolve(transactionHash);
} catch (error) {
console.log('the connector error is = ', error);
reject(error);
}
} catch (err) {
console.log('contact error is = ', err);
reject(err);
}

Cannot update or save data on second or next user in mongodb

May I know what is the problem with my code for the backend. I try to create a place and update it in the user database. The problem is If I only have 1 user. The database can create and update the data but if I have more than 2 then, the data cannot be updated or created. Here is my code. I have been working on this part for so long, that I cannot find the solution.
const createFile = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
new HttpError('Invalid inputs passed, please check your data.', 422)
);
}
const { userId, Dataset } = req.body;
const createdFile = new File({
userId,
Dataset,
});
let user;
try {
user = await User.findById(userId);
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again 1',
500
);
return next(error);
}
if (!user) {
const error = new HttpError('Could not find user for provided id', 404);
return next(error);
}
try {
const sess = await mongoose.startSession();
sess.startTransaction();
await createdFile.save({ session: sess });
user.Dataset.push(createdFile);
await user.save({ session: sess });
await sess.commitTransaction();
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again.2',
500
);
return next(error);
}
res.status(201).json({ files: createdFile });
};
The error message that I got
Error: User validation failed: _id: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at ValidationError.inspect (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\error\validation.js:48:26)
at internal/per_context/primordials.js:23:32
at formatValue (internal/util/inspect.js:783:19)
at inspect (internal/util/inspect.js:337:10)
at formatWithOptionsInternal (internal/util/inspect.js:2016:40)
at formatWithOptions (internal/util/inspect.js:1898:10)
at console.value (internal/console/constructor.js:323:14)
at console.log (internal/console/constructor.js:358:61)
at createFile (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\controllers\files-controller.js:102:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
errors: {
_id: ValidatorError: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at validate (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1321:13)
at C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1297:24
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
properties: [Object],
kind: 'unique',
path: '_id',
value: new ObjectId("62c661c629d1cb99768efd05"),
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}
It already settle, I reroll the mongoose-unique-validator to 2.0.3 version
I use this command
npm install mongoose-unique-validator#2.0.3 --legacy-peer-deps
hope that someone with same issues as mine find my post and can help them to solve the same issues

Error connect to Spring-boot-Rsocket (Auth JWT) from web-client RSocketWebSocketClient

The connection to server with spring-boot client works good:
public RSocketAdapter() throws IOException {
requester = createRSocketRequesterBuilder()
.connectWebSocket(URI.create("ws://localhost:7878/"))
.block();
}
private RSocketRequester.Builder createRSocketRequesterBuilder() {
RSocketStrategies strategies = RSocketStrategies.builder()
.encoders(encoders -> encoders.add(new Jackson2CborEncoder()))
.decoders(decoders -> decoders.add(new Jackson2CborDecoder()))
.dataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT))
.build();
return RSocketRequester.builder().rsocketStrategies(strategies);
}
public Mono<HelloToken> signIn(String principal, String credential) {
return requester
.route("signin.v1")
.data(HelloUser.builder().userId(principal).password(credential).build())
.retrieveMono(HelloToken.class)
.doOnNext(token -> {
accessToken = token.getAccessToken();
})
.onErrorStop();
}
And server receives such frame:
Correct byte frame
But the same request from web-client:
authSocketReactiv = () => {
const maxRSocketRequestN = 2147483647;
const keepAlive = 60000;
const lifetime = 180000;
const dataMimeType = 'application/json';
const metadataMimeType = 'message/x.rsocket.authentication.bearer.v0';
var client = new RSocketClient({
serializers: {
data: JsonSerializer,
metadata: JsonSerializer,
},
setup: {
dataMimeType,
keepAlive,
lifetime,
metadataMimeType
},
transport: new RSocketWebSocketClient({
url: 'ws://localhost:7878'
},Encoders)
});
// Open the connection
client.connect().subscribe({
onComplete: socket => {
socket.requestStream({
data:{
'user_id': '0000',
'password': 'Zero4'
},
metadata:'signin.v1'
}).subscribe({
onComplete: () => console.log('complete'),
onError: error => {
console.log(error);
},
onNext: payload => {
console.log('Subscribe1');
},
onSubscribe: subscription => {
console.log('Subscribe');
subscription.request(2147483647);
},
});
},
onError: error => {
console.log(error);
},
onSubscribe: cancel => {
}
});
Forms the incorrect frame and fall with “metadata is malformed ERROR” :
Error byte frame from web
What encoding or buffering options should be used here? Thanks for any tips and suggestions.
You are likely going to want to work with composite metadata and set your metadataMimeType to MESSAGE_RSOCKET_COMPOSITE_METADATA.string.
The important bit is going to be the routing metadata, which is what tells the server how to route the incoming RSocket request.
I haven't dug through the server example code you linked on StackOverflow, but just by looking at your example code, you would supply the routing metadata with your requestStream as so:
Also, the example project you listed though references signin as a request/response so you actually don't want requestStream, but requestResponse.
socket
.requestResponse({
data: Buffer.from(JSON.stringify({
user_id: '0000',
password: 'Zero4'
})),
metadata: encodeCompositeMetadata([
[MESSAGE_RSOCKET_ROUTING, encodeRoute("signin.v1")],
]),
})
You will likely want to use BufferEncoders, as shown in this example. And additionally, I believe you should not use JsonSerializer for the metadata, but instead IdentitySerializer, which will pass the composite metadata buffer straight through, rather than trying to serialize to and from JSON.
You may still run into some issues, but I suspect that this will get you past the metadata is malformed ERROR error.
Hope that helps.
Grate thanks for the detailed advices. According to directions, this complined solution works for my case:
getAuthToken = () => {
const maxRSocketRequestN = 2147483647;
const keepAlive = 60000;
const lifetime = 180000;
const dataMimeType = APPLICATION_JSON.string;
const metadataMimeType = MESSAGE_RSOCKET_COMPOSITE_METADATA.string;
var client = new RSocketClient({
serializers: {
data: IdentitySerializer,
metadata: IdentitySerializer,
},
setup: {
dataMimeType,
keepAlive,
lifetime,
metadataMimeType
},
transport: new RSocketWebSocketClient({
url: 'ws://localhost:7878'
},BufferEncoders)
});
client.connect().then(
(socket) => {
socket.requestResponse({
data: Buffer.from(JSON.stringify({
user_id: '0000',
password: 'Zero4'
})),
metadata: encodeCompositeMetadata([
[MESSAGE_RSOCKET_ROUTING, encodeRoute("signin.v1")],
]),
}).subscribe({
onComplete: (data) => console.log(data),
onError: error =>
console.error(`Request-stream error:${error.message}`),
});
},
(error) => {
console.log("composite initial connection failed");
}
);

Trying to add a warning system to my mongodb, it works but says application didn't respond

const {Client, CommandInteraction, MessageEmbed} = require("discord.js");
const db = require("../../Structures/Schemas/InfractionDB");
module.exports = {
name: "warnings",
description: "Give a warning",
permission: "ADMINISTRATOR",
options: [
{
name: "target",
description: "Select a target.",
type: "USER",
required: true
},
{
name: "reason",
description: "Provide a reason.",
type: "STRING",
required: true
},
{
name: "evidence",
description: "Provide evidence.",
type: "STRING",
required: false
},
],
/**
*
* #param {CommandInteraction} interaction
* #param {Client} client
*/
execute(interaction, client) {
const{guild, member, options} = interaction
const Target = options.getMember("target");
const Reason = options.getString("reason");
const Evidence = options.getString("evidence") || "None provided";
const Response = new MessageEmbed()
.setColor("RED")
.setAuthor({name: "MOD BOT", iconURL: guild.iconURL()});
db.findOne({GuildID: guild.id, UserID: Target.id}, async (err,data)=> {
if(err) throw err;
if(!data || !data.WarnData) {
data = new db({
GuildID: guild.id,
UserID: Target.id,
WarnData: [
{
ExecuterID: member.id,
ExecuterTag: member.user.tag,
TargetID: Target.id,
TargetTag: Target.user.tag,
Reason: Reason,
Evidence: Evidence,
Date: parseInt(interaction.createdTimestamp / 1000)
}
],
})
} else {
const WarnDataObject ={
ExecuterID: member.id,
ExecuterTag: member.user.tag,
TargetID: Target.id,
TargetTag: Target.user.tag,
Reason: Reason,
Evidence: Evidence,
Date: parseInt(interaction.createdTimestamp / 1000)
}
data.WarnData.push(WarnDataObject)
}
data.save()
});
Response.setDescription(`Warning Added: ${Target.user.tag} | ||${Target.id}||\n**Reason**: ${Reason}\n**Evidence**:${Evidence}`);
guild.channels.cache.get("946217387336818699").send({embeds:[Response]});
}}
originally this was routed to a different collection in my db. I've tried to convert it so I can see everything in one place. but it's taken me hours and don't seem to be getting anywhere. Like I said, the data is being stored on the db, but the Response is failing. Any ideas how to fix this? There are no errors in terminal
The error i think is that your application is taking too long to respond.
you have only 3 seconds to respose.
for this i would suggest that you execute you interaction as a async function
and you should use await before trying to find it in the database. because it can take some time to find the data in the database.
The data is store in database because it has no concern with the response time but the discord api wants a reply in 3 seconds or it will fail.
I have read your code. it seems okay.
i would suggest you to use the easier way instead of using the object or json form to create the commands.
SlashCommandBuilder from #discordjs/builders
its easy to use and simple.
here is an example of how easy it is if you use SlashCommandBuilder
const { SlashCommandBuilder } = require('#discordjs/builders');
const data = new SlashCommandBuilder()
.setName('gif')
.setDescription('Sends a random gif!')
.addStringOption(option =>
option.setName('category')
.setDescription('The gif category')
.setRequired(true)
.addChoice('Funny', 'gif_funny')
.addChoice('Meme', 'gif_meme')
.addChoice('Movie', 'gif_movie'));
you can install all the dependencies using
npm install discord.js #discordjs/rest discord-api-types

Where to put Discord JS Bot Presence code?

So I was trying to put code into my Discord bot to give it a custom status for users to see, then when I found the code I had no idea where to put it.
Here's the code: where should I put it?
* Sets the full presence of the client user.
* #param {PresenceData} data Data for the presence
* #returns {Promise<ClientUser>}
* #example
* // Set the client user's presence
* client.user.setPresence({ game: { name: 'with discord.js' }, status: 'idle' })
* .then(console.log)
* .catch(console.error);
*/
setPresence(data) {
return new Promise(resolve => {
let status = this.localPresence.status || this.presence.status;
let game = this.localPresence.game;
let afk = this.localPresence.afk || this.presence.afk;
if (!game && this.presence.game) {
game = {
name: this.presence.game.name,
type: this.presence.game.type,
url: this.presence.game.url,
};
}
This code above belongs to the ClientUser.js file. It might belong to other files like Presence.js
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
status: 'online',
activity: {
name: ".help",
type: "PLAYING"
}
});
});
The status can be online, idle, dnd, or invisible. (dnd is Do not disturb)
The other variable here is activity. It is a group of two variables: name and type.
The name is what the bot is doing. This is a string of your choice. The type is the other thing that will help it display as. It can be "PLAYING", "STREAMING", "WATCHING", "LISTENING", and "CUSTOM_STATUS".
You can put it anywhere but most likely you want to put it into your ready event like
client.on('ready', () => {
client.user.setPresence({ game: { name: 'with discord.js' }, status: 'idle' })
console.log(`${client.user.username} is up and running!`);
})

Resources