개인 잔액 간에 SOL, SPL 또는 Token 2022 자산을 전송하는 가이드와 전체 코드 예제.
개인 전송은 개인 지갑 간에 링 속에서 토큰을 이동시킵니다.
개인 전송은 단일 Solana 거래로 Solana 지갑 주소로 송신됩니다.
전송: 무엇이 비공개인지
Default Ring
Custom Rings
필드
공개 여부
자산
비공개. 온체인에서 암호화됩니다.
금액
비공개. 온체인에서 암호화됩니다.
송신자
공개. 기본 링은 기밀입니다.
수신자
공개. 기본 링은 기밀입니다.
메모(선택 사항)
비공개. 온체인에서 암호화됩니다.
전송
자산
금액
송신자
수신자
메모(선택 사항)
사용자 지정 기밀 링 내에서
비공개
비공개
공개
공개
비공개
사용자 지정 익명 링 내에서
비공개
비공개
비공개
비공개
비공개
기본 링에서 사용자 지정 기밀 링으로 또는 그 반대로
비공개
비공개
공개
공개
비공개
기밀 링에서 사용자 지정 익명 링으로
비공개
비공개
공개
비공개
비공개
사용자 지정 익명 링에서 기밀 링으로
비공개
비공개
비공개
공개
비공개
릴레이어가 익명 링의 전송을 제출하므로 공개 원장에는 송금 출처인 비공개 지갑이 드러나지 않습니다. 사용자 지정 링 프로그램 ID는 공개 상태로 유지됩니다.링 간 전송은 출발 링의 정책을 따라야 합니다. 하나의 트랜잭션에서 기본 링과 하나의 사용자 지정 링에 있는 잔액을 결합할 수 있습니다. 두 사용자 지정 링 간의 전송은 기본 링을 거칩니다.
허가 없는 링은 금액과 자산이 암호화되어 기밀로 유지됩니다.
사용자 정의 링은 기밀 또는 익명으로 구성할 수 있습니다 (발신자, 수신자, 자산 및 금액이 암호화됨).
전송이 작동하는 방법
개인 전송은 공공 Solana 전송과 유사하게 작동합니다:
사용자의 SOL 또는 SPL 잔액이 온체인에서 암호화됩니다.
사용자는 개인 상태를 해독하고, 지갑은 전송을 생성하며, 소유자는 서명합니다.
전용 RPC 방법으로 암호화된 상태를 가져옵니다. 사용자는 로컬에서만 잔액을 해독할 수 있습니다.
지갑은 금액과 수신자를 설정한 후 ZK 증명을 요청합니다. RPC 제공자는 기본적으로 ZK 증명을 생성하여 반환합니다.
Solana 런타임은 서명을 검증하고 Solana 프라이버시 프로그램을 호출하여 암호화된 상태를 공개하지 않고 ZK 증명을 검증합니다.
앱은 Solana 거래 해시를 통해 상태를 추적합니다.
Solana 전송과 비교
사용자의 SOL 또는 SPL 잔액은 온체인에서 공개됩니다.
지갑은 공개 상태를 읽고 전송을 생성하며, 소유자는 서명합니다.
Solana 런타임은 서명을 검증하고 시스템 프로그램 또는 토큰 프로그램을 호출하여 공개 잔액을 업데이트합니다.
앱은 Solana 거래 해시를 통해 상태를 추적합니다.
다음은 무허가형 기밀 Ring의 상위 수준 트랜잭션 흐름입니다.
상위 수준 트랜잭션 흐름에서 커스텀 Ring과 비교해 보세요.
시작하기
TypeScript 클라이언트
Rust Client
1
사전 준비 사항
TypeScript 예제는 Node.js 24 이상, pnpm 11.18.0, 그리고 Solana CLI가 필요합니다.
import { SOL_MINT, ShieldedKeypair, createSprClient,} from "@heliuslabs/spr";import { LocalKeys, atSlot,} from "@heliuslabs/spr/client";import { depositInstruction, transactInstruction, DepositAsset, TransactWithdrawal,} from "@heliuslabs/spr/interface";import { AssetRegistry, ConfidentialTransfer, ProofInputUtxo, decryptToBalances, WithdrawalTarget,} from "@heliuslabs/spr/transaction";import { cliKeypair, sendAndConfirmFactory, setup,} from "../src/lib.js";const DEPOSIT_AMOUNT = 10_000_000n;const TRANSFER_AMOUNT = 3_000_000n;const WITHDRAW_AMOUNT = 3_000_000n;async function main(): Promise<void> { const { clientConfig } = await setup(); const client = await createSprClient(clientConfig); // localnet: const client = await createZolanaClient({}); // Initialize the sender's private wallet and local authority // to decrypt transactions and sync balances. // The Solana signer and private wallet are derived from the same Ed25519 seed. const sender = ShieldedKeypair.fromKeypair( await cliKeypair(), ); const recipient = ShieldedKeypair.generate(); const senderSigner = sender.toSolanaSigner(); const senderAddress = sender.shieldedAddress(); const senderKeys = LocalKeys.fromKeypair( sender, client.proofService, ); // The SDK hands back instructions; the app owns signing and sending. const sendAndConfirm = sendAndConfirmFactory( client, senderSigner, ); // Mints that are registered with Solana Privacy Rings for privacy. const assets = new AssetRegistry(); // Deposit SOL into the sender's private balance. // A deposit from a public balance reveals // sender, recipient, asset and amount. // Alternatively, you can onramp fiat directly to a private balance. // 1. Move public SOL into the sender's private balance. // The view tag is the sender's Solana public key in confidential rings. // Used by the indexer to fetch the sender's outputs. const senderViewTag = senderAddress.confidentialViewTag(); const depositIx = await depositInstruction({ tree: client.tree, depositor: senderSigner, deposits: [ { asset: DepositAsset.sol(), viewTag: senderViewTag, recipientOwnerHash: senderAddress.ownerHash(), amount: DEPOSIT_AMOUNT, }, ], }); // 2. Send and confirm like any Solana transaction; confirmation yields the landed slot. const depositTx = await sendAndConfirm([ depositIx, ]); // 3. Fetch this transaction's outputs, gated on its confirmed slot. const depositResponse = await client.getShieldedTransactionsBySignature( depositTx.signature, atSlot(depositTx.slot), ); // 4. The sender decrypts the transaction outputs locally to read the funds deposited in this run. const balancesAfterDeposit = await decryptToBalances({ keypair: sender, registry: assets, transactions: depositResponse.transactions.map( ({ transaction }) => transaction, ), }); const depositBalance = balancesAfterDeposit.balance(SOL_MINT); if (depositBalance.amount !== DEPOSIT_AMOUNT) { throw new Error( `expected deposit amount ${DEPOSIT_AMOUNT}, got ${depositBalance.amount}`, ); } if (depositBalance.utxos.length !== 1) { throw new Error( `expected 1 deposit utxo, got ${depositBalance.utxos.length}`, ); } // Confidential SOL transfer to the recipient's private balance. // A confidential transfer reveals only sender and recipient, // not the asset or amount. // 1. Select private token accounts (UTXOs) that make up the private balance for the transfer. const transferUtxo = depositBalance.utxos[0]!; // 2. Prepare the selected UTXOs as inputs for the zero-knowledge proof. const transferInput = ProofInputUtxo.fromKeypair( transferUtxo, sender, ); // 3. Build and sign the confidential transfer. // Signing encrypts the asset and amount and produces the proof inputs for the ZK prover. const transfer = new ConfidentialTransfer( senderAddress, [transferInput], senderSigner.address, ); transfer.send( recipient.shieldedAddress(), SOL_MINT, TRANSFER_AMOUNT, ); const transferProofInputs = transfer.sign( sender, assets, ); // 4. Fetch the ZK proof to prove the sender can spend the balance without revealing asset and amount. const transferData = await client.proveTransact( transferProofInputs, senderKeys, ); // 5. Build the instruction with the state Merkle tree and Solana accounts required for the transfer. // Private transfers move balances only between private token accounts, not public token accounts. const transferInstruction = await transactInstruction({ payer: senderSigner, ownerSigners: [senderSigner], inputTree: client.tree, outputTree: client.tree, data: transferData, }); // 6. Send and confirm like any Solana transaction; confirmation yields the landed slot. const transferTx = await sendAndConfirm([ transferInstruction, ]); // 7. Fetch this transaction's outputs, gated on its confirmed slot. const transferResponse = await client.getShieldedTransactionsBySignature( transferTx.signature, atSlot(transferTx.slot), ); const balancesAfterTransfer = await decryptToBalances({ keypair: sender, registry: assets, transactions: transferResponse.transactions.map( ({ transaction }) => transaction, ), }); const transferBalance = balancesAfterTransfer.balance(SOL_MINT); if ( transferBalance.amount !== DEPOSIT_AMOUNT - TRANSFER_AMOUNT ) { throw new Error( `expected remaining amount from this run ${DEPOSIT_AMOUNT - TRANSFER_AMOUNT}, got ${transferBalance.amount}`, ); } if (transferBalance.utxos.length !== 1) { throw new Error( `expected 1 transfer utxo, got ${transferBalance.utxos.length}`, ); } // Withdraw SOL from the sender's private balance to their public balance. // A withdrawal reveals the sender, recipient, asset, and amount. // 1. Select private token accounts (UTXOs) that make up the private balance for the withdrawal. const withdrawalUtxo = transferBalance.utxos[0]!; // 2. Prepare the selected UTXOs as inputs for the zero-knowledge proof. const withdrawalInput = ProofInputUtxo.fromKeypair( withdrawalUtxo, sender, ); // 3. Build and sign the private-to-public withdrawal. // Signing encrypts the asset and amount of the remaining private balance // and produces the proof inputs for the ZK prover. const withdrawal = new ConfidentialTransfer( senderAddress, [withdrawalInput], senderSigner.address, ); withdrawal.withdraw( SOL_MINT, WITHDRAW_AMOUNT, WithdrawalTarget.sol({ recipient: senderSigner.address, }), ); const withdrawalProofInputs = withdrawal.sign( sender, assets, ); // 4. Fetch the ZK proof to prove the sender can spend the balance. const withdrawalData = await client.proveTransact( withdrawalProofInputs, senderKeys, ); // 5. Build the instruction with the state Merkle tree and Solana accounts required for the withdrawal. const withdrawalInstruction = await transactInstruction({ payer: senderSigner, ownerSigners: [senderSigner], inputTree: client.tree, outputTree: client.tree, withdrawal: TransactWithdrawal.sol({ recipient: senderSigner.address, }), data: withdrawalData, }); // 6. Send and confirm like any Solana transaction; confirmation yields the landed slot. const withdrawalTx = await sendAndConfirm([ withdrawalInstruction, ]); // 7. Fetch this transaction's outputs, gated on its confirmed slot. const withdrawalResponse = await client.getShieldedTransactionsBySignature( withdrawalTx.signature, atSlot(withdrawalTx.slot), ); const balancesAfterWithdrawal = await decryptToBalances({ keypair: sender, registry: assets, transactions: withdrawalResponse.transactions.map( ({ transaction }) => transaction, ), }); const withdrawalBalance = balancesAfterWithdrawal.balance(SOL_MINT); if ( withdrawalBalance.amount !== DEPOSIT_AMOUNT - TRANSFER_AMOUNT - WITHDRAW_AMOUNT ) { throw new Error( `expected remaining amount from this run ${DEPOSIT_AMOUNT - TRANSFER_AMOUNT - WITHDRAW_AMOUNT}, got ${withdrawalBalance.amount}`, ); } if (withdrawalBalance.utxos.length !== 1) { throw new Error( `expected 1 withdrawal utxo, got ${withdrawalBalance.utxos.length}`, ); } // 8. Read remaining private balance and the public balance. const solanaBalance = await client.getBalance( senderSigner.address, ); console.log( `withdraw private_balance=${withdrawalBalance.amount} ` + `solana_balance=${solanaBalance} tx=${withdrawalTx.signature}`, );}await main();
use spr_transaction::SOL_MINT;let transfer_utxo = sender_balances_after_deposit .get_balance(SOL_MINT) // SPL: .get_balance(spl.mint) .and_then(|balance| balance.utxos.first()) .expect("failed to fetch deposited utxo") .clone();
이 예제에서는 입력 UTXO를 수동으로 선택합니다. Rust SDK의 지갑 헬퍼를 사용하면 UTXO를 자동으로 선택할 수 있습니다. 앱은 대기 중인 전송에서 사용된 UTXO를 추적해야 합니다. 입력 선택 지침은 UTXO 선택을 참고하세요.
이 예제는 앞선 입금에서 생성된 프라이빗 Solana 토큰 계정을 사용합니다. 하나의 전송에서 여러 UTXO를 사용할 수 있습니다.
transfer_utxo는 해당 자산에 사용할 수 있는 첫 번째 UTXO입니다. // SPL: 주석은 get_balance(spl.mint)를 보여 줍니다.
2. Prepare proof inputs
use zolana_transaction::instructions::transact::ConfidentialTransaction;let mut transfer = ConfidentialTransaction::new(vec![transfer_utxo], sender.pubkey())?;
use anyhow::{anyhow, Result};use rust_client_example::{cli_keypair, landed_slot, setup};use solana_address::Address;use solana_keypair::Keypair;use solana_signer::Signer;use zolana_client::{IndexerRpcConfig, Rpc, SolanaRpc, ZolanaClient};use zolana_keypair::ShieldedKeypair;use zolana_program::instruction::{ AssetDeposit, Deposit, DepositAsset, Transact, TransactInterfaceTransferAccounts, TransactSolTransferAccounts,};use zolana_transaction::{ decrypt_spendable, instructions::transact::ConfidentialTransaction, AssetRegistry, SOL_MINT,};const DEPOSIT_AMOUNT: u64 = 10_000_000;const TRANSFER_AMOUNT: u64 = 3_000_000;const WITHDRAW_AMOUNT: u64 = 3_000_000;fn main() -> Result<()> { let context = setup()?; let client = context.client()?; run(&client, context.tree, &cli_keypair()?)}pub fn run(client: &ZolanaClient<SolanaRpc>, tree: Address, payer: &Keypair) -> Result<()> { // Mints that are registered with Solana Privacy Rings for privacy. let assets = AssetRegistry::default(); // SPL: assets.insert(spl.asset_id, spl.mint)?; // Initialize the sender's private wallet and local authority // to decrypt transactions and sync balances. // The Solana signer and private wallet are derived from the same Ed25519 seed. let sender = ShieldedKeypair::from_keypair(payer)?; let recipient = ShieldedKeypair::from_keypair(&Keypair::new())?; let sender_shielded_address = sender.shielded_address()?; // Deposit SOL into the sender's private balance. // A deposit from a public balance reveals // sender, recipient, asset and amount. // Alternatively, you can onramp fiat directly to a private balance. // 1. Move public SOL into the sender's private balance. let sender_balances_after_deposit = { let deposit_ix = Deposit { tree, depositor: sender.pubkey(), deposits: vec![AssetDeposit { asset: DepositAsset::Sol, // SPL: asset: DepositAsset::Spl(zolana_program::instruction::DepositSplAccounts { // SPL: mint: spl.mint, // SPL: user_token: spl.user_token_account, // SPL: token_program: spl.token_program, // SPL: }), view_tag: sender_shielded_address.confidential_view_tag()?, owner: sender_shielded_address.owner_hash()?, amount: DEPOSIT_AMOUNT, memo: None, }], } .instruction()?; // 2. Send and confirm like any Solana transaction; the landed slot gates // the indexer fetch below. let signature = client.create_and_send_transaction( &[deposit_ix], sender.pubkey(), &[&sender], client.compute_budget(), )?; let slot = landed_slot(client, signature)?; // 3. Fetch this transaction's outputs, gated on its confirmed slot. let response = client.get_shielded_transactions_by_signature( signature, Some(IndexerRpcConfig::at_slot(slot)), )?; let transactions = response .transactions .into_iter() .map(|indexed| indexed.transaction) .collect::<Vec<_>>(); // 4. The sender decrypts the transaction outputs locally to read the funds deposited in this run. let balances = decrypt_spendable(&sender, &transactions, &assets) .map_err(|e| anyhow!("decrypt sender transactions: {e:?}"))? .balances; let sender_balance = balances .get_balance(SOL_MINT) // SPL: .get_balance(spl.mint) .expect("failed to fetch sender's utxo"); assert_eq!(sender_balance.amount, DEPOSIT_AMOUNT); assert_eq!(sender_balance.utxos.len(), 1); balances }; // Confidential SOL transfer to the recipient's private balance. // A confidential transfer reveals only sender and recipient, // not the asset or amount. let sender_balances_after_transfer = { // 1. Select UTXOs that make up the private balance for the transfer. let transfer_utxo = sender_balances_after_deposit .get_balance(SOL_MINT) // SPL: .get_balance(spl.mint) .and_then(|balance| balance.utxos.first()) .expect("failed to fetch deposited utxo") .clone(); // 2. Prepare the selected UTXOs as inputs for the zero-knowledge proof. let mut transfer = ConfidentialTransaction::new(vec![transfer_utxo], sender.pubkey())?; // 3. Build and encrypt the confidential transfer. // Encryption hides the asset and amount and produces the proof inputs for the ZK prover. transfer.transfer_sol(&recipient.shielded_address()?, TRANSFER_AMOUNT)?; // SPL: transfer.transfer(&recipient.shielded_address()?, spl.mint, TRANSFER_AMOUNT)?; let proof_inputs = transfer.encrypt(&sender)?; // 4. Fetch the zk proof to prove the sender can spend the balance without revealing asset and amount. let transfer_data = client.prove_transact(proof_inputs, None, &sender)?; // 5. Construct the instruction. let transfer_ix = Transact { payer: sender.pubkey(), input_trees: vec![tree], output_tree: tree, owner_signers: vec![sender.pubkey()], interface_transfer_accounts: Vec::new(), data: transfer_data, } .instruction(); // 6. Send and confirm like any Solana transaction; confirmation yields the landed slot. let signature = client.create_and_send_transaction( &[transfer_ix], sender.pubkey(), &[&sender], client.compute_budget(), )?; let slot = landed_slot(client, signature)?; // 7. Fetch this transaction's outputs, gated on its confirmed slot. let response = client.get_shielded_transactions_by_signature( signature, Some(IndexerRpcConfig::at_slot(slot)), )?; let transactions = response .transactions .into_iter() .map(|indexed| indexed.transaction) .collect::<Vec<_>>(); let sender_balances = decrypt_spendable(&sender, &transactions, &assets) .map_err(|e| anyhow!("decrypt sender transactions: {e:?}"))? .balances; let sender_balance = sender_balances .get_balance(SOL_MINT) // SPL: .get_balance(spl.mint) .expect("failed to fetch sender's utxo"); assert_eq!(sender_balance.amount, DEPOSIT_AMOUNT - TRANSFER_AMOUNT); assert_eq!(sender_balance.utxos.len(), 1); sender_balances }; // Withdraw SOL back to the sender's public balance. // A withdrawal from a confidential balance reveals // sender, recipient, asset and amount. { // 1. Select UTXOs that make up the private balance for the withdrawal. let withdrawal_utxo = sender_balances_after_transfer .get_balance(SOL_MINT) // SPL: .get_balance(spl.mint) .and_then(|balance| balance.utxos.first()) .expect("failed to fetch sender's utxo") .clone(); // 2. Prepare the selected UTXOs as inputs for the zero-knowledge proof. let mut withdrawal = ConfidentialTransaction::new(vec![withdrawal_utxo], sender.pubkey())?; // 3. Build and encrypt the confidential withdrawal. // Encryption hides the private change and produces the ZK prover inputs. withdrawal.withdraw_sol(WITHDRAW_AMOUNT, sender.pubkey())?; // SPL: withdrawal.withdraw(spl.mint, WITHDRAW_AMOUNT, spl.user_token_account)?; let proof_inputs = withdrawal.encrypt(&sender)?; // 4. Fetch the ZK proof to prove the sender can spend the balance. let withdrawal_data = client.prove_transact(proof_inputs, None, &sender)?; // 5. Combine the proof and withdrawal accounts in a single instruction. let withdraw_ix = Transact { payer: sender.pubkey(), input_trees: vec![tree], output_tree: tree, owner_signers: vec![sender.pubkey()], interface_transfer_accounts: vec![TransactInterfaceTransferAccounts::Sol( TransactSolTransferAccounts { recipient: sender.pubkey(), }, )], // SPL: interface_transfer_accounts: vec![ // SPL: TransactInterfaceTransferAccounts::SplWithdrawal( // SPL: zolana_program::instruction::TransactSplWithdrawalAccounts { // SPL: mint: spl.mint, // SPL: spl_interface: spl.vault, // SPL: user_token_account: spl.user_token_account, // SPL: token_program: spl.token_program, // SPL: }, // SPL: ), // SPL: ], data: withdrawal_data, } .instruction(); // 6. Send and confirm like any Solana transaction. let signature = client.create_and_send_transaction( &[withdraw_ix], sender.pubkey(), &[&sender], client.compute_budget(), )?; let slot = landed_slot(client, signature)?; // 7. Fetch this transaction's outputs, gated on its confirmed slot. let response = client.get_shielded_transactions_by_signature( signature, Some(IndexerRpcConfig::at_slot(slot)), )?; let transactions = response .transactions .into_iter() .map(|indexed| indexed.transaction) .collect::<Vec<_>>(); let sender_balances = decrypt_spendable(&sender, &transactions, &assets) .map_err(|e| anyhow!("decrypt sender transactions: {e:?}"))? .balances; let sender_balance = sender_balances .get_balance(SOL_MINT) // SPL: .get_balance(spl.mint) .expect("failed to fetch sender's utxo"); assert_eq!( sender_balance.amount, DEPOSIT_AMOUNT - TRANSFER_AMOUNT - WITHDRAW_AMOUNT ); assert_eq!(sender_balance.utxos.len(), 1); // 8. Read the funds remaining from this run and the public SOL balance. let solana_balance = client.get_balance(sender.pubkey())?; println!("withdraw solana_balance={solana_balance} tx={signature}"); // SPL: println!( // SPL: "withdraw user_token={} tx={signature}", // SPL: spl.user_token_account, // SPL: ); } Ok(())}