Connection is used to interact with the Nexis JSON RPC. You can use Connection to confirm transactions, get account info, and more.
You create a connection by defining the JSON RPC cluster endpoint and the desired commitment. Once this is complete, you can use this connection object to interact with any of the Nexis JSON RPC API.
A transaction is used to interact with programs on the Nexis blockchain. These transactions are constructed with TransactionInstructions, containing all the accounts possible to interact with, as well as any needed data or program addresses. Each TransactionInstruction consists of keys, data, and a programId. You can do multiple instructions in a single transaction, interacting with multiple programs at once.
const web3 = require("@solana/web3.js");
const nacl = require("tweetnacl");
// Airdrop NZT for paying transactions
let payer = web3.Keypair.generate();
let connection = new web3.Connection(web3.clusterApiUrl("devnet"), "confirmed");
let airdropSignature = await connection.requestAirdrop(
payer.publicKey,
web3.LAMPORTS_PER_SOL,
);
await connection.confirmTransaction({ signature: airdropSignature });
let toAccount = web3.Keypair.generate();
// Create Simple Transaction
let transaction = new web3.Transaction();
// Add an instruction to execute
transaction.add(
web3.SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: toAccount.publicKey,
lamports: 1000,
}),
);
// Send and confirm transaction
// Note: feePayer is by default the first signer, or payer, if the parameter is not set
await web3.sendAndConfirmTransaction(connection, transaction, [payer]);
// Alternatively, manually construct the transaction
let recentBlockhash = await connection.getRecentBlockhash();
let manualTransaction = new web3.Transaction({
recentBlockhash: recentBlockhash.blockhash,
feePayer: payer.publicKey,
});
manualTransaction.add(
web3.SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: toAccount.publicKey,
lamports: 1000,
}),
);
let transactionBuffer = manualTransaction.serializeMessage();
let signature = nacl.sign.detached(transactionBuffer, payer.secretKey);
manualTransaction.addSignature(payer.publicKey, signature);
let isVerifiedSignature = manualTransaction.verifySignatures();
console.log(`The signatures were verified: ${isVerifiedSignature}`);
// The signatures were verified: true
let rawTransaction = manualTransaction.serialize();
await web3.sendAndConfirmRawTransaction(connection, rawTransaction);
The keypair is used to create an account with a public key and secret key within Nexis. You can either generate, generate from a seed, or create from a secret key.
Using generate generates a random Keypair for use as an account on Nexis. Using fromSeed, you can generate a Keypair using a deterministic constructor. fromSecret creates a Keypair from a secret Uint8array. You can see that the publicKey for the generate Keypair and fromSecret Keypair are the same because the secret from the generate Keypair is used in fromSecret.
Warning: Do not use fromSeed unless you are creating a seed with high entropy. Do not share your seed. Treat the seed like you would a private key.
PublicKey is used throughout @solana/web3.js in transactions, keypairs, and programs. You require publickey when listing each account in a transaction and as a general identifier on Nexis.
A PublicKey can be created with a base58 encoded string, buffer, Uint8Array, number, and an array of numbers.
const { Buffer } = require("buffer");
const web3 = require("@solana/web3.js");
const crypto = require("crypto");
// Create a PublicKey with a base58 encoded string
let base58publicKey = new web3.PublicKey(
"5xot9PVkphiX2adznghwrAuxGs2zeWisNSxMW6hU6Hkj",
);
console.log(base58publicKey.toBase58());
// 5xot9PVkphiX2adznghwrAuxGs2zeWisNSxMW6hU6Hkj
// Create a Program Address
let highEntropyBuffer = crypto.randomBytes(31);
let programAddressFromKey = await web3.PublicKey.createProgramAddress(
[highEntropyBuffer.slice(0, 31)],
base58publicKey,
);
console.log(`Generated Program Address: ${programAddressFromKey.toBase58()}`);
// Generated Program Address: 3thxPEEz4EDWHNxo1LpEpsAxZryPAHyvNVXJEJWgBgwJ
// Find Program address given a PublicKey
let validProgramAddress = await web3.PublicKey.findProgramAddress(
[Buffer.from("", "utf8")],
programAddressFromKey,
);
console.log(`Valid Program Address: ${validProgramAddress}`);
// Valid Program Address: C14Gs3oyeXbASzwUpqSymCKpEyccfEuSe8VRar9vJQRE,253
The SystemProgram grants the ability to create accounts, allocate account data, assign an account to programs, work with nonce accounts, and transfer lamports. You can use the SystemInstruction class to help with decoding and reading individual instructions
const { keccak_256 } = require("js-sha3");
const web3 = require("@solana/web3.js");
const secp256k1 = require("secp256k1");
// Create a Ethereum Address from secp256k1
let secp256k1PrivateKey;
do {
secp256k1PrivateKey = web3.Keypair.generate().secretKey.slice(0, 32);
} while (!secp256k1.privateKeyVerify(secp256k1PrivateKey));
let secp256k1PublicKey = secp256k1
.publicKeyCreate(secp256k1PrivateKey, false)
.slice(1);
let ethAddress =
web3.Secp256k1Program.publicKeyToEthAddress(secp256k1PublicKey);
console.log(`Ethereum Address: 0x${ethAddress.toString("hex")}`);
// Ethereum Address: 0xadbf43eec40694eacf36e34bb5337fba6a2aa8ee
// Fund a keypair to create instructions
let fromPublicKey = web3.Keypair.generate();
let connection = new web3.Connection(web3.clusterApiUrl("devnet"), "confirmed");
let airdropSignature = await connection.requestAirdrop(
fromPublicKey.publicKey,
web3.LAMPORTS_PER_SOL,
);
await connection.confirmTransaction({ signature: airdropSignature });
// Sign Message with Ethereum Key
let plaintext = Buffer.from("string address");
let plaintextHash = Buffer.from(keccak_256.update(plaintext).digest());
let { signature, recid: recoveryId } = secp256k1.ecdsaSign(
plaintextHash,
secp256k1PrivateKey,
);
// Create transaction to verify the signature
let transaction = new Transaction().add(
web3.Secp256k1Program.createInstructionWithEthAddress({
ethAddress: ethAddress.toString("hex"),
plaintext,
signature,
recoveryId,
}),
);
// Transaction will succeed if the message is verified to be signed by the address
await web3.sendAndConfirmTransaction(connection, transaction, [fromPublicKey]);
Message is used as another way to construct transactions. You can construct a message using the accounts, header, instructions, and recentBlockhash that are a part of a transaction. A Transaction is a Message plus the list of required signatures required to execute the transaction.
The Enum class is used to represent a Rust compatible Enum in javascript. The enum will just be a string representation if logged but can be properly encoded/decoded when used in conjunction with Struct. This class is only compatible with Borsh encoded Rust enumerations.
Normally a transaction is rejected if a transaction's recentBlockhash field is too old. To provide for certain custodial services, Nonce Accounts are used. Transactions which use a recentBlockhash captured on-chain by a Nonce Account do not expire as long at the Nonce Account is not advanced.
You can create a nonce account by first creating a normal account, then using SystemProgram to make the account a Nonce Account.
The above example shows both how to create a NonceAccount using SystemProgram.createNonceAccount, as well as how to retrieve the NonceAccount from accountInfo. Using the nonce, you can create transactions offline with the nonce in place of the recentBlockhash.
The StakeProgram facilitates staking NZT and delegating them to any validators on the network. You can use StakeProgram to create a stake account, stake some SOL, authorize accounts for withdrawal of your stake, deactivate your stake, and withdraw your funds. The StakeInstruction class is used to decode and read more instructions from transactions calling the StakeProgram
const web3 = require("@solana/web3.js");
// Fund a key to create transactions
let fromPublicKey = web3.Keypair.generate();
let connection = new web3.Connection(web3.clusterApiUrl("devnet"), "confirmed");
let airdropSignature = await connection.requestAirdrop(
fromPublicKey.publicKey,
web3.LAMPORTS_PER_SOL,
);
await connection.confirmTransaction({ signature: airdropSignature });
// Create Account
let stakeAccount = web3.Keypair.generate();
let authorizedAccount = web3.Keypair.generate();
/* Note: This is the minimum amount for a stake account -- Add additional Lamports for staking
For example, we add 50 lamports as part of the stake */
let lamportsForStakeAccount =
(await connection.getMinimumBalanceForRentExemption(
web3.StakeProgram.space,
)) + 50;
let createAccountTransaction = web3.StakeProgram.createAccount({
fromPubkey: fromPublicKey.publicKey,
authorized: new web3.Authorized(
authorizedAccount.publicKey,
authorizedAccount.publicKey,
),
lamports: lamportsForStakeAccount,
lockup: new web3.Lockup(0, 0, fromPublicKey.publicKey),
stakePubkey: stakeAccount.publicKey,
});
await web3.sendAndConfirmTransaction(connection, createAccountTransaction, [
fromPublicKey,
stakeAccount,
]);
// Check that stake is available
let stakeBalance = await connection.getBalance(stakeAccount.publicKey);
console.log(`Stake balance: ${stakeBalance}`);
// Stake balance: 2282930
// We can verify the state of our stake. This may take some time to become active
let stakeState = await connection.getStakeActivation(stakeAccount.publicKey);
console.log(`Stake state: ${stakeState.state}`);
// Stake state: inactive
// To delegate our stake, we get the current vote accounts and choose the first
let voteAccounts = await connection.getVoteAccounts();
let voteAccount = voteAccounts.current.concat(voteAccounts.delinquent)[0];
let votePubkey = new web3.PublicKey(voteAccount.votePubkey);
// We can then delegate our stake to the voteAccount
let delegateTransaction = web3.StakeProgram.delegate({
stakePubkey: stakeAccount.publicKey,
authorizedPubkey: authorizedAccount.publicKey,
votePubkey: votePubkey,
});
await web3.sendAndConfirmTransaction(connection, delegateTransaction, [
fromPublicKey,
authorizedAccount,
]);
// To withdraw our funds, we first have to deactivate the stake
let deactivateTransaction = web3.StakeProgram.deactivate({
stakePubkey: stakeAccount.publicKey,
authorizedPubkey: authorizedAccount.publicKey,
});
await web3.sendAndConfirmTransaction(connection, deactivateTransaction, [
fromPublicKey,
authorizedAccount,
]);
// Once deactivated, we can withdraw our funds
let withdrawTransaction = web3.StakeProgram.withdraw({
stakePubkey: stakeAccount.publicKey,
authorizedPubkey: authorizedAccount.publicKey,
toPubkey: fromPublicKey.publicKey,
lamports: stakeBalance,
});
await web3.sendAndConfirmTransaction(connection, withdrawTransaction, [
fromPublicKey,
authorizedAccount,
]);
Authorized is an object used when creating an authorized account for staking within Nexis. You can designate a staker and withdrawer separately, allowing for a different account to withdraw other than the staker.
You can find more usage of the Authorized object under StakeProgram
Lockup is used in conjunction with the StakeProgram to create an account. The Lockup is used to determine how long the stake will be locked, or unable to be retrieved. If the Lockup is set to 0 for both epoch and the Unix timestamp, the lockup will be disabled for the stake account.
const {
Authorized,
Keypair,
Lockup,
StakeProgram,
} = require("@solana/web3.js");
let account = Keypair.generate();
let stakeAccount = Keypair.generate();
let authorized = new Authorized(account.publicKey, account.publicKey);
let lockup = new Lockup(0, 0, account.publicKey);
let createStakeAccountInstruction = StakeProgram.createAccount({
fromPubkey: account.publicKey,
authorized: authorized,
lamports: 1000,
lockup: lockup,
stakePubkey: stakeAccount.publicKey,
});
The above code creates a createStakeAccountInstruction to be used when creating an account with the StakeProgram. The Lockup is set to 0 for both the epoch and Unix timestamp, disabling lockup for the account.