Web3 API参考指南
@solana/web3.js
库是一个涵盖Solana JSON RPC API的软件包。
您可以在这里找到@solana/web3.js
库的完整文档。
一般
连接
连接用于与Solana JSON RPC进行交互。 您可以使用连接来确认交易,获取账户信息等。
您可以通过定义JSON RPC集群终点和所需的承诺来创建连接。
一旦完成此操作,您可以使用此连接对象与任何Solana JSON RPC API 进行交互。
示例用法
const web3 = require("@solana/web3.js");
let connection = new web3.Connection(web3.clusterApiUrl("devnet"), "confirmed");
let slot = await connection.getSlot();
console.log(slot);
// 93186439
let blockTime = await connection.getBlockTime(slot);
console.log(blockTime);
// 1630747045
let block = await connection.getBlock(slot);
console.log(block);
/*
{
blockHeight: null,
blockTime: 1630747045,
blockhash: 'AsFv1aV5DGip9YJHHqVjrGg6EKk55xuyxn2HeiN9xQyn',
parentSlot: 93186438,
previousBlockhash: '11111111111111111111111111111111',
rewards: [],
transactions: []
}
*/
let slotLeader = await connection.getSlotLeader();
console.log(slotLeader);
//49AqLYbpJYc2DrzGUAH1fhWJy62yxBxpLEkfJwjKy2jr
上面的示例仅显示了 Connection
上的一些方法。请参阅生成的文档以获取完整列表。
交易
交易用于与Solana区块链上的程序进行交互。
这些交易使用TransactionInstructions
构建,
其中包含所有可能进行交互的账户,以及任何所需的数据或程序地址。
每个TransactionInstruction
包括键、数据和程序ID。
您可以在单个交易中执行多个指令,同时与多个程序进行交互。
示例用法
const web3 = require("@solana/web3.js");
const nacl = require("tweetnacl");
// Airdrop SOL 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);
密钥对
密钥对用于在Solana内创建具有公钥和秘钥的帐户。
您可以生成密钥对,从种子生成,或者从秘钥创建。
示例用法
const { Keypair } = require("@solana/web3.js");
let account = Keypair.generate();
console.log(account.publicKey.toBase58());
console.log(account.secretKey);
// 2DVaHtcdTf7cm18Zm9VV8rKK4oSnjmTkKE6MiXe18Qsb
// Uint8Array(64) [
// 152, 43, 116, 211, 207, 41, 220, 33, 193, 168, 118,
// 24, 176, 83, 206, 132, 47, 194, 2, 203, 186, 131,
// 197, 228, 156, 170, 154, 41, 56, 76, 159, 124, 18,
// 14, 247, 32, 210, 51, 102, 41, 43, 21, 12, 170,
// 166, 210, 195, 188, 60, 220, 210, 96, 136, 158, 6,
// 205, 189, 165, 112, 32, 200, 116, 164, 234
// ]
let seed = Uint8Array.from([
70, 60, 102, 100, 70, 60, 102, 100, 70, 60, 102, 100, 70, 60, 102, 100, 70,
60, 102, 100, 70, 60, 102, 100, 70, 60, 102, 100, 70, 60, 102, 100,
]);
let accountFromSeed = Keypair.fromSeed(seed);
console.log(accountFromSeed.publicKey.toBase58());
console.log(accountFromSeed.secretKey);
// 3LDverZtSC9Duw2wyGC1C38atMG49toPNW9jtGJiw9Ar
// Uint8Array(64) [
// 70, 60, 102, 100, 70, 60, 102, 100, 70, 60, 102,
// 100, 70, 60, 102, 100, 70, 60, 102, 100, 70, 60,
// 102, 100, 70, 60, 102, 100, 70, 60, 102, 100, 34,
// 164, 6, 12, 9, 193, 196, 30, 148, 122, 175, 11,
// 28, 243, 209, 82, 240, 184, 30, 31, 56, 223, 236,
// 227, 60, 72, 215, 47, 208, 209, 162, 59
// ]
let accountFromSecret = Keypair.fromSecretKey(account.secretKey);
console.log(accountFromSecret.publicKey.toBase58());
console.log(accountFromSecret.secretKey);
// 2DVaHtcdTf7cm18Zm9VV8rKK4oSnjmTkKE6MiXe18Qsb
// Uint8Array(64) [
// 152, 43, 116, 211, 207, 41, 220, 33, 193, 168, 118,
// 24, 176, 83, 206, 132, 47, 194, 2, 203, 186, 131,
// 197, 228, 156, 170, 154, 41, 56, 76, 159, 124, 18,
// 14, 247, 32, 210, 51, 102, 41, 43, 21, 12, 170,
// 166, 210, 195, 188, 60, 220, 210, 96, 136, 158, 6,
// 205, 189, 165, 112, 32, 200, 116, 164, 234
// ]
使用 generate
生成一个随机的 Keypair
以在 Solana 上用作账户。
使用 fromSeed
,您可以使用确定性构造函数生成一个 Keypair
。
fromSecret
从一个秘密的 Uint8array
创建一个 Keypair
。
您可以看到 generate Keypair
和 fromSecret Keypair
的 publicKey
是相同的,
因为 generate Keypair
中的秘密被用于 fromSecret
。
除非您使用高熵生成种子,否则不要使用 fromSeed
。不要分享您的种子。将种子视为私 钥对待。
PublicKey
PublicKey
在 @solana/web3.js
中被用于交易、密钥对和程序。
在交易中列出每个账户和作为 Solana 上的通用标识符时,您需要公钥。
公钥可以使用 base58
编码的字符串、缓冲区、Uint8Array
、数字和数字数组进行创建。
示例用法
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
系统程序
SystemProgram
允许创建帐户、分配帐户数 据、将帐户分配给程序、
处理 nonce 帐户以及传输 lamports
。
您可以使用 SystemInstruction
类来帮助解码和阅读单个指令
示例用法
const web3 = require("@solana/web3.js");
// Airdrop SOL 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 });
// Allocate Account Data
let allocatedAccount = web3.Keypair.generate();
let allocateInstruction = web3.SystemProgram.allocate({
accountPubkey: allocatedAccount.publicKey,
space: 100,
});
let transaction = new web3.Transaction().add(allocateInstruction);
await web3.sendAndConfirmTransaction(connection, transaction, [
payer,
allocatedAccount,
]);
// Create Nonce Account
let nonceAccount = web3.Keypair.generate();
let minimumAmountForNonceAccount =
await connection.getMinimumBalanceForRentExemption(web3.NONCE_ACCOUNT_LENGTH);
let createNonceAccountTransaction = new web3.Transaction().add(
web3.SystemProgram.createNonceAccount({
fromPubkey: payer.publicKey,
noncePubkey: nonceAccount.publicKey,
authorizedPubkey: payer.publicKey,
lamports: minimumAmountForNonceAccount,
}),
);
await web3.sendAndConfirmTransaction(
connection,
createNonceAccountTransaction,
[payer, nonceAccount],
);
// Advance nonce - Used to create transactions as an account custodian
let advanceNonceTransaction = new web3.Transaction().add(
web3.SystemProgram.nonceAdvance({
noncePubkey: nonceAccount.publicKey,
authorizedPubkey: payer.publicKey,
}),
);
await web3.sendAndConfirmTransaction(connection, advanceNonceTransaction, [
payer,
]);
// Transfer lamports between accounts
let toAccount = web3.Keypair.generate();
let transferTransaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: toAccount.publicKey,
lamports: 1000,
}),
);
await web3.sendAndConfirmTransaction(connection, transferTransaction, [payer]);
// Assign a new account to a program
let programId = web3.Keypair.generate();
let assignedAccount = web3.Keypair.generate();
let assignTransaction = new web3.Transaction().add(
web3.SystemProgram.assign({
accountPubkey: assignedAccount.publicKey,
programId: programId.publicKey,
}),
);
await web3.sendAndConfirmTransaction(connection, assignTransaction, [
payer,
assignedAccount,
]);
Secp256k1Program
Secp256k1Program
用于验证 Secp256k1
签名,该签名被比特币和以太坊使用。
示例用法
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]);
消息
消息用作构造交易的另一种方式。
您可以使用交易中的账户、头部、指令和最近的区块哈希来构造消息。
交易是消息和执行交易所需的所需签名列表的总和。
示例用法
const { Buffer } = require("buffer");
const bs58 = require("bs58");
const web3 = require("@solana/web3.js");
let toPublicKey = web3.Keypair.generate().publicKey;
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 });
let type = web3.SYSTEM_INSTRUCTION_LAYOUTS.Transfer;
let data = Buffer.alloc(type.layout.span);
let layoutFields = Object.assign({ instruction: type.index });
type.layout.encode(layoutFields, data);
let recentBlockhash = await connection.getRecentBlockhash();
let messageParams = {
accountKeys: [
fromPublicKey.publicKey.toString(),
toPublicKey.toString(),
web3.SystemProgram.programId.toString(),
],
header: {
numReadonlySignedAccounts: 0,
numReadonlyUnsignedAccounts: 1,
numRequiredSignatures: 1,
},
instructions: [
{
accounts: [0, 1],
data: bs58.encode(data),
programIdIndex: 2,
},
],
recentBlockhash,
};
let message = new web3.Message(messageParams);
let transaction = web3.Transaction.populate(message, [
fromPublicKey.publicKey.toString(),
]);
await web3.sendAndConfirmTransaction(connection, transaction, [fromPublicKey]);
结构
结构类用于在 JavaScript 中创建与 Rust 兼容的结构体。
该类仅与 Borsh 编码的 Rust 结构体兼容。
示例用法
Rust中的结构体:
pub struct Fee {
pub denominator: u64,
pub numerator: u64,
}
使用web3:
import BN from "bn.js";
import { Struct } from "@solana/web3.js";
export class Fee extends Struct {
denominator: BN;
numerator: BN;
}
枚举
枚举类用于在 JavaScript 中表示与 Rust 兼容的枚举。
如果记录,该枚举将只是一个字符串表示,但在与 Struct 结合使用时,可以正常编码/解码。
该类仅与 Borsh 编码的 Rust 枚举兼容。
示例用法
Rust中的枚举:
pub enum AccountType {
Uninitialized,
StakePool,
ValidatorList,
}
使用web3:
import { Enum } from "@solana/web3.js";
export class AccountType extends Enum {}
NonceAccount
通常情况下,如果交易的 recentBlockhash
字段过时,交易将被拒绝。
为了提供某些托管服务,使用 Nonce 账户。
通过 Nonce 账户在链上捕获 recentBlockhash
的交易不会过期,
只要 Nonce 账户未被推进。
您可以先创建一个普通账户,
然后使用 SystemProgram
使账户成为 Nonce 账户来创建一个 nonce 账户。
示例用法
const web3 = require("@solana/web3.js");
// Create connection
let connection = new web3.Connection(web3.clusterApiUrl("devnet"), "confirmed");
// Generate accounts
let account = web3.Keypair.generate();
let nonceAccount = web3.Keypair.generate();
// Fund account
let airdropSignature = await connection.requestAirdrop(
account.publicKey,
web3.LAMPORTS_PER_SOL,
);
await connection.confirmTransaction({ signature: airdropSignature });
// Get Minimum amount for rent exemption
let minimumAmount = await connection.getMinimumBalanceForRentExemption(
web3.NONCE_ACCOUNT_LENGTH,
);
// Form CreateNonceAccount transaction
let transaction = new web3.Transaction().add(
web3.SystemProgram.createNonceAccount({
fromPubkey: account.publicKey,
noncePubkey: nonceAccount.publicKey,
authorizedPubkey: account.publicKey,
lamports: minimumAmount,
}),
);
// Create Nonce Account
await web3.sendAndConfirmTransaction(connection, transaction, [
account,
nonceAccount,
]);
let nonceAccountData = await connection.getNonce(
nonceAccount.publicKey,
"confirmed",
);
console.log(nonceAccountData);
// NonceAccount {
// authorizedPubkey: PublicKey {
// _bn: <BN: 919981a5497e8f85c805547439ae59f607ea625b86b1138ea6e41a68ab8ee038>
// },
// nonce: '93zGZbhMmReyz4YHXjt2gHsvu5tjARsyukxD4xnaWaBq',
// feeCalculator: { lamportsPerSignature: 5000 }
// }
let nonceAccountInfo = await connection.getAccountInfo(
nonceAccount.publicKey,
"confirmed",
);
let nonceAccountFromInfo = web3.NonceAccount.fromAccountData(
nonceAccountInfo.data,
);
console.log(nonceAccountFromInfo);
// NonceAccount {
// authorizedPubkey: PublicKey {
// _bn: <BN: 919981a5497e8f85c805547439ae59f607ea625b86b1138ea6e41a68ab8ee038>
// },
// nonce: '93zGZbhMmReyz4YHXjt2gHsvu5tjARsyukxD4xnaWaBq',
// feeCalculator: { lamportsPerSignature: 5000 }
// }
上述示例展示了如何使用 SystemProgram.createNonceAccount
创建 NonceAccount
,
以及如何从 accountInfo
中检索 NonceAccount
。
使用 nonce
,您可以创建将 nonce
替代最近的 blockhash
的离线交易。
VoteAccount
投票账户是一个对象,它授予从网络上的本地投票账户程序解码投票账户的能力。
示例用法
const web3 = require("@solana/web3.js");
let voteAccountInfo = await connection.getProgramAccounts(web3.VOTE_PROGRAM_ID);
let voteAccountFromData = web3.VoteAccount.fromAccountData(
voteAccountInfo[0].account.data,
);
console.log(voteAccountFromData);
/*
VoteAccount {
nodePubkey: PublicKey {
_bn: <BN: cf1c635246d4a2ebce7b96bf9f44cacd7feed5552be3c714d8813c46c7e5ec02>
},
authorizedWithdrawer: PublicKey {
_bn: <BN: b76ae0caa56f2b9906a37f1b2d4f8c9d2a74c1420cd9eebe99920b364d5cde54>
},
commission: 10,
rootSlot: 104570885,
votes: [
{ slot: 104570886, confirmationCount: 31 },
{ slot: 104570887, confirmationCount: 30 },
{ slot: 104570888, confirmationCount: 29 },
{ slot: 104570889, confirmationCount: 28 },
{ slot: 104570890, confirmationCount: 27 },
{ slot: 104570891, confirmationCount: 26 },
{ slot: 104570892, confirmationCount: 25 },
{ slot: 104570893, confirmationCount: 24 },
{ slot: 104570894, confirmationCount: 23 },
...
],
authorizedVoters: [ { epoch: 242, authorizedVoter: [PublicKey] } ],
priorVoters: [
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object]
],
epochCredits: [
{ epoch: 179, credits: 33723163, prevCredits: 33431259 },
{ epoch: 180, credits: 34022643, prevCredits: 33723163 },
{ epoch: 181, credits: 34331103, prevCredits: 34022643 },
{ epoch: 182, credits: 34619348, prevCredits: 34331103 },
{ epoch: 183, credits: 34880375, prevCredits: 34619348 },
{ epoch: 184, credits: 35074055, prevCredits: 34880375 },
{ epoch: 185, credits: 35254965, prevCredits: 35074055 },
{ epoch: 186, credits: 35437863, prevCredits: 35254965 },
{ epoch: 187, credits: 35672671, prevCredits: 35437863 },
{ epoch: 188, credits: 35950286, prevCredits: 35672671 },
{ epoch: 189, credits: 36228439, prevCredits: 35950286 },
...
],
lastTimestamp: { slot: 104570916, timestamp: 1635730116 }
}
*/
质押
StakeProgram
StakeProgram
便于质押 SOL
并将它们委托给网络上的任何验证器。
您可以使用 StakeProgram
创建一个质押账户,质押一些 SOL
,授权账户用于提取质押金,
停用您的质押,并提取您的资金。
StakeInstruction
类用于解码和阅读通过调用StakeProgram
的交易中的更多指令