I export JSON interface from compile.js file but deploy.js file not work
it shows error as
RuntimeError: abort(Error: You must provide the JSON interface of the contract when instantiating a contract object.). Build with -s ASSERTIONS=1 for more info.
here is compile.js
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const lotteryPath = path.resolve(__dirname, 'contracts', 'lottery.sol');
const source = fs.readFileSync(lotteryPath, 'utf-8');
//console.log(solc.compile(source,1));
var input = JSON.stringify({
language: 'Solidity',
sources: {
'lottery.sol': {
content: source
}
},
settings: {
outputSelection: {
// Enable the metadata and bytecode outputs of every single contract.
"*": {
"*": ["metadata", "evm.bytecode"]
},
// Enable the abi and opcodes output of MyContract defined in file def.
"def": {
"Lottery": ["abi"]
},
}
}
})
const output = JSON.parse(solc.compile(input));
const interface = output.contracts['lottery.sol'].Lottery.abi;
const bytecode = output.contracts['lottery.sol'].Lottery.evm.bytecode.object;
module.exports = {
interface,
bytecode,
};
after that export this to deploy.js file
const HDwalletProvider = require("truffle-hdwallet-provider");
const Web3 = require("web3");
const {interface,bytecode}= require('./compile.js');
const provider = new HDwalletProvider(
'',
'https://ropsten.infura.io/v3/9ba5113757f648aaaab4d53e65898119'
);
const web3 = new Web3(provider);
const deploy = async()=>{
const accounts = await web3.eth.getAccounts();
console.log(accounts);
console.log("contract is deployed by manager with address",accounts[0]);
const result = await new web3.eth.Contract(interface)
.deploy({data : '0x'+bytecode})
.send({gas : '2000000' , from : accounts[0]});
console.log('contract deployed to address ', result.options.address);
}
deploy();
finally, show error
JSON interface error
Please help me,I am just a beginner at web3.js.I follow old tutorial to know the workflow
But it does not match with updated versions
here is depend
"dependencies": {
"next": "^11.1.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"solc": "^0.8.6",
"truffle-hdwallet-provider": "^1.0.17",
"web3": "^1.5.2"
}
I need someone help to get deployed address to set here
lottery.js file
import web3 from './web3.js';
const address = '';
const abi = [{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"enterLottery","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"participants","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pickWinner","outputs":[],"stateMutability":"nonpayable","type":"function"}];
export default new web3.eth.Contract(abi,address);
in compile.js
var output = JSON.parse(solc.compile(JSON.stringify(input))); // an object
// it spits out bytecode and interface
module.exports = output.contracts["Lottery.sol"]["Lottery"];
in deploy.js
const { abi, evm } = require("./compile");
compile.js
const path = require("path");
const fs = require("fs");
const solc = require("solc");
const inboxPath = path.resolve(__dirname, "contracts", "Example.sol");
const source = fs.readFileSync(inboxPath, "utf8");
const input = {
language: "Solidity",
sources: {
"Example.sol": {
content: source,
},
},
settings: {
outputSelection: {
"*": {
"*": ["*"],
},
},
},
};
const output = JSON.parse(solc.compile(JSON.stringify(input)));
module.exports = output.contracts["Example.sol"]["Example"];
here is my mocha test file example.test.js:
const assert = require("assert");
const ganache = require("ganache-cli");
const Web3 = require("web3");
const web3 = new Web3(ganache.provider());
const { abi, evm } = require("../compile");
let accounts;
let exampleContract;
beforeEach(async () => {
// Get a list of all accounts
accounts = await web3.eth.getAccounts();
// Use one of those accounts to deploy the contract
exampleContract = await new web3.eth
.Contract(abi)
.deploy({
data: evm.bytecode.object,
arguments: ["Hi there"],
})
.send({ from: accounts[0], gas: 1000000 });
});
describe("Example", () => {
it("deploys a contract", () => {
console.log(exampleContract);
});
});
Related
it might be a stupid question but since I'm a beginner I sadly don't understand most of how javascript works yet.
I'm trying to create a small Discord bot for a project that I'm working on and I would like to make it so you can select an option from a dropdown menu and whatever you select it sends a different embedded message in the channel. But whatever I do it doesn't send the embedded message. I've looked up multiple tutorials, but it seems like I'm missing something. Maybe someone can direct me in the right direction.
It is sending the dropdown menu, but sending error "InteractionAlreadyReplied". And whenever I try to select an option it won't send the embedded messages.
Here is my code so you can see the approach I'm using. I've tried using "MessageActionRow" and "MessageSelectMenu", but it seems like they don't work anymore. After inserting "ActionRowBuilder" and "StringSelectMenuBuilder" I got the menu working, but as said I don't get the embedded messages as an option. (didn't include the .env file since its only the token in there) I'm just not sure how I can make it so it connects the values from the dropdown menu to the right embeds.
CommandFile:
const { Discord, MessageActionRow, MessageSelectMenu,
SlashCommandBuilder, EmbedBuilder, roleMention, ButtonBuilder,
StringSelectMenuBuilder, StringSelectMenuOptionBuilder, ActionRowBuilder } = require('discord.js');
const { MessageEmbed } = require("discord.js")
module.exports = {
data: new SlashCommandBuilder()
.setName('dropdown')
.setDescription('Returns a select dropdown!'),
async execute(interaction, client, message, args) {
const row = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId("select")
.setPlaceholder("Wähle etwas aus:")
.addOptions([
{
label: "Auswahl 1",
description: "Beschreibung Auswahl 1",
value: "first"
},
{
label: "Auswahl 2",
description: "Beschreibung Auswahl 2",
value: "second"
},
{
label: "Auswahl 3",
description: "Beschreibung Auswahl 3",
value: "third"
},
])
)
let embed = new EmbedBuilder()
.setTitle("Embed Startseite")
.setDescription("Ab hier kann man selecten, was man möchte")
.setColor(0x18e1ee)
let sendmsg = await interaction.reply({ content:
"ㅤ", ephemeral:true, embeds: [embed], components: [row] })
let embed1 = new EmbedBuilder()
.setTitle("Embed 1")
.setDescription("Embed 1 Beschreibung")
.setColor(0x18e1ee)
let embed2 = new EmbedBuilder()
.setTitle("Embed 2")
.setDescription("Embed 2 Beschreibung")
.setColor(0x18e1ee)
let embed3 = new EmbedBuilder()
.setTitle("Embed 3")
.setDescription("Embed 3 Beschreibung")
.setColor(0x18e1ee)
const collector = message.createMessageComponentCollector({
componentType: "StringSelectMenuBuilder"
})
collector.on("collect", async (collected) => {
const value = collected.values[0]
if(value === "first") {
collected.reply({ embeds: [embed1], ephemeral:true })
}
if(value === "second") {
collected.reply({ embeds: [embed2], ephemeral:true })
}
if(value === "third") {
collected.reply({ embeds: [embed3], ephemeral:true })
}
})
}
}
bot.js:
require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits, ChannelSelectMenuInteraction } = require("discord.js");
const fs = require("fs");
const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.buttons = new Collection();
client.selectMenus = new Collection();
client.commandArray = [];
const functionFolders = fs.readdirSync(`./src/functions`);
for (const folder of functionFolders) {
const functionFiles = fs
.readdirSync(`./src/functions/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of functionFiles)
require(`./functions/${folder}/${file}`)(client);
}
client.handleEvents();
client.handleCommands();
client.handleComponents();
client.login(token);
HandleComponents.js :
const { readdirSync } = require('fs');
module.exports = (client) => {
client.handleComponents = async () => {
const componentFolders = readdirSync(`./src/components`);
for (const folder of componentFolders) {
const componentFiles = readdirSync(`./src/components/${folder}`).filter(
(file) => file.endsWith('.js')
);
const { buttons, selectMenus } = client;
switch (folder) {
case "buttons":
for (const file of componentFiles) {
const button = require(`../../components/${folder}/${file}`);
buttons.set(button.data.name, button);
}
break;
case "selectMenus":
for (const file of componentFiles) {
const menu = require(`../../components/${folder}/${file}`);
selectMenus.set(menu.data.name, menu);
}
break;
default:
break;
}
}
};
};
HandleCommands.js :
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const fs = require("fs");
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync("./src/commands");
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./src/commands/${folder}`)
.filter(file => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`../../commands/${folder}/${file}`);
commands.set(command.data.name, command);
commandArray.push(command.data.toJSON());
}
}
const clientId = "IDbutCensored";
const guildId = "IDbutCensored";
const rest = new REST({ version: '9' }).setToken(process.env.token);
try {
console.log("Started refreshing application (/) commands.");
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: client.commandArray,
});
console.log("Successfully reloaded application (/) commands.");
} catch (error) {
console.error(error);
}
};
};
handleEvents.js :
const fs = require("fs");
module.exports = (client) => {
client.handleEvents = async () => {
const eventFolders = fs.readdirSync(`./src/events`);
for (const folder of eventFolders) {
const eventFiles = fs
.readdirSync(`./src/events/${folder}`)
.filter((file) => file.endsWith(".js"));
switch (folder) {
case "client":
for (const file of eventFiles) {
const event = require(`../../events/${folder}/${file}`);
if (event.once) client.once(event.name, (...args) => event.execute(...args, client));
else client.on(event.name, (...args) => event.execute(...args, client));
}
break;
default:
break;
}
}
}
}
The error is pretty self explanatory. The error InteractionAlreadyReplied means you already replied and you're trying to reply again.
You can solve this by doing the following;
• Use .followUp() to send a new message
• If you deferred reply it's better to use .editReply()
• Information about responding to slash commands / buttons / select menus
From the Discord docs
Im using discord js to make a multi-purpose discord bot for my server, but its giving me this error:
ValidationError: Expected a string primitive
It was working fine yesterday but i forgot to save something and i dont know what.
const fs = require('node:fs');
const path = require('node:path');
const {
Client,
GatewayIntentBits,
Partials,
Collection,
} = require("discord.js");
const { Player } = require('discord-player');
const { Routes } = require('discord-api-types/v10');
const { token, prefix, guildId, clientId } = require('./config.json');
const { REST } = require('#discordjs/rest');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildVoiceStates
],
partials: [
Partials.Channel,
Partials.Message,
Partials.User,
Partials.GuildMember,
],
});
client.player = new Player(client, {
ytdlOptions: {
quality: "highestaudio",
highWaterMark: 1 << 25
}
});
module.exports = client;
// command handler
//slash commands
const slashCommands = [];
client.slashCommands = new Collection();
const commandsPath = path.join(__dirname, "commands"); // E:\yt\discord bot\js\intro\commands
const slash_commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('S.js'));
for(const file of slash_commandFiles)
{
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.slashCommands.set(command.data.name, command);
slashCommands.push(command.toJSON());
}
console.log(slashCommands);
//message commands
client.messageCommands = new Collection();
const message_commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('M.js'));
for (const file of message_commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.messageCommands.set(command.Name, command);
}
//event handler
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
// messageCommand handler
client.on('messageCreate', (message) => {
const args = message.content.slice(prefix.length).split(' ');
const command = args[0];
if (client.messageCommands.get(command)) {
let Command = client.messageCommands.get(command);
Command.execute(message);
}
});
client.on('ready', () => {
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId),
{ body: slashCommands })
.then(() => console.log('Successfully updated commands for guild ' + guildId))
.catch(console.error);
console.log('bot is online!');
client.user.setStatus('idle');
});
client.login(token);
im sure there's nothing wrong with any of the command files because it was working fine yesterday.
there's 100% an error in this line slashCommands.push(command.toJSON()); but I cant seem to fix it. The command.toJSON() console logs just fine but gives an error while trying to push into the list
Ran into the same issue, turns out options (i.e. addUserOption) require a description. Point is it's really confusing as this error shows up when doing command.data.toJSON(). If you are dynamically loading the command files as described in the guide and running into this issue, then try manually doing a require to trigger the validation beforehand.
Try using command.data.toJSON() as command is a nested object with a data and an execute key.
I've fixed it, there was a url in the json which seemed to be causing some issue, I removed the file with the url and its working now
Can someone please help me figure out when javascript cannot seem to find the getSignedUrl() . I am attempt to recreate my own version of generateThumbnail (https://github.com/firebase/functions-samples/blob/main/generate-thumbnail/functions/index.js) and storage-resize-images (https://github.com/firebase/extensions/blob/master/storage-resize-images/functions/lib/index.js) for some reason it cannot find the function even though imported the correct library.
Here is the error I am receiving:
Error when resizing image TypeError:
updatedImage.getSignedUrl is not a function
at /workspace/index.js:121:22
at Array.forEach ()
at /workspace/index.js:120:17
at runMicrotasks ()
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Here is my code for reference:
const { Storage } = require("#google-cloud/storage");
const storage = new Storage({
keyFilename: "./cloud",
});
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
//const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');
const uuid = require('uuid');
const mkdirp = require("mkdirp");
const sharp = require("sharp");
const resize_image_1 = require("./resize-images");
const config_1 = require("./config");
const logs = require("./logs");
const util_1 = require("./util");
const {constants } = require("buffer");
// exports.helloWorld = functions.https.onRequest((request, response) => {
// functions.logger.info("Hello logs!", {structuredData: true});
// response.send("Hello from Firebase!");
// });
exports.generateThumbnail = functions.storage.object().onFinalize ( async (object) => {
logs.start();
const { contentType } = object; // This is the image MIME type
const tmpFilePath = path.resolve("/", path.dirname(object.name)); // Absolute path to dirname
const feedPath = '/uploads/groups/*/feed';
if (!contentType) {
logs.noContentType();
return;
}
if (!contentType.startsWith("image/")) {
logs.contentTypeInvalid(contentType);
return;
}
if (object.contentEncoding === "gzip") {
logs.gzipContentEncoding();
return;
}
if (config_1.paramToArray(feedPath) &&
!util_1.startsWithArray(feedPath, tmpFilePath)) {
logs.imageOutsideOfPaths(feedPath, tmpFilePath);
return;
}
if (object.metadata && object.metadata.resizedImage === "true") {
logs.imageAlreadyResized();
return;
}
const bucket = storage.storage().bucket(object.bucket);
const filePath = object.name; // File path in the bucket.
const fileDir = path.dirname(filePath);
console.log("File path :" +filePath);
const fileExtension = path.extname(filePath);
console.log("File extension :" +fileExtension);
const fileNameWithoutExtension = util_1.extractFileNameWithoutExtension(filePath, fileExtension);
const objectMetadata = object;
let originalFile;
let remoteFile;
try {
originalFile = path.join(os.tmpdir(), filePath);
const tempLocalDir = path.dirname(originalFile);
// Create the temp directory where the storage file will be downloaded.
logs.tempDirectoryCreating(tempLocalDir);
await mkdirp(tempLocalDir);
logs.tempDirectoryCreated(tempLocalDir);
// Download file from bucket.
remoteFile = bucket.file(filePath);
logs.imageDownloading(filePath);
await remoteFile.download({ destination: originalFile });
logs.imageDownloaded(filePath, originalFile);
// Get a unique list of image types
const imageTypes = new Set(['jpeg']);
// Convert to a set to remove any duplicate sizes
const imageSizes = new Set(['480x480','640x640','1024x1024']);
const tasks = [];
console.log("ileNameWithoutExtension : " +fileNameWithoutExtension);
console.log("fileExtension : " +fileExtension);
imageTypes.forEach((format) => {
imageSizes.forEach((size) => {
tasks.push(resize_image_1.modifyImage({
bucket,
originalFile,
fileDir,
fileNameWithoutExtension,
fileExtension,
contentType,
size,
objectMetadata: objectMetadata,
format,
}));
});
});
const results = await Promise.all(tasks);
const failed = results.some((result) => result.success === false);
logs.complete();
if (failed) {
logs.failed();
return;
}
if (originalFile) {
logs.tempOriginalFileDeleting(filePath);
fs.unlinkSync(originalFile);
logs.tempOriginalFileDeleted(filePath);
}
const config = {
action: 'read',
expires: '03-01-2500',
};
const resizedImages = await Promise.all(
results.forEach((updatedImage)=>{
updatedImage.getSignedUrl(config);
}));
console.log('Got Signed URLs.');
const postImage = resizedImages[0];
const feedCard = resizedImages[1];
const zoomImage = resizedImages[2];
const postImageUrl = postImage[0];
const feedCardUrl = feedCard[0];
const zoomImageUrl = zoomImage[0];
await admin.database().ref('feeds/{gId}/{post}').push({ postImage: postImageUrl, feedCard: feedCardUrl, zoomImage: zoomImageUrl});
return console.log('Thumbnail URLs saved to database.');
}
catch (err) {
logs.error(err);
}
// finally {
// }
});
in terminal (at project directory)
cd functions npm install #google-cloud/storage
package.json code
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "14"
},
"main": "index.js",
"dependencies": {
"#google-cloud/storage": "^5.8.5",
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.14.1",
"fs-extra": "^10.0.0",
"mkdirp": "^1.0.4",
"sharp": "^0.28.3",
" uuid": "^8.3.2",
"uuidv4": "^6.2.11"
},
"devDependencies": {
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
I modified the nested loops a bit and still can't getSignedUrl to be found.
imageTypes.forEach( async(format) => {
imageSizes.forEach((size) => {
tasks.push(resize_image_1.modifyImage({
bucket,
originalFile,
fileDir,
fileNameWithoutExtension,
fileExtension,
contentType,
size,
objectMetadata: objectMetadata,
format,
}));
});
const results = await Promise.all([
remoteFile.getSignedUrl({
action: 'read',
expires: '03-01-2500',
}),]);
const config = {
action: 'read',
expires: '03-01-2500',
};
const resizedImages = await Promise.all(
results.map((updatedImage) => updatedImage.getSignedUrl(config)));
const postImage = resizedImages[0];
const postImageUrl = postImage[0];
await admin.database().ref('feeds/{gId}/{post}').push({ postImage: postImageUrl,});
return console.log('Thumbnail URLs saved to database.');
});
I should also mention that the images do get resized and sent to storage.
I'm not sure what you mean by register but using a forEach loop inside of Promise.all() won't form an array. So the problem is here:
const resizedImages = await Promise.all(
results.forEach((updatedImage)=>{
updatedImage.getSignedUrl(config);
}));
Instead use the map method:
const resizedImages = await Promise.all(
results.map((updatedImage) => updatedImage.getSignedUrl(config))
);
Now the parameter in Promise.all() is an array.
const {ChainId, Fetcher, WETH, Route, Trade, TokenAmount, TradeType, Percent} = require ('#uniswap/sdk');
const ethers = require('ethers');
const chainId = ChainId.MAINNET;
how would I specify it to be the locally forked ganache chain?
tried this:
const Web3 = require('web3');
const web3 = new Web3(`http://localhost:8545`);
const tokenAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F';
const init = async ()=> {
const chainId = await web3.eth.getChainId();
...
following error is shown:
/Users/GreyShadow/node_modules/#ethersproject/logger/lib/index.js:179
var error = new Error(message);
^
Error: unsupported getDefaultProvider network (operation="getDefaultProvider", network={"chainId":1337,"name":"unknown"}, code=NETWORK_ERROR, version=providers/5.0.17)
Help is much appreciated
I'm doing a Discord bot with command handling, but on a file, I can't get the content of my JSON file out with lowdb... I proceed exactly the same way with success in the other files, I don't understand... Here is my code:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('../db.json')
const db = low(adapter)
const adapter2 = new FileSync('../users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;
module.exports = {
name: 'rent',
description: 'Rent a number',
usage: '<country>',
guildOnly: true,
async execute(message, args) {
return console.log(db.get().value())
...
Here's my db.json:
{
"numbers": [
{
"test": "1234"
}
]
}
When I console.log db alone, it takes me out the object, but as soon as I try to console.log with lowdb like above it takes me out undefined ....
So I'm not sure why, but you have to remove a point on the road to lowdb files.
Code not working:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('../db.json')
const db = low(adapter)
const adapter2 = new FileSync('../users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;
Code after modification and functional:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('./db.json')
const db = low(adapter)
const adapter2 = new FileSync('./users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;