How to Detect Collisions Between Humanoids in Roblox

Really quick blog post here tonight on how to detect collisions between Humanoids in Roblox. My script is named DetectCollisionsBetweenHumanoids and I’ve placed this script under ServerScriptService. Please note, that I have some code in my example which displays text on the users screen whenever a collision is detected, you can ignore this part of the code which displays that a collision has occurred on the screen:

-- DisplayTextModule is some code I use to display text on screen for testing, if you see this in a code snippet, ignore this part
local DisplayTextModule = require(script.Parent.Parent.StarterGui.ScreenGui.Frame.TextLabel.DisplayTextModuleScript)
local Players = game:GetService("Players")
-- Works for R15, not sure if this works for R6 or not
local function partIsHumanoid(part)
if part.Name == "Head" then
return true
elseif part.Name == "UpperTorso" then
return true
elseif part.Name == "LowerTorso" then
return true
elseif part.Name == "LeftFoot" then
return true
elseif part.Name == "LeftLowerLeg" then
return true
elseif part.Name == "LeftUpperLeg" then
return true
elseif part.Name == "RightFoot" then
return true
elseif part.Name == "RightLowerLeg" then
return true
elseif part.Name == "RightUpperLeg" then
return true
elseif part.Name == "LeftHand" then
return true
elseif part.Name == "LeftLowerArm" then
return true
elseif part.Name == "LeftUpperArm" then
return true
elseif part.Name == "RightHand" then
return true
elseif part.Name == "RightLowerArm" then
return true
elseif part.Name == "RightUpperArm" then
return true
else
return false
end
end
local function onPlayerAdded(player)
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
humanoid.Touched:Connect(function(otherPart)
local timestampStr = tostring(os.time(os.date("!*t")))
if partIsHumanoid(otherPart) then
DisplayTextModule.Display("Collision w/ R15: " .. otherPart.Name)
end
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
 

How to Display Text on Screen Programmatically in Roblox

I’m currently working on building my first game in Roblox, and I need to be able to print out some information to the screen for debugging. Normally you can just use “print()” to display text for debugging / texting purposes, but I’ve noticed that this doesn’t work when you’re testing multiplayer functionality. Right now I’m trying to detect collisions between Humanoids, and print just isn’t working for me in this specific circumstance since I have to run the game in multiplayer mode (print works fine for me when just running the game as a single player however).

Okay so let’s get to it, how to display text on screen programmatically in Roblox. First you’ll need to add ScreenGui to the StarterGui in Roblox Studio. If you need help with this, reference this tutorial from Roblox on how to add a scoreboard: https://create.roblox.com/docs/tutorials/building/ui/creating-a-score-bar

Then you’ll want to add a TextLabel to your ScreenGui, and after that, add a ModuleScript called DisplayTextModuleScript.

Then under ServerScriptServer, add another script called PrintToOnScreenLogger.

Here is a screenshot of what this initial setup should look like in Roblox Studio:

local module = {}
function Display(text)
local textLabel = script.Parent
textLabel.Text = text
end
module.Display = Display
return module
local DisplayTextModule = require(script.Parent.Parent.StarterGui.ScreenGui.OnScreenLogger.TextLabel.DisplayTextModuleScript)
DisplayTextModule.Display("hello, world")

The finished product will look like:

 

How to Change a Roblox Humanoid’s Appearance using Lua in Roblox Studio

I broke my femur skydiving a couple of weeks ago and am still laid up in a hospital bed recovering. I’ve been meaning to start learning a little Roblox development though, so I’m using this time lying in bed at the hospital to learn Roblox game development.

The first game that I want to make is a zombie game, because I think that’d be fairly simple to create. However, I found that I’ve been having some trouble doing two things:

  1. Detecting collisions between Humanoids
  2. Changing Humanoid’s Appearance (to turn them into zombies)

This quick blog post is just going to cover topic 2, changing humanoid’s appearance. I have a little code snippet that I created tonight that changes a Humanoid’s skin color to neon green so I can represent them as zombies. If you are looking to do something similar, maybe you’ll find this code snippet useful:

local Players = game:GetService("Players")
local function alterPlayer(player)
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local userId = player.UserId
local humanoidDescription = game.Players:GetHumanoidDescriptionFromUserId(userId)
humanoidDescription.HeadColor = Color3.fromHex("#39FF14")
humanoidDescription.LeftArmColor = Color3.fromHex("#39FF14")
humanoidDescription.RightArmColor = Color3.fromHex("#39FF14")
humanoidDescription.TorsoColor = Color3.fromHex("#39FF14")
humanoidDescription.LeftLegColor = Color3.fromHex("#39FF14")
humanoidDescription.RightLegColor = Color3.fromHex("#39FF14")
if humanoid then
humanoid:ApplyDescription(humanoidDescription)
end
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(function(character)
alterPlayer(player)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
 

Roblox Development Links

I’m laid up in the hospital right now with a broken femur (skydiving accident) and I’m trying to teach myself a little Roblox development. Roblox’s website has tons of great resources, but I don’t think it’s all that well organized. So I just wanted to write this really quick blog post to jot down the links that I have for getting started with Roblox development. Here are my links so far (will update as I learn more):

Roblox Docs (Use Slide Out Hamburger Menu): https://create.roblox.com/docs

Docs > Engine > Guides: https://create.roblox.com/docs/platform

Docs > Engine > Tutorials: https://create.roblox.com/docs/tutorials

Docs > Engine > Reference: https://create.roblox.com/docs/reference/engine

Docs > Engine > Resources: https://create.roblox.com/docs/samples

Docs > Engine > Art: https://create.roblox.com/docs/art/modeling

Docs > Engine > Design: https://create.roblox.com/docs/production/game-design

Tutorials[Core]: https://create.roblox.com/docs/tutorials/core

Tutorials[Environmental Art]: https://create.roblox.com/docs/tutorials/environmental-art

Docs > Engine > Guides > Coding Fundamentals: https://create.roblox.com/docs/tutorials/fundamentals/coding-1/coding-fundamentals

And last, there is “Introduction to Scripting.” This is the best part of the docs in my opinion for learning how to build real Roblox games that use code. I had a hard time rediscovering this section, but here’s the link: https://create.roblox.com/docs/tutorials/scripting/basic-scripting/intro-to-scripting

 

SuperInvest Privacy Policy

SuperInvest does not collect any user information. However, in the future we will track certain events users take in order to gain insights into our product and make improvements for user experience. All data will be anonymized.

 

Deploying Flask Apps to Production Linux Servers using Gunicorn and Nginx

This is is going to be a super short post that I’m really just writing for my own personal reference. The old guides that I used to use to setup my linux virtual machines for my flask apps keep giving me problems, so the purpose of this post is to jot down how to do this in the future the next time I need to do this.

First, reference this blog post: Deploy Flask The Easy Way With Gunicorn and Nginx!

What I like about this particular blog post is it skips all of the complicated pain in the @$$ steps like setting up non-root users and whatnot. I think using root is fine for small projects.

Last, the most critical thing is to make sure you install gunicorn into your virtual environment. When you do this, make sure to set the –ignore-installed flag so that gunicorn gets installed into the virtual environment. I believe this is the missing step from the previous guides I used to use which kept causing my setups to fail.

(venv) $ pip install --ignore-installed gunicorn

If you are installing from requirements.txt, also make sure to set the –ignore-installed flag so that gunicorn gets installed into your virtual environment instead of somewhere else:

(venv) $ pip install --ignore-installed -r requirements.txt

 

How to Switch Between Different Version of Cocoapods

Switching betweent different versions of cocoapods, I’ve been having to do this a lot at work recently. We have two branches of our codebase which are using different versions of cocoapods. At some point the all of the branches will end up using the same version of cocoapods, but at the moment one branch does not include the work which upgraded to the latest version of cocoapods. So if you find yourself in a similar situation, here’s all you have to do in order to switch between different versions.

First, uninstall cocoapods (the version which you don’t want to be using):

$ sudo gem uninstall cocoapods

Then, install the version you want to be using :

$ sudo gem install cocoapods -v 1.11.3

Feel free to switch back and forth between versions as needed.

 

Resolving Merge Conflicts in React Native: How to Address Conflicts in Pods, package-lock.json, yarn.lock, and project.pbxproj

Having trouble with merge conflicts in your React Native app with Pods, package-lock.json, yarn.lock, and project.pbxproj? I have the solution you’re looking for. These types of conflicts usually arise in React Native apps when one or both branches of code have installed a new node_module which uses native code, and then all sorts of conflicts will start to pop up in the Pods directory and project.pbxproj when you go to merge. The solution to fix these conflicts is to run $ pod deintegrate in both of your branches before doing your merge. This will take care of the majority of conflicts which tend to arise.

Then you’ll probably still have a few conflicts in package-lock.json, yarn.lock, and Podfile.lock. To fix the conflicts in package-lock.json or yarn.lock, you’ll want to checkout either branches package-lock.json or yarn.lock: $ git checkout name-of-your-branch — yarn.lock

For Podfile.lock, simply delete this file.

If there are any other conflicts which require manual resolution, go ahead and fix those. Then last, run $ pod install and then either $ npm install or $ yarn install. And boom! You’re back in business; merge conflicts resolved.

If you want to see every single terminal command from start to finish, please reference the 20 minute video above. Sometimes it’s hard to jot down every single step when it comes to doing something like this, so I find its helpful to just film everything for reference in case someone gets stuck on a particular step.

 

How to Pass an Array of Arguments in JavaScript

Quick blog post today that I’m writing during work on how to pass an array of arguments in JavaScript. This is something that I actually need to do today and well… I didn’t know how to do it 5 minutes ago! So without further ado… here’s how:

You can use JavaScript’s built-in Function.prototype.apply() method to pass an array of arguments. If you need to do this, check out this example–

function takeThreeArgs(arg1, arg2, arg3) {
console.log(arg1);
console.log(arg2);
console.log(arg3);
}
const myArgs = ["foo", "bar", "baz"];
takeThreeArgs.apply(null, myArgs);
 

Hello, World in Solana with Rust & Web3.js

My friend Sameer and I are currently working on our first Web3 project together, and we’re trying to learn how to use Solana. So far it’s been kind of complicated and a bit of a pain, so I just wanted to jot down a few notes here in this blog post for future reference. Mainly, I want to record my notes on getting to “hello, world” in Solana using Rust & Web3.js.

So far I haven’t found a great tutorial yet, however, there’s an okay course called recommended by the Solana team called Solana 101 that my friend and I both just took, and I think it has most of the basic building blocks you’ll need to get started with Solana programming.

If you’d like to take the Solana 101 course yourself, you can do that here: Solana 101

I believe the course used to be something you could take on Figment’s website, but now it’s simply a Github repo that you download. After you download the repo you an follow the instructions in the README to launch the course in your web browser running off of a local web server running on your machine.

Now for the real meat of what I wanted to post here… The course above has like 12 different lessons all featuring a code snippet demonstrating how to do some basic operation in Solana. However, the course isn’t hosted on the internet anymore! If you want to reference it or take it again, you have to spin your local web server up again to read the code snippets. So I decided that I really wanted to have a copy of all the code snippets up on the web that I could reference when needed. So without further ado, the 12 essential code snippets from Figment’s Solana 101 Course:

Solana 101: Connect to Solana (From Figment.io’s Solana 101 Course)

import type {NextApiRequest, NextApiResponse} from 'next';
import {getNodeURL} from '@figment-solana/lib';
import {Connection} from '@solana/web3.js';
export default async function connect(
req: NextApiRequest,
res: NextApiResponse<string>,
) {
try {
const {network} = req.body;
const url = getNodeURL(network);
const connection = new Connection(url, 'confirmed');
const version = await connection.getVersion();
res.status(200).json(version['solana-core']);
} catch (error) {
let errorMessage = error instanceof Error ? error.message : 'Unknown Error';
res.status(500).json(errorMessage);
}
}
view raw connect.ts hosted with ❤ by GitHub

Solana 101: Creating Solana Accounts AKA Keypair (From Figment.io’s Solana 101 Course)

import type {NextApiRequest, NextApiResponse} from 'next';
import {Keypair} from '@solana/web3.js';
/*
* Like with most Web 3 protocols, transactions on Solana happen between accounts.
* To create an account, a client generates a keypair which has a public key (or
* address, used to identify and lookup an account) and a secret key used to sign
* transactions.
*/
type ResponseT = {
secret: string;
address: string;
};
export default function keypair(
_req: NextApiRequest,
res: NextApiResponse<string | ResponseT>,
) {
try {
const keypair = Keypair.generate();
const address = keypair?.publicKey.toString();
const secret = JSON.stringify(Array.from(keypair.secretKey));
res.status(200).json({
secret,
address,
});
} catch (error) {
let errorMessage = error instanceof Error ? error.message : 'Unknown Error';
res.status(500).json(errorMessage);
}
}
view raw keypair.ts hosted with ❤ by GitHub

Solana 101: Funding Your Solana Account via Airdrop (From Figment.io’s Solana 101 Course)

import {Connection, PublicKey, LAMPORTS_PER_SOL} from '@solana/web3.js';
import type {NextApiRequest, NextApiResponse} from 'next';
import {getNodeURL} from '@figment-solana/lib';
export default async function fund(
req: NextApiRequest,
res: NextApiResponse<string>,
) {
try {
const {network, address} = req.body;
const url = getNodeURL(network);
const connection = new Connection(url, 'confirmed');
const publicKey = new PublicKey(address);
const hash = await connection.requestAirdrop(publicKey, LAMPORTS_PER_SOL);
await undefined;
res.status(200).json(hash);
} catch (error) {
let errorMessage = error instanceof Error ? error.message : 'Unknown Error';
res.status(500).json(errorMessage);
}
}
view raw fund.ts hosted with ❤ by GitHub

Solana 101: Getting Your Balance (From Figment.io’s Solana 101 Course)

import type {NextApiRequest, NextApiResponse} from 'next';
import {Connection, PublicKey} from '@solana/web3.js';
import {getNodeURL} from '@figment-solana/lib';
export default async function balance(
req: NextApiRequest,
res: NextApiResponse<string | number>,
) {
try {
const {network, address} = req.body;
const url = getNodeURL(network);
const connection = new Connection(url, 'confirmed');
const publicKey = new PublicKey(address);
const balance = await connection.getBalance(publicKey);
if (balance === 0 || balance === undefined) {
throw new Error('Account not funded');
}
res.status(200).json(balance);
} catch (error) {
let errorMessage = error instanceof Error ? error.message : 'Unknown Error';
res.status(500).json(errorMessage);
}
}
view raw balance.ts hosted with ❤ by GitHub

Solana 101: Transfering Funds (From Figment.io’s Solana 101 Course)

import type {NextApiRequest, NextApiResponse} from 'next';
import {getNodeURL} from '@figment-solana/lib';
import {
Connection,
PublicKey,
SystemProgram,
Transaction,
sendAndConfirmTransaction,
} from '@solana/web3.js';
export default async function transfer(
req: NextApiRequest,
res: NextApiResponse<string>,
) {
try {
const {address, secret, recipient, lamports, network} = req.body;
const url = getNodeURL(network);
const connection = new Connection(url, 'confirmed');
const fromPubkey = new PublicKey(address);
const toPubkey = new PublicKey(recipient);
// The secret key is stored in our state as a stringified array
const secretKey = Uint8Array.from(JSON.parse(secret as string));
//... let's skip the beginning as it should be familiar for you by now!
// Find the parameter to pass
const instructions = SystemProgram.transfer({
fromPubkey,
toPubkey,
lamports,
});
// How could you construct a signer array's
const signers = [
{
publicKey: fromPubkey,
secretKey,
},
];
// Maybe adding something to a Transaction could be interesting ?
const transaction = new Transaction().add(instructions);
// We can send and confirm a transaction in one row.
const hash = await sendAndConfirmTransaction(connection, transaction, signers);
res.status(200).json(hash);
} catch (error) {
let errorMessage = error instanceof Error ? error.message : 'Unknown Error';
res.status(500).json(errorMessage);
}
}
view raw transfer.ts hosted with ❤ by GitHub

Solana 101: Deploy Rust Program to Solana Blockchain (from Figment.io’s Solana 101 Course)

use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
pubkey::Pubkey,
};
/// Define the type of state stored in accounts
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct GreetingAccount {
/// number of greetings
pub counter: u32,
}
// Declare and export the program's entrypoint
entrypoint!(process_instruction);
// Program entrypoint's implementation
pub fn process_instruction(
program_id: &Pubkey, // Public key of the account the hello world program was loaded into
accounts: &[AccountInfo], // The account to say hello to
_instruction_data: &[u8], // Ignored, all helloworld instructions are hellos
) -> ProgramResult {
msg!("Hello World Rust program entrypoint");
// Iterating accounts is safer then indexing
let accounts_iter = &mut accounts.iter();
// Get the account to say hello to
let account = next_account_info(accounts_iter)?;
// The account must be owned by the program in order to modify its data
if account.owner != program_id {
msg!("Greeted account does not have the correct program id");
return Err(ProgramError::IncorrectProgramId);
}
// Increment and store the number of times the account has been greeted
let mut greeting_account = GreetingAccount::try_from_slice(&account.data.borrow())?;
greeting_account.counter += 1;
greeting_account.serialize(&mut &mut account.data.borrow_mut()[..])?;
msg!("Greeted {} time(s)!", greeting_account.counter);
Ok(())
}
// Sanity tests
#[cfg(test)]
mod test {
use super::*;
use solana_program::clock::Epoch;
use std::mem;
#[test]
fn test_sanity() {
let program_id = Pubkey::default();
let key = Pubkey::default();
let mut lamports = 0;
let mut data = vec![0; mem::size_of::<u32>()];
let owner = Pubkey::default();
let account = AccountInfo::new(
&key,
false,
true,
&mut lamports,
&mut data,
&owner,
false,
Epoch::default(),
);
let instruction_data: Vec<u8> = Vec::new();
let accounts = vec![account];
assert_eq!(
GreetingAccount::try_from_slice(&accounts[0].data.borrow())
.unwrap()
.counter,
0
);
process_instruction(&program_id, &accounts, &instruction_data).unwrap();
assert_eq!(
GreetingAccount::try_from_slice(&accounts[0].data.borrow())
.unwrap()
.counter,
1
);
process_instruction(&program_id, &accounts, &instruction_data).unwrap();
assert_eq!(
GreetingAccount::try_from_slice(&accounts[0].data.borrow())
.unwrap()
.counter,
2
);
}
}
view raw lib.rs hosted with ❤ by GitHub

$ yarn run solana:build:program

$ solana program deploy /home/zu/project/figment/learn-web3-dapp/dist/solana/program/helloworld.so

Solana 101: Check Deployed Solana Program from Client (From Figment.io’s Solana 101 Course)

import type {NextApiRequest, NextApiResponse} from 'next';
import {Connection, PublicKey} from '@solana/web3.js';
import {getNodeURL} from '@figment-solana/lib';
import path from 'path';
import fs from 'mz/fs';
const PROGRAM_PATH = path.resolve('dist/solana/program');
const PROGRAM_SO_PATH = path.join(PROGRAM_PATH, 'helloworld.so');
export default async function deploy(
req: NextApiRequest,
res: NextApiResponse<string | boolean>,
) {
try {
const {network, programId} = req.body;
const url = getNodeURL(network);
const connection = new Connection(url, 'confirmed');
// Re-create publicKeys from params
const publicKey = new PublicKey(programId);
const programInfo = await connection.getAccountInfo(publicKey);
if (programInfo === null) {
if (fs.existsSync(PROGRAM_SO_PATH)) {
throw new Error(
'Program needs to be deployed with `solana program deploy`',
);
} else {
throw new Error('Program needs to be built and deployed');
}
} else if (!programInfo.executable) {
throw new Error(`Program is not executable`);
}
res.status(200).json(true);
} catch (error) {
let errorMessage = error instanceof Error ? error.message : 'Unknown Error';
res.status(500).json(errorMessage);
}
}
view raw deploy.ts hosted with ❤ by GitHub

Solana 101: Storing Data on the Solana Blockchain (From Figment.io’s Solana 101 Course)

import {
Connection,
PublicKey,
Keypair,
SystemProgram,
Transaction,
sendAndConfirmTransaction,
} from '@solana/web3.js';
import type {NextApiRequest, NextApiResponse} from 'next';
import {getNodeURL} from '@figment-solana/lib';
import * as borsh from 'borsh';
// The state of a greeting account managed by the hello world program
class GreetingAccount {
counter = 0;
constructor(fields: {counter: number} | undefined = undefined) {
if (fields) {
this.counter = fields.counter;
}
}
}
// Borsh schema definition for greeting accounts
const GreetingSchema = new Map([
[GreetingAccount, {kind: 'struct', fields: [['counter', 'u32']]}],
]);
// The expected size of each greeting account.
const GREETING_SIZE = borsh.serialize(
GreetingSchema,
new GreetingAccount(),
).length;
type ResponseT = {
hash: string;
greeter: string;
};
export default async function greeter(
req: NextApiRequest,
res: NextApiResponse<string | ResponseT>,
) {
try {
const {network, secret, programId: programAddress} = req.body;
const url = getNodeURL(network);
const connection = new Connection(url, 'confirmed');
const programId = new PublicKey(programAddress);
const payer = Keypair.fromSecretKey(new Uint8Array(JSON.parse(secret)));
const GREETING_SEED = 'hello';
// Are there any methods from PublicKey to derive a public key from a seed?
const greetedPubkey = await PublicKey.createWithSeed(
payer.publicKey,
GREETING_SEED,
programId,
);
// This function calculates the fees we have to pay to keep the newly
// created account alive on the blockchain. We're naming it lamports because
// that is the denomination of the amount being returned by the function.
const lamports = await connection.getMinimumBalanceForRentExemption(
GREETING_SIZE,
);
// Find which instructions are expected and complete SystemProgram with
// the required arguments.
const transaction = new Transaction().add(SystemProgram.createAccountWithSeed({
fromPubkey: payer.publicKey,
basePubkey: payer.publicKey,
seed: GREETING_SEED,
newAccountPubkey: greetedPubkey,
lamports,
space: GREETING_SIZE,
programId,
}));
// Complete this function call with the expected arguments.
const hash = await sendAndConfirmTransaction(connection, transaction, [payer]);
res.status(200).json({
hash: hash,
greeter: greetedPubkey.toBase58(),
});
} catch (error) {
let errorMessage = error instanceof Error ? error.message : 'Unknown Error';
res.status(500).json(errorMessage);
}
}
view raw greeter.ts hosted with ❤ by GitHub

Solana 101: Get Data from Solana Blockchain (From Figment.io’s Solana 101 Course)

import type {NextApiRequest, NextApiResponse} from 'next';
import {Connection, PublicKey} from '@solana/web3.js';
import {getNodeURL} from '@figment-solana/lib';
import * as borsh from 'borsh';
// The state of a greeting account managed by the hello world program
class GreetingAccount {
counter = 0;
constructor(fields: {counter: number} | undefined = undefined) {
if (fields) {
this.counter = fields.counter;
}
}
}
// Borsh schema definition for greeting accounts
const GreetingSchema = new Map([
[GreetingAccount, {kind: 'struct', fields: [['counter', 'u32']]}],
]);
export default async function getter(
req: NextApiRequest,
res: NextApiResponse<string | number>,
) {
try {
const {network, greeter} = req.body;
const url = getNodeURL(network);
const connection = new Connection(url, 'confirmed');
const greeterPublicKey = new PublicKey(greeter);
const accountInfo = await connection.getAccountInfo(greeterPublicKey);
if (accountInfo === null) {
throw new Error('Error: cannot find the greeted account');
}
// Find the expected parameters.
const greeting = borsh.deserialize(
GreetingSchema,
GreetingAccount,
accountInfo.data,
);
// A little helper
console.log(greeting);
// Pass the counter to the client-side as JSON
res.status(200).json(greeting.counter);
} catch (error) {
let errorMessage = error instanceof Error ? error.message : 'Unknown Error';
console.log(errorMessage);
res.status(500).json(errorMessage);
}
}
view raw getter.ts hosted with ❤ by GitHub

Solana 101: Set Data on Solana Blockchain (From Figment.io’s Solana 101 Course)

import {
Connection,
PublicKey,
Keypair,
TransactionInstruction,
Transaction,
sendAndConfirmTransaction,
} from '@solana/web3.js';
import type {NextApiRequest, NextApiResponse} from 'next';
import {getNodeURL} from '@figment-solana/lib';
export default async function setter(
req: NextApiRequest,
res: NextApiResponse<string>,
) {
try {
const {greeter, secret, programId, network} = req.body;
const url = getNodeURL(network);
const connection = new Connection(url, 'confirmed');
const greeterPublicKey = new PublicKey(greeter);
const programKey = new PublicKey(programId);
const payerSecretKey = new Uint8Array(JSON.parse(secret));
const payerKeypair = Keypair.fromSecretKey(payerSecretKey);
// this your turn to figure out
// how to create this instruction
const instruction = new TransactionInstruction({
keys: [{pubkey: greeterPublicKey, isSigner: false, isWritable: true}],
programId: programKey,
data: Buffer.alloc(0),
});
// this your turn to figure out
// how to create this transaction
const hash = await sendAndConfirmTransaction(
connection,
new Transaction().add(instruction),
[payerKeypair]
);
res.status(200).json(hash);
} catch (error) {
console.error(error);
res.status(500).json('Get balance failed');
}
}
view raw setter.ts hosted with ❤ by GitHub