Keypairs and Wallets
How to generate a new Keypair
Keypair 또는 Wallet을 요구하는 다양한 Solana 라이브러리들에 대해 당신은 많은 다른 액션들을 취할 수 있습니다. 만약 당신이 wallet에 연결하고 있다면 걱정할 필요가 없습니다. 하지만 당신이 keypair가 필요하다면, 하나를 생성할 필요가 있습니다.
import { Keypair } from "@solana/web3.js";
(async () => {
let keypair = Keypair.generate();
})();
let keypair = Keypair.generate();
from solana.keypair import Keypair
keypair = Keypair()
keypair = Keypair()
use solana_sdk::signature::{Keypair};
fn main() {
let wallet = Keypair::new();
}
let wallet = Keypair::new();
$ solana-keygen new
# pubkey: 9ZNTfG4NyQgxy2SWjSiQoUyBPEvXT2xo7fKc5hPYYJ7b
solana-keygen new
How to restore a Keypair from a secret
만약 당신이 secret을 이미 가지고 있다면, 당신은 dApp을 테스트하기 위해 secret으로부터 Keypair를 얻을 수 있습니다.
- Bytes로부터
import { Keypair } from "@solana/web3.js";
(async () => {
const keypair = Keypair.fromSecretKey(
Uint8Array.from([
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56,
222, 53, 138, 189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246,
15, 185, 186, 82, 177, 240, 148, 69, 241, 227, 167, 80, 141, 89, 240, 121,
121, 35, 172, 247, 68, 251, 226, 218, 48, 63, 176, 109, 168, 89, 238, 135,
])
);
})();
const keypair = Keypair.fromSecretKey(
Uint8Array.from([
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56,
222, 53, 138, 189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246,
15, 185, 186, 82, 177, 240, 148, 69, 241, 227, 167, 80, 141, 89, 240, 121,
121, 35, 172, 247, 68, 251, 226, 218, 48, 63, 176, 109, 168, 89, 238, 135,
])
);
from solana.keypair import Keypair
secret_key= [
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56, 222, 53, 138,
189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246, 15, 185, 186, 82, 177, 240,
148, 69, 241, 227, 167, 80, 141, 89, 240, 121, 121, 35, 172, 247, 68, 251, 226, 218, 48,
63, 176, 109, 168, 89, 238, 135,
]
keypair = Keypair.from_secret_key(bytes(secret_key))
print("Created Keypair with Public Key: {}".format(keypair.public_key))
secret_key= [
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56, 222, 53, 138,
189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246, 15, 185, 186, 82, 177, 240,
148, 69, 241, 227, 167, 80, 141, 89, 240, 121, 121, 35, 172, 247, 68, 251, 226, 218, 48,
63, 176, 109, 168, 89, 238, 135,
]
keypair = Keypair.from_secret_key(bytes(secret_key))
use solana_sdk::signature::{Keypair, Signer};
fn main() {
let secret_key: [u8; 64] = [
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56, 222, 53, 138,
189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246, 15, 185, 186, 82, 177, 240,
148, 69, 241, 227, 167, 80, 141, 89, 240, 121, 121, 35, 172, 247, 68, 251, 226, 218, 48,
63, 176, 109, 168, 89, 238, 135,
];
if let Ok(wallet) = Keypair::from_bytes(&secret_key) {
let pubkey = Signer::pubkey(&wallet);
println!("Created keypair: {}", pubkey)
}
}
let secret_key: [u8; 64] = [
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56, 222, 53, 138,
189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246, 15, 185, 186, 82, 177, 240,
148, 69, 241, 227, 167, 80, 141, 89, 240, 121, 121, 35, 172, 247, 68, 251, 226, 218, 48,
63, 176, 109, 168, 89, 238, 135,
];
let wallet = Keypair::from_bytes(&secret_key)?;
# input your secret into the Keypath listed under solana config get
# input your secret into the Keypath listed under solana config get
- Base58 String으로부터
import { Keypair } from "@solana/web3.js";
import * as bs58 from "bs58";
(async () => {
const keypair = Keypair.fromSecretKey(
bs58.decode(
"5MaiiCavjCmn9Hs1o3eznqDEhRwxo7pXiAYez7keQUviUkauRiTMD8DrESdrNjN8zd9mTmVhRvBJeg5vhyvgrAhG"
)
);
})();
const keypair = Keypair.fromSecretKey(
bs58.decode(
"5MaiiCavjCmn9Hs1o3eznqDEhRwxo7pXiAYez7keQUviUkauRiTMD8DrESdrNjN8zd9mTmVhRvBJeg5vhyvgrAhG"
)
);
import base58
from solana.keypair import Keypair
b58_string = "5MaiiCavjCmn9Hs1o3eznqDEhRwxo7pXiAYez7keQUviUkauRiTMD8DrESdrNjN8zd9mTmVhRvBJeg5vhyvgrAhG"
keypair = Keypair.from_secret_key(base58.b58decode(b58_string)
print("Created Keypair with Public Key: {}".format(keypair.public_key))
b58_string = "5MaiiCavjCmn9Hs1o3eznqDEhRwxo7pXiAYez7keQUviUkauRiTMD8DrESdrNjN8zd9mTmVhRvBJeg5vhyvgrAhG"
keypair = Keypair.from_secret_key(base58.b58decode(b58_string))
use solana_sdk::signature::{Keypair, Signer};
fn main() {
let wallet = Keypair::from_base58_string(
"5MaiiCavjCmn9Hs1o3eznqDEhRwxo7pXiAYez7keQUviUkauRiTMD8DrESdrNjN8zd9mTmVhRvBJeg5vhyvgrAhG",
);
let pubkey = Signer::pubkey(&wallet);
println!("Created keypair: {}", pubkey)
}
let wallet = Keypair::from_base58_string(
"5MaiiCavjCmn9Hs1o3eznqDEhRwxo7pXiAYez7keQUviUkauRiTMD8DrESdrNjN8zd9mTmVhRvBJeg5vhyvgrAhG",
);
How to verify a Keypair
keypair가 주어졌다면 당신은 secret이 주어진 public key와 일치하는지 검증할 수 있습니다.
import { Keypair, PublicKey } from "@solana/web3.js";
(async () => {
const publicKey = new PublicKey(
"24PNhTaNtomHhoy3fTRaMhAFCRj4uHqhZEEoWrKDbR5p"
);
const keypair = Keypair.fromSecretKey(
Uint8Array.from([
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56,
222, 53, 138, 189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246,
15, 185, 186, 82, 177, 240, 148, 69, 241, 227, 167, 80, 141, 89, 240, 121,
121, 35, 172, 247, 68, 251, 226, 218, 48, 63, 176, 109, 168, 89, 238, 135,
])
);
console.log(keypair.publicKey.toBase58() === publicKey.toBase58());
// true
})();
const publicKey = new PublicKey("24PNhTaNtomHhoy3fTRaMhAFCRj4uHqhZEEoWrKDbR5p");
const keypair = Keypair.fromSecretKey(
Uint8Array.from([
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56,
222, 53, 138, 189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246,
15, 185, 186, 82, 177, 240, 148, 69, 241, 227, 167, 80, 141, 89, 240, 121,
121, 35, 172, 247, 68, 251, 226, 218, 48, 63, 176, 109, 168, 89, 238, 135,
])
);
console.log(keypair.publicKey.toBase58() === publicKey.toBase58());
// true
from solana.keypair import Keypair
from solana.publickey import PublicKey
public_key = PublicKey("24PNhTaNtomHhoy3fTRaMhAFCRj4uHqhZEEoWrKDbR5p")
keys = [
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56, 222, 53, 138,
189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246, 15, 185, 186, 82, 177, 240,
148, 69, 241, 227, 167, 80, 141, 89, 240, 121, 121, 35, 172, 247, 68, 251, 226, 218, 48,
63, 176, 109, 168, 89, 238, 135,
]
keypair = Keypair.from_secret_key(bytes(keys))
print(keypair.public_key.to_base58() == public_key.to_base58())
# True
public_key = PublicKey("24PNhTaNtomHhoy3fTRaMhAFCRj4uHqhZEEoWrKDbR5p")
keys = [
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56, 222, 53, 138,
189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246, 15, 185, 186, 82, 177, 240,
148, 69, 241, 227, 167, 80, 141, 89, 240, 121, 121, 35, 172, 247, 68, 251, 226, 218, 48,
63, 176, 109, 168, 89, 238, 135,
]
keypair = Keypair.from_secret_key(bytes(keys))
print(keypair.public_key.to_base58() == public_key.to_base58())
# True
solana-keygen verify <PUBKEY> prompt://
solana-keygen verify <PUBKEY> prompt://
How to check if a public key has an associated private key
특별한 케이스 (e.g. a Program Derived Address)에서, public key들은 연관된 private key를 가지고 있지 않을지 모릅니다. 당신은 이 public key가 ed25519 곡선에 놓여있는지를 확인함으로써 이것을 체크할 수 있습니다. 이 곡선에 놓여있는 public key들은 지갑을 갖고 있는 사용자들에 의해서만 다뤄질 수 있습니다.
import { PublicKey } from "@solana/web3.js";
(async function () {
// Note that Keypair.generate() will always give a public key that is valid for users
const key = new PublicKey("5oNDL3swdJJF1g9DzJiZ4ynHXgszjAEpUkxVYejchzrY"); // Valid public key
console.log(PublicKey.isOnCurve(key.toBytes())); // Lies on the ed25519 curve and is suitable for users
const offCurveAddress = new PublicKey(
"4BJXYkfvg37zEmBbsacZjeQDpTNx91KppxFJxRqrz48e"
); // Valid public key
console.log(PublicKey.isOnCurve(offCurveAddress.toBytes())); // Not on the ed25519 curve, therefore not suitable for users
const errorPubkey = new PublicKey("testPubkey"); // Is not a valid public key
})();
const key = new PublicKey("5oNDL3swdJJF1g9DzJiZ4ynHXgszjAEpUkxVYejchzrY");
console.log(PublicKey.isOnCurve(key.toBytes()));
from solana.keypair import Keypair
from solana.publickey import PublicKey
from solana.utils.ed25519_base import is_on_curve
# Note that Keypair() will always give a public key that is valid for users
key = PublicKey('5oNDL3swdJJF1g9DzJiZ4ynHXgszjAEpUkxVYejchzrY') # Valid public key
print(is_on_curve(key)) # Lies on the ed25519 curve and is suitable for users
off_curve_address = PublicKey('4BJXYkfvg37zEmBbsacZjeQDpTNx91KppxFJxRqrz48e') # Valid public key
print(PublicKey._is_on_curve(off_curve_address)) # Not on the ed25519 curve, therefore not suitable for users
error_pubkey = PublicKey("testPubkey"); # Is not a valid public key
key = PublicKey('5oNDL3swdJJF1g9DzJiZ4ynHXgszjAEpUkxVYejchzrY')
print(is_on_curve(key))
use solana_sdk::pubkey::{Pubkey};
use std::str::FromStr;
fn main() {
// Note that Keypair::new() will always give a public key that is valid for users
let pubkey = Pubkey::from_str("5oNDL3swdJJF1g9DzJiZ4ynHXgszjAEpUkxVYejchzrY").unwrap(); // Valid public key
println!("{:?}", pubkey.is_on_curve()); // Lies on the ed25519 curve and is suitable for users
let off_curve_address = Pubkey::from_str("4BJXYkfvg37zEmBbsacZjeQDpTNx91KppxFJxRqrz48e").unwrap(); // Valid public key
println!("{:?}", off_curve_address.is_on_curve()); // Not on the ed25519 curve, therefore not suitable for users
let error_pubkey = Pubkey::from_str("testPubkey").unwrap(); // Is not a valid public key
}
let pubkey = Pubkey::from_str("5oNDL3swdJJF1g9DzJiZ4ynHXgszjAEpUkxVYejchzrY").unwrap();
println!("{:?}", pubkey.is_on_curve())
How to generate a mnemonic phrase
만약 당신이 wallet을 생성하고 있다면, 당신은 사용자들이 백업을 위해 저장할 연상 문구를 생성할 필요가 있을 것입니다.
import * as bip39 from "bip39";
const mnemonic = bip39.generateMnemonic();
const mnemonic = bip39.generateMnemonic();
from mnemonic import Mnemonic
mnemo = Mnemonic("english")
words = mnemo.generate(strength=256)
mnemo = Mnemonic("english")
words = mnemo.generate(strength=256)
solana-keygen new
solana-keygen new
How to restore a Keypair from a mnemonic phrase
많은 지갑들이 Secret key들을 대변하는 연상 구문들을 사용합니다. 당신은 이 연상 구문들을 keypair로 변환할 수 있습니다.
- BIP39 - 단일 지갑 생성
import { Keypair } from "@solana/web3.js";
import * as bip39 from "bip39";
(async () => {
const mnemonic =
"pill tomorrow foster begin walnut borrow virtual kick shift mutual shoe scatter";
const seed = bip39.mnemonicToSeedSync(mnemonic, ""); // (mnemonic, password)
const keypair = Keypair.fromSeed(seed.slice(0, 32));
console.log(`${keypair.publicKey.toBase58()}`); // 5ZWj7a1f8tWkjBESHKgrLmXshuXxqeY9SYcfbshpAqPG
})();
const mnemonic =
"pill tomorrow foster begin walnut borrow virtual kick shift mutual shoe scatter";
const seed = bip39.mnemonicToSeedSync(mnemonic, ""); // (mnemonic, password)
const keypair = Keypair.fromSeed(seed.slice(0, 32));
from solana.keypair import Keypair
from mnemonic import Mnemonic
mnemo = Mnemonic("english")
seed = mnemo.to_seed("pill tomorrow foster begin walnut borrow virtual kick shift mutual shoe scatter")
keypair = Keypair.from_secret_key(seed)
print("Created Keypair with Public Key: {}".format(keypair.public_key)
mnemo = Mnemonic("english")
seed = mnemo.to_seed("pill tomorrow foster begin walnut borrow virtual kick shift mutual shoe scatter")
keypair = Keypair.from_secret_key(seed)
solana-keygen recover
solana-keygen recover
- BIP44 (HD 지갑으로도 알려진 다중 지갑)
당신은 하나의 seed로부터 다중 지갑을 만들 수 있습니다. - 'Hierarchical Deterministic wallets' or HD wallets으로도 알려진:
import { Keypair } from "@solana/web3.js";
import { HDKey } from "micro-ed25519-hdkey";
import * as bip39 from "bip39";
(async () => {
const mnemonic =
"neither lonely flavor argue grass remind eye tag avocado spot unusual intact";
const seed = bip39.mnemonicToSeedSync(mnemonic, ""); // (mnemonic, password)
const hd = HDKey.fromMasterSeed(seed.toString("hex"));
for (let i = 0; i < 10; i++) {
const path = `m/44'/501'/${i}'/0'`;
const keypair = Keypair.fromSeed(hd.derive(path).privateKey);
console.log(`${path} => ${keypair.publicKey.toBase58()}`);
}
})();
const mnemonic =
"neither lonely flavor argue grass remind eye tag avocado spot unusual intact";
const seed = bip39.mnemonicToSeedSync(mnemonic, ""); // (mnemonic, password)
for (let i = 0; i < 10; i++) {
const path = `m/44'/501'/${i}'/0'`;
const keypair = Keypair.fromSeed(derivePath(path, seed.toString("hex")).key);
console.log(`${path} => ${keypair.publicKey.toBase58()}`);
}
solana-keygen recover 'prompt:?key=0/0'
solana-keygen recover 'prompt:?key=0/0'
How to generate a vanity address
Vanity publickeys 또는 custom addresses는 특별한 문자들로 시작하는 key들입니다. 예를들어, 어떤 사람은 publickey가 "elv1s" 또는 "cook"으로 시작하길 원할 수도 있습니다. 이것들은 다른 사람들이 이 key가 누구의 것인지 기억할 수 있게 도와줍니다. 즉 이 key를 더 쉽게 식별 가능하게 만들어 줍니다.
Note: 당신의 vanity address에 문자들이 많을수록 더 오래 걸립니다.
WARNING
이 작업을 위해서는 CLI를 사용해야 합니다. Python 과 TypeScript 예제들은 보여주기 위한 목적으로 CLI보다 훨씬 느립니다.
import { Keypair } from "@solana/web3.js";
(async () => {
let keypair = Keypair.generate();
while (!keypair.publicKey.toBase58().startsWith("elv1s")) {
keypair = Keypair.generate();
}
})();
let keypair = Keypair.generate();
while (!keypair.publicKey.toBase58().startsWith("elv1s")) {
keypair = Keypair.generate();
}
from solana.keypair import Keypair
keypair = Keypair()
while(str(keypair.public_key)[:5]!="elv1s") :
keypair = Keypair()
print("Created Keypair with Public Key: {}".format(keypair.public_key))
keypair = Keypair()
while(str(keypair.public_key)[:5]!="elv1s") :
keypair = Keypair()
solana-keygen grind --starts-with e1v1s:1
solana-keygen grind --starts-with e1v1s:1
How to sign and verify messages with wallets
keypair의 주된 기능은 message들에 서명하고 이 서명을 검증 가능하게 만드는 것입니다. 서명에 대한 검증은 수신자가 이 데이터가 특정 private key의 소유자에 의해 서명되었다는 것을 확신할 수 있게 해 줍니다.
이걸 하기 위해 우리는 TweetNaCl 라이브러리를 import 할 것입니다.
import { Keypair } from "@solana/web3.js";
import nacl from "tweetnacl";
import { decodeUTF8 } from "tweetnacl-util";
(async () => {
const keypair = Keypair.fromSecretKey(
Uint8Array.from([
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56,
222, 53, 138, 189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246,
15, 185, 186, 82, 177, 240, 148, 69, 241, 227, 167, 80, 141, 89, 240, 121,
121, 35, 172, 247, 68, 251, 226, 218, 48, 63, 176, 109, 168, 89, 238, 135,
])
);
const message = "The quick brown fox jumps over the lazy dog";
const messageBytes = decodeUTF8(message);
const signature = nacl.sign.detached(messageBytes, keypair.secretKey);
const result = nacl.sign.detached.verify(
messageBytes,
signature,
keypair.publicKey.toBytes()
);
console.log(result);
})();
const message = "The quick brown fox jumps over the lazy dog";
const messageBytes = decodeUTF8(message);
const signature = nacl.sign.detached(messageBytes, keypair.secretKey);
const result = nacl.sign.detached.verify(
messageBytes,
signature,
keypair.publicKey.toBytes()
);
console.log(result);
from nacl.signing import VerifyKey
from solana.keypair import Keypair
secret_key = [
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56, 222, 53, 138, 189, 224, 216, 117,
173, 10, 149, 53, 45, 73, 251, 237, 246, 15, 185, 186, 82, 177, 240, 148, 69, 241, 227, 167, 80, 141, 89, 240,
121, 121, 35, 172, 247, 68, 251, 226, 218, 48, 63, 176, 109, 168, 89, 238, 135,
]
keypair = Keypair.from_secret_key(bytes(secret_key))
pubkey_bytes = bytes(keypair.public_key)
message = "The quick brown fox jumps over the lazy dog"
message_bytes = bytes(message,'utf8')
signed_message = keypair.sign(message_bytes)
verify_sign = VerifyKey(
pubkey_bytes
).verify(
smessage=message_bytes,
signature=signed_message.signature
)
#Returns original message if the signature has not been tampered with
print(verify_sign)
message = "The quick brown fox jumps over the lazy dog"
message_bytes = bytes(message,'utf8')
signed_message = keypair.sign(message_bytes)
verify_sign = VerifyKey(
pubkey_bytes
).verify(
smessage=message_bytes,
signature=signed_message.signature
)
How to connect to a wallet
Solana의 wallet-adapter 라이브러리들은 client-side에서 wallet 연결 관리를 쉽게 해 줍니다.
React
요구되는 의존성들을 설치하기 위해 아래의 명령어를 실행하세요:
yarn add @solana/wallet-adapter-react @solana/wallet-adapter-react-ui @solana/wallet-adapter-base @solana/wallet-adapter-wallets
React의 wallet-adapter 라이브러리들은 hook들과 useWallet
, WalletProvider
, useConnection
, 그리고 ConnectionProvider
로 불리는 Context provider들을 통해 지갑 연결 상태를 지속하고 접근할 수 있게 해 줍니다.
추가적으로, 우리는 연결 modal의 껐다 켰다하는 useWalletModal
을 사용해 유저들이 연결하도록 유도할 수 있습니다. useWalletModal
은 @solana/wallet-adapter-react-ui
에 있는 WalletModalProvider
를 가진 앱을 감싸고 있습니다. 연결 modal은 우리가 연결 흐름을 다룰 수 있게 해 줄 것입니다. 그래서 우리는 지갑이 연결되었을 때 동안 단지 수신하면 됩니다. 우리는 userWallet
응답이 null이 아닌 wallet
속성을 가질 때, 지갑이 연결된 것을 알 수 있습니다. 반대로, 만약 이 속성이 null이라면 지갑이 연결되지 않은 것을 알 수 있습니다.
import React, { useMemo, FC, PropsWithChildren } from "react";
import {
ConnectionProvider,
WalletProvider,
} from "@solana/wallet-adapter-react";
import { WalletModalProvider } from "@solana/wallet-adapter-react-ui";
import { WalletAdapterNetwork } from "@solana/wallet-adapter-base";
import {
LedgerWalletAdapter,
PhantomWalletAdapter,
SlopeWalletAdapter,
TorusWalletAdapter,
} from "@solana/wallet-adapter-wallets";
import { clusterApiUrl } from "@solana/web3.js";
import { useWallet } from "@solana/wallet-adapter-react";
import { useWalletModal } from "@solana/wallet-adapter-react-ui";
import { MouseEventHandler } from "react";
export const Web3Provider: FC<PropsWithChildren<{}>> = ({ children }) => {
// Can be set to 'devnet', 'testnet', or 'mainnet-beta'
const endpoint = useMemo(
() => clusterApiUrl(WalletAdapterNetwork.Devnet),
[]
);
// @solana/wallet-adapter-wallets includes all the adapters but supports tree shaking --
// Only the wallets you configure here will be compiled into your application
const wallets = useMemo(
() => [
new PhantomWalletAdapter(),
new SlopeWalletAdapter(),
new TorusWalletAdapter(),
new LedgerWalletAdapter(),
],
[]
);
return (
<ConnectionProvider endpoint={endpoint}>
<WalletModalProvider>
<WalletProvider wallets={wallets}>{children}</WalletProvider>
</WalletModalProvider>
</ConnectionProvider>
);
};
/**
* Make sure to wrap the App with
* ConnectionProvider, WalletProvider, and WalletModalProvider.
*
* If you have a lot of Providers already, you can combine them
* into a single wrapper (i.e. Web3Provider) instead.
*/
export const App = () => {
return (
<Web3Provider>
<AppChild />
</Web3Provider>
);
};
const AppChild = () => {
const { wallet } = useWallet();
const { setVisible } = useWalletModal();
// Display the connection modal
const onRequestConnectWallet = () => {
setVisible(true);
};
// Prompt user to connect wallet
if (!wallet) {
return <button onClick={onRequestConnectWallet}>Connect Wallet</button>;
}
return (
<main>
<p>Wallet successfully connected!</p>
<p>{wallet.publicKey.toString()}</p>
</main>
);
};
const { wallet } = useWallet();
const { setVisible } = useWalletModal();
const onRequestConnectWallet = () => {
setVisible(true);
};
// Prompt the user to connect their wallet
if (!wallet) {
return <button onClick={onRequestConnectWallet}>Connect Wallet</button>;
}
// Displays the connected wallet address
return (
<main>
<p>Wallet successfully connected!</p>
<p>{wallet.publicKey.toBase58()}</p>
</main>
);
Vue
요구되는 의존성들을 설치하기 위해 아래의 명령어를 실행하세요:
npm install solana-wallets-vue @solana/wallet-adapter-wallets
Solana Wallets Vue 플러그인은 우리가 지갑 저장소를 초기화하고 어떤 컴포넌트 안에서도 접근할 수 있는 $wallet
글로벌 속성을 생성할 수 있게 해 줍니다. 당신이 userWallet()
을 사용해 얻을 수 있는 모든 속성과 메소드들은 여기에 나와 있습니다. 우리는 또한 WalletMultiButton 컴포넌트를 import 하고 render 할 수 있습니다. 이것은 사용자들이 연결하기 위한 지갑을 선택할 수 있게 해 줍니다.
<script setup>
import { WalletMultiButton } from "solana-wallets-vue";
import {
LedgerWalletAdapter,
PhantomWalletAdapter,
SlopeWalletAdapter,
TorusWalletAdapter,
} from "@solana/wallet-adapter-wallets";
import { initWallet, useWallet } from "solana-wallets-vue";
const wallets = {
wallets: [
new PhantomWalletAdapter(),
new SlopeWalletAdapter(),
new TorusWalletAdapter(),
new LedgerWalletAdapter(),
],
};
initWallet(wallets);
const { connected, wallet } = useWallet();
</script>
<template>
<div>
<p v-if="connected">
Wallet with public key {{ wallet.publicKey }} successfully connected!
</p>
<div v-else>
<wallet-multi-button></wallet-multi-button>
</div>
</div>
</template>
<script setup>
import { WalletMultiButton } from "solana-wallets-vue";
</script>
<template>
<wallet-multi-button></wallet-multi-button>
</template>
Svelte
요구되는 의존성들을 설치하기 위해 아래의 명령어를 실행하세요:
npm install @svelte-on-solana/wallet-adapter-core @svelte-on-solana/wallet-adapter-ui @solana/wallet-adapter-base @solana/wallet-adapter-wallets @solana/web3.js
Svelte Wallet Adapter 패키지는 프로젝트 내의 모든 JS, TS 또는/그리고 Svelte 파일들에서 접근할 수 있는 Svelte Store ($walletStore
)을 추가할 수 있게 해 줍니다. 여기 있는 레퍼런스를 사용해서 당신은 SSR 또는 SPA를 위한 어댑터를 사용할 수 있습니다. UI 패키지는 <WalletMultiButton />
컴포넌트를 포함하고 있고 이것은 사용자들이 연결할 지갑을 선택할 수 있게 해 줍니다.
<script>
import { walletStore } from "@svelte-on-solana/wallet-adapter-core";
import {
WalletProvider,
WalletMultiButton,
ConnectionProvider,
} from "@svelte-on-solana/wallet-adapter-ui";
import { clusterApiUrl } from "@solana/web3.js";
import {
PhantomWalletAdapter,
SolflareWalletAdapter,
TorusWalletAdapter,
LedgerWalletAdapter,
} from "@solana/wallet-adapter-wallets";
const localStorageKey = "walletAdapter";
const network = clusterApiUrl("devnet"); // localhost or mainnet
let wallets = [
new PhantomWalletAdapter(),
new SolflareWalletAdapter(),
new TorusWalletAdapter(),
new LedgerWalletAdapter(),
];
</script>
<WalletProvider {localStorageKey} {wallets} autoConnect />
<ConnectionProvider {network} />
{#if $walletStore?.connected} Wallet with public key {$walletStore.publicKey}
successfully connected! {:else}
<WalletMultiButton />
{/if}
<script>
import { walletStore } from "@svelte-on-solana/wallet-adapter-core";
import { WalletMultiButton } from "@svelte-on-solana/wallet-adapter-ui";
</script>
{#if $walletStore?.connected} Wallet with public key {$walletStore.publicKey}
successfully connected! {:else}
<WalletMultiButton />
{/if}