How to deploy a solana program from a particular address or public key - node.js

I've two problems here, major of all, I can't understand the difference between account address and public key of a program
The second thing is, there is a problem while deploying my solana program. I've made a deployment script...
const { Keypair } = require("#solana/web3.js");
const { Connection, LAMPORTS_PER_SOL } = require("#solana/web3.js");
const path = require('path');
const spawn = require("cross-spawn");
const fs = require('fs');
//import { Connection, LAMPORTS_PER_SOL } from "#solana/web3.js"
async function main(){
const SLASH = path.sep;
let programAuthorityKeypair = new Keypair();
this.connection = new Connection("https://api.devnet.solana.com", "confirmed");
const signature = await this.connection.requestAirdrop(programAuthorityKeypair.publicKey, LAMPORTS_PER_SOL * 5);
await this.connection.confirmTransaction(signature);
const programAuthorityKeyfileName = `target/deploy/programauthority-keypair.json`
const programAuthorityKeypairFile = path.resolve(
`${__dirname}${SLASH}${programAuthorityKeyfileName}`
);
fs.writeFileSync(
programAuthorityKeypairFile,
`[${Buffer.from(programAuthorityKeypair.secretKey.toString())}]`
);
const programKeyfileName = `target/deploy/solblog-keypair.json`
const programKeypairFile = path.resolve(
`${__dirname}${SLASH}${programKeyfileName}`
);
let programKeypair = readKeyfile(programKeypairFile);
let programId = programKeypair.publicKey.toString();
//////////////////////////////////configurations//////////////////////////////////
let method = ["deploy"] // we are deploying for the first time, using 'deploy'
spawn.sync(
"anchor",
[
...method, // we use a variable so we when we want to upgrade, we can use 'upgrade' instead
"--provider.cluster", // we want to specify the node cluster
"Devnet", // the node cluster as the Devnet
"--provider.wallet", // we need to pass in a keyfile to pay for the deployment
`${programAuthorityKeypairFile}`, // this is the keypair file we created just a moment ago
],
{ stdio: "inherit" }
)
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
function readKeyfile(keypairfile) {
let kf = fs.readFileSync(keypairfile)
let parsed = JSON.parse(kf.toString()) // [1,1,2,2,3,4]
kf = new Uint8Array(parsed)
const keypair = Keypair.fromSecretKey(kf)
return keypair
}
now, I'm running the script by node deploy.js but it is giving me balance insufficient error...
Deploying workspace: https://api.devnet.solana.com
Upgrade authority: /home/adil/Desktop/solblog/target/deploy/programauthority-keypair.json
Deploying program "solblog"...
Program path: /home/adil/Desktop/solblog/target/deploy/solblog.so...
===========================================================================
Recover the intermediate account's ephemeral keypair file with
`solana-keygen recover` and the following 12-word seed phrase:
===========================================================================
all orbit slim nothing learn country polar casual print help coffee gesture
===========================================================================
To resume a deploy, pass the recovered keypair as the
[BUFFER_SIGNER] to `solana program deploy` or `solana write-buffer'.
Or to recover the account's lamports, pass it as the
[BUFFER_ACCOUNT_ADDRESS] argument to `solana program close`.
===========================================================================
Error: Account JjetRg5FHM6xpPjTT7KfrEaTBeEWxMh5Pyjo4UXw3nm has insufficient funds for spend (1.8711612 SOL) + fee (0.00135 SOL)
There was a problem deploying: Output { status: ExitStatus(unix_wait_status(256)), stdout: "", stderr: "" }.
so I'm taking the above account address JjetRg5FHM6xpPjTT7KfrEaTBeEWxMh5Pyjo4UXw3nm to solana faucet site, and airdropping 5 SOLs into that address then again I'm running the script, AND GETTING THE SAME ERROR WITH DIFFERENT ACCOUNT like...
Error: Account .
already set the env to the DEVNET.
What I'm thinking that how can I deploy the program with the same account into which I'm airdropping SOLs?

Related

Slash command registers command from wrong folder discord.js14

I'm tired of trying to solve this. First off, here is my deployment code
const { REST, Routes } = require('discord.js');
const fs = require('node:fs');
const { client_id } = require('./config.json')
const commands = [];
// Grab all the command files from the commands directory you created earlier
const commandFiles = fs.readdirSync('./slashCommands').filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`./slashCommands/${file}`);
commands.push(command.data.toJSON());
}
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
// and deploy your commands!
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationCommands(client_id),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();
It is supposed to get the command from the "slashCommand" folder. So I run 'node deploy-commands.js' and it works.
The problem is when I do the slash command '/ping', I get this error:
/home/runner/Nocinel/commands/ping.js:8
message.reply('🏓 **Ball is going over the net...**').then(m => { m.edit(`**🏓 Pong!\n:stopwatch: Uptime: ${Math.round(message.client.uptime / 60000)} minutes\n:sparkling_heart: Websocket Heartbeat: ${message.client.ws.ping}ms\n:round_pushpin: Rountrip Latency: ${m.createdTimestamp - message.createdTimestamp}ms**`) });
^
TypeError: m.edit is not a function
at /home/runner/Nocinel/commands/ping.js:8:73
repl process died unexpectedly: exit status 1
Now this error indicates that I am running a command from my "command" folder rather than my "slashCommand" folder. Which doesnt make sense because I explicitly coded it to only get commands from the "slash command folder"
I have restarted, deleted, waited for an hour, and tested it multiple times, it always gives the same disappointing result. I see absolutely nothing wrong with my code.
There is no problem with registring comannd (deploy-comannds.js is only registring comannds not using making them work). Problem have to be in your index.js you have to handle interaction comannds to your folder slashComannds. Registring comannds was sucessfull.
Documentation:
https://discordjs.guide/creating-your-bot/command-handling.html#loading-command-files

Firebase Cloud Functions with TypeScript: Realtime Database update ends with success but not updates anything, JS works fine

I added Cloud Functions to Firebase project with Firebase CLI. I have started with JavaScript, managed to write working code.
Then I decided to switch to TypeScript. So I decided to delete all Cloud Functions JS related files and start with firebase init cmd from scratch. I copied code from index.js to index.ts, needed only to change how dataMap Map was declared.
So, now whenever I look into console logs on Firebase, everything seems to work fine, everything is logged out, and I'm getting success message on client side.
However nothing happens in Realtime Database, no update, no trace of any data.
I know almost nothing about JS / TS, so every suggestion about code and solution is welcomed.
I'm using node: 14.17.6 and updated firebase-tools to 9.18.0, firebase-admin to 9.11.1 and firebase-functions to 3.15.6.
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
exports.createItemWithVIP = functions.region("europe-west1").
https.onCall((data, context) => {
// Checking that the user is authenticated.
if (!context.auth) {
console.log("Unauthenticated request");
throw new functions.https.HttpsError("permission-denied", "You have" +
" no permission to perform this operation");
}
// item details
const foo = data.foo;
const bar = data.bar;
console.log(`foo: ${foo}, bar: ${bar}`);
const userUID = context.auth.uid;
console.log(`userUID: ${userUID}`);
const db = admin.database();
// get new item uid
const somePathTableReference = db.ref("somePath/").push();
const itemUID = `${somePathTableReference}`
.split("somePath/")[1];
console.log(`itemUID: ${itemUID}`);
const itemPath = `somePath/${itemUID}`;
const userPath = `users/${userUID}/somePath/${itemUID}`;
const dataMap = new Map<string, unknown>();
dataMap.set(`${itemPath}/vip/${userUID}`, true);
dataMap.set(`${itemPath}/foo`, foo);
dataMap.set(`${itemPath}/bar`, bar);
dataMap.set(`${userPath}/role`, "vip");
dataMap.set(`${userPath}/foo`, foo);
dataMap.set(`${userPath}bar`, bar);
dataMap.forEach((value: unknown, key: string) =>
console.log(key, value));
return db.ref("/").update(dataMap).then(() => {
console.log(`Added new item with key: ${itemUID} ` +
`; added vip role to user ${userUID}`);
return {"message": "Success"};
}).catch((e) => {
console.log(`Error: ${e}`);
throw new functions.https.HttpsError("unknown", "Unknown error" +
"occured");
});
});
I'm not totally sure about the reason but updating with an object directly instead of new Map() seems to be working (and yes, it didn't work for me with a Map):
const dMap = {
[`${itemPath}/vip/${userUID}`]: true,
[`${itemPath}/foo`]: foo,
[`${itemPath}/bar`]: bar,
[`${userPath}/role`]: "vip",
[`${userPath}/foo`]: foo,
[`${userPath}bar`]: bar
}
try {
await db.ref("/").update(dMap);
console.log(`Added new item with key: ${itemUID}; added vip role to user ${userUID}`);
return {"message": "Success"};
} catch (e) {
console.log(`Error: ${e}`);
throw new functions.https.HttpsError("unknown", "Unknown error" +
"occured");
}
This works for me.
const dMap: { [key: string]: any; } = {};
dMap[`${itemPath}/vip/${userUID}`]= true;
dMap[`${itemPath}/foo`]= foo;
dMap[`${itemPath}/bar`]= bar;
dMap[`${userPath}/role`]= "vip";
dMap[`${userPath}/foo`]= foo;
dMap[`${userPath}bar`]= bar;
db.ref().update(dMap);

can not get cascade DDS value for SharedObjectSequence

I have a test like this, but i can not get the 'sharedMap' in 'sharedSeq1' value, i don't know how to get the 'remoteFluidObjectHandle' value.
import {MockContainerRuntimeFactory, MockFluidDataStoreRuntime, MockStorage} from "#fluidframework/test-runtime-utils";
import {SharedObjectSequence, SharedObjectSequenceFactory} from "#fluidframework/sequence";
import * as mocks from "#fluidframework/test-runtime-utils";
import {SharedMap} from "#fluidframework/map";
import {IFluidHandle} from "#fluidframework/core-interfaces";
const mockRuntime: mocks.MockFluidDataStoreRuntime = new mocks.MockFluidDataStoreRuntime();
describe('ShredObjectSequence', function () {
it('should get synchronization data from another shared object', async function () {
const dataStoreRuntime1 = new MockFluidDataStoreRuntime();
const sharedSeq1: SharedObjectSequence<IFluidHandle<SharedMap>> = new SharedObjectSequence(mockRuntime, 'shareObjectSeq1', SharedObjectSequenceFactory.Attributes,)
const containerRuntimeFactory = new MockContainerRuntimeFactory();
dataStoreRuntime1.local = false;
const containerRuntime1 = containerRuntimeFactory.createContainerRuntime(
dataStoreRuntime1,
);
const services1 = {
deltaConnection: containerRuntime1.createDeltaConnection(),
objectStorage: new MockStorage(),
};
sharedSeq1.initializeLocal();
sharedSeq1.connect(services1);
const dataStoreRuntime2 = new MockFluidDataStoreRuntime();
const containerRuntime2 = containerRuntimeFactory.createContainerRuntime(
dataStoreRuntime2,
);
const services2 = {
deltaConnection: containerRuntime2.createDeltaConnection(),
objectStorage: new MockStorage(),
};
const sharedSeq2: SharedObjectSequence<IFluidHandle<SharedMap>> = new SharedObjectSequence(mockRuntime, 'shareObjectSeq2', SharedObjectSequenceFactory.Attributes,)
sharedSeq2.initializeLocal();
sharedSeq2.connect(services2);
// insert a node into sharedSeq2, it will sync to sharedSeq1
sharedSeq2.insert(0, [<IFluidHandle<SharedMap>>new SharedMap('sharedMapId', mockRuntime, SharedMap.getFactory().attributes).handle])
containerRuntimeFactory.processAllMessages();
// next case is passed, it show we got the sharedSeq2 changed
expect(sharedSeq1.getLength()).toBe(1)
const remoteFluidObjectHandle = await sharedSeq1.getRange(0, 1)[0];
// at here, i get error: Cannot read property 'mimeType' of null, it cause by remoteFluidObjectHandle.ts:51:30
const sharedMap = await remoteFluidObjectHandle.get()
expect(sharedMap).not.toBeUndefined()
});
});
run this test will get 'Cannot read property 'mimeType' of null' error, it caused by 'remoteFluidObjectHandle.ts:51:30'
The fluid mocks have very limited and specific behaviors, it looks like you are hitting the limits of them. You'll have better luck with an end-to-end test, see packages\test\end-to-end-tests. These use the same in-memory server as our as the playground on fluidframework dot com. The in-memory server uses the same code as tinylicious, our single process server and routerlicious, our docker based reference implementation.

How would I write a changed variable to my config.js file for a permanent change?

My Problem
I am currently writing a Discord bot to be used on one server at the moment. I have set up a command that will change the prefix of the bot's commands but as soon as I restart my repl, it resets to the original prefix. I would like to change the command so that it will write to my config.js file to stop this from happening.
What I've Tried So Far
To be honest, I haven't tried anything yet as I have no idea where to start
My code Files
config.js file:
var config={};
config.token = "My Bot Token";
config.prefix = "//";
config.statusMessage = "video games | (" + config.prefix + "help)";
config.dbltoken = undefined;
module.exports = config;
change-prefix.js file:
config = require('../config.js');
module.exports = (client, message, args) => {
config.prefix = args;
message.reply("Prefix has been changed to: " + config.prefix);
console.log("Command Used: Change-Prefix");
}
What Should Happen
The change-prefix.js file should successfully write the new prefix determined by the user to the config.js file. At this moment in time, I have no errors, but I would like to change this as it would vastly improve the user experience for my bot.
If you want to write the file, you can use fs module. The code below saves custom prefix to prefix.txt file and checks if it exists every time you start your repl. If not, it's using the default value.
Note: the code doesn't have any error handling or any other features, it's just a simple code to show you the idea. In real life scenario, you'll probably want to save your prefix to database, add per-server prefix setting, filter messages from other bots, include prefix in command invocation. Just one more thing - please put Discord token in .env, not in config file.
const Discord = require('discord.js');
const fs = require('fs');
const config = require('./config.js');
const client = new Discord.Client();
// If prefix.txt exist, use it. Otherwise, get data from config file
let prefix = fs.existsSync('prefix.txt') ? fs.readFileSync('prefix.txt').toString() : config.prefix;
client.on('message', (msg) => {
// 'set prefix XXX' to change your prefix to XXX
if (/^set prefix /i.exec(msg.content)) {
const newPrefix = msg.content.split(' ')[2];
fs.writeFile("./prefix.txt", newPrefix, function(err) {
if(err) {
return console.log(err);
}
prefix = newPrefix;
console.log(`Prefix changed to ${prefix}`);
});
}
// 'show prefix' to show current prefix
if (/^show prefix/i.exec(msg.content)) {
console.log(`Prefix is ${prefix}`);
};
});
client.on('ready', () => {
console.log(`I'm in`);
});
client.login(process.env.DISCORD_TOKEN);

Git diff gives no output although SHA for image is different

I'm trying to create a deployment script which will let me know whether or not I have the latest image of my project deployed on either my master or development branch.
I'm attempting to use git.diff to compare the SHA1 hash of the deployed image against my local repository, and although the hashes are clearly different, git.diff gives me no output. I don't understand what's going on here, since if the SHA1 is different, there must surely be changes to show from git.diff?
This is the code I have written so far:
#!/usr/bin/node
// get an exec function from node we can use to run shell commands
const exec = require('util').promisify(require('child_process').exec);
// check the user supplied the folder name of the repo as an arg
if (!process.argv[2]) {
console.error('argument missing');
process.exit(1);
}
// initialize our git client using the repo path arg
const git = require('simple-git/promise')("../../" + process.argv[2]);
var projectNameArray = process.argv[2].split(".");
const projectName = projectNameArray[0] + "-" + projectNameArray[1] + "-" + projectNameArray[2]
console.log('\x1b[36m%s\x1b[0m', 'Your project name is:', projectName);
// use an IIAFE for async/await
(async () => {
// run git rev-parse development and
var devSha1 = await git.revparse(['development']);
console.log('\x1b[36m%s\x1b[0m', 'devSha1: ', devSha1);
devSha1 = devSha1.replace(/(\n)/gm,"");
// run git rev-parse master
var masterSha1 = await git.revparse(['master']);
console.log('\x1b[36m%s\x1b[0m', 'masterSha1: ', masterSha1);
masterSha1 = masterSha1.replace(/(\n)/gm,"");
// use kubectl to export pods to JSON and then parse it
const { stdout, stderr } = await exec(`kubectl get deployment ${projectName} -o json`);
const pods = JSON.parse(stdout);
const imageName = pods.spec.template.spec.containers[0].image;
//get deployed image has
const commitHashArray = imageName.split('development-' || 'master-');
console.log('\x1b[36m%s\x1b[0m', 'Deployed image: ', commitHashArray[1]);
var diffArray = new Array(devSha1, commitHashArray[1])
//logic to tell if latest is deployed of if behind
if (commitHashArray[1] == devSha1){
console.log('\x1b[32m%s\x1b[0m', 'You have the latest image deployed');
} else {
console.log('\x1b[31m%s\x1b[0m', 'You don\'t have the latest image deployed');
await git.diff(diffArray);
}
})().then(() => console.log('\x1b[32m%s\x1b[0m', 'Ok')).catch((e) => console.error(e));
This gives me the following console output:
Your project name is: xxx-xxx-xxx
devSha1: 6a7ee89dbefc4508b03d863e5c1f5dd9dce579b4
masterSha1: 4529244ba95e1b043b691c5ef1dc484c7d67dbe2
Deployed image: 446c4ba124f7a12c8a4c91ca8eedde4c3c8652fd
You don't have the latest image deployed
Ok
I'm not sure if I'm fundamentally misunderstanding how git.diff works, or if something else is at play here. The images clearly don't match, so I would love if anyone could explain why there is no output from this function?
Thanks! :)

Resources