스케일된 UI 금액

Scaled UI Amount 확장이란?

Token Extensions Program의 ScaledUiAmount 민트 확장은 토큰 잔액에 표시되는 UI 금액에 업데이트 가능한 승수를 적용할 수 있게 해줍니다.

이는 토큰이 주식 분할이나 배당금과 같은 실물 자산이나 금융 상품을 나타낼 때 유용합니다. 예를 들어, 주식 분할은 모든 보유자의 주식 수를 두 배로 늘립니다. 모든 token account 잔액을 변경하지 않고도, *rsScaledUiAmount*를 사용하면 지갑과 애플리케이션이 민트의 승수를 사용하여 새로운 UI 금액을 표시할 수 있습니다.

이 기능은 배당금이나 수익 분배에도 사용될 수 있습니다.

새로운 토큰은 생성되지 않습니다. token account에 저장된 토큰 금액은 그대로 유지됩니다. 표시되는 UI 금액만 변경됩니다.

호환되지 않는 확장

동일한 민트에 _rsScaledUiAmount_와 _rsInterestBearingConfig_를 함께 활성화하지 마세요. Token Extensions Program은 해당 확장 조합을 거부합니다.

Scaled UI Amount 작동 방식

  • *rsScaledUiAmountConfig*는 업데이트 권한, multiplier, new_multiplier, new_multiplier_effective_timestamp를 저장합니다.
  • new_multiplier_effective_timestamp 이전에는 변환에 multiplier를 사용합니다. 해당 타임스탬프 시점 또는 이후에는 변환에 new_multiplier를 사용합니다.
  • *rsUpdateMultiplier*는 새로운 승수를 즉시 적용하거나 미래의 Unix 타임스탬프로 예약할 수 있습니다.
  • AmountToUiAmount, UiAmountToAmount, 그리고 확장 변환 헬퍼는 scaled UI amount 민트에 대해 부동 소수점 연산을 사용하므로, 변환이 정확하게 왕복 변환되는 것이 보장되지 않습니다.

Scaled UI Amount 사용 방법

Scaled UI Amount를 사용하려면:

  1. 민트 및 ScaledUiAmount 확장에 필요한 민트 계정 크기와 rent를 계산합니다.
  2. *rsCreateAccount*로 민트 계정을 생성하고, *rsScaledUiAmount*를 초기화한 다음, *rsInitializeMint*로 민트를 초기화합니다.
  3. 잔액을 표시하거나 UI 금액을 변환할 때 AmountToUiAmount, UiAmountToAmount, 또는 클라이언트 헬퍼를 사용합니다.
  4. *rsUpdateMultiplier*를 사용하여 표시되는 승수를 즉시 또는 미래의 Unix 타임스탬프에 업데이트합니다.

명령어 순서

_rsScaledUiAmountMintInstruction::Initialize_는 _rsInitializeMint_보다 먼저 실행되어야 합니다. CreateAccount, ScaledUiAmountMintInstruction::Initialize, 그리고 _rsInitializeMint_는 동일한 트랜잭션에 포함되어야 합니다.

가이드

소스 참조

항목설명소스
ScaledUiAmountConfig권한, 현재 승수, 다음 승수 및 적용 시점의 타임스탬프를 저장하는 민트 확장 상태입니다.소스
ScaledUiAmountMintInstruction::InitializeInitializeMint 이전에 민트에서 *rsScaledUiAmount*를 초기화하는 명령어입니다.소스
ScaledUiAmountMintInstruction::UpdateMultiplier새로운 승수와 그것이 적용되는 Unix 타임스탬프를 설정하는 명령어입니다.소스
amount_to_ui_amount현재 승수, 소수점 자릿수 및 타임스탬프를 사용하여 토큰 수량을 UI 수량 문자열로 변환하는 헬퍼입니다.소스
try_ui_amount_into_amount현재 승수, 소수점 자릿수 및 타임스탬프를 사용하여 UI 수량 문자열을 토큰 수량으로 다시 변환하는 헬퍼입니다.소스
process_initialize*rsScaledUiAmountConfig*를 초기화하고 초기화되지 않은 민트에 초기 승수를 저장하는 프로세서입니다.소스
process_update_multiplier권한을 검증하고, 예정된 승수를 업데이트하며, 적절한 경우 즉시 적용하는 프로세서입니다.소스
process_amount_to_ui_amount민트에 확장이 활성화되어 있을 때 *rsScaledUiAmountConfig*를 사용하는 Token Program 변환 경로입니다.소스
process_ui_amount_to_amountScaled UI Amount 민트를 위해 UI 수량을 토큰 수량으로 다시 변환하는 Token Program 변환 경로입니다.소스

Typescript

아래의 Kit 예제는 생성된 명령어를 직접 사용합니다. @solana/web3.js@solana/spl-token를 사용하는 레거시 예제는 참고용으로 포함되어 있습니다.

Kit

Instructions
import {
lamports,
createClient,
generateKeyPairSigner,
unwrapOption
} from "@solana/kit";
import { solanaRpc, rpcAirdrop } from "@solana/kit-plugin-rpc";
import { generatedPayer, airdropPayer } from "@solana/kit-plugin-signer";
import { getCreateAccountInstruction } from "@solana-program/system";
import {
amountToUiAmountForMintWithoutSimulation,
extension,
fetchMint,
findAssociatedTokenPda,
getCreateAssociatedTokenInstructionAsync,
getInitializeMintInstruction,
getInitializeScaledUiAmountMintInstruction,
getMintSize,
getMintToCheckedInstruction,
getUpdateMultiplierScaledUiMintInstruction,
isExtension,
TOKEN_2022_PROGRAM_ADDRESS
} from "@solana-program/token-2022";
const client = await createClient()
.use(generatedPayer())
.use(
solanaRpc({
rpcUrl: "http://localhost:8899",
rpcSubscriptionsUrl: "ws://localhost:8900"
})
)
.use(rpcAirdrop())
.use(airdropPayer(lamports(1_000_000_000n)));
const mint = await generateKeyPairSigner();
const recipient = await generateKeyPairSigner();
const initialMultiplier = 5.0;
const updatedMultiplier = 10.0;
const tokenAmount = 1_000n;
const scaledUiAmountExtension = extension("ScaledUiAmountConfig", {
authority: client.payer.address,
multiplier: initialMultiplier,
newMultiplierEffectiveTimestamp: 0n,
newMultiplier: initialMultiplier
});
const mintSpace = BigInt(getMintSize([scaledUiAmountExtension]));
const mintRent = await client.rpc
.getMinimumBalanceForRentExemption(mintSpace)
.send();
await client.sendTransaction([
getCreateAccountInstruction({
payer: client.payer, // Account funding the new mint account.
newAccount: mint, // New mint account to create.
lamports: mintRent, // Lamports funding the mint account rent.
space: mintSpace, // Account size in bytes for the mint plus ScaledUiAmountConfig.
programAddress: TOKEN_2022_PROGRAM_ADDRESS // Program that owns the mint account.
}),
getInitializeScaledUiAmountMintInstruction({
mint: mint.address, // Mint account that stores the ScaledUiAmountConfig extension.
authority: client.payer.address, // Authority allowed to update the multiplier later.
multiplier: initialMultiplier // Initial multiplier used for displayed UI amounts.
}),
getInitializeMintInstruction({
mint: mint.address, // Mint account to initialize.
decimals: 0, // Number of decimals for the token.
mintAuthority: client.payer.address, // Authority allowed to mint new tokens.
freezeAuthority: client.payer.address // Authority allowed to freeze token accounts.
})
]);
const [tokenAccount] = await findAssociatedTokenPda({
mint: mint.address,
owner: recipient.address,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS
});
await client.sendTransaction([
await getCreateAssociatedTokenInstructionAsync({
payer: client.payer, // Account funding the associated token account creation.
mint: mint.address, // Mint for the associated token account.
owner: recipient.address // Owner of the token account.
}),
getMintToCheckedInstruction({
mint: mint.address, // Mint account that issues the tokens.
token: tokenAccount, // Token account receiving the newly minted tokens.
mintAuthority: client.payer, // Signer authorized to mint new tokens.
amount: tokenAmount, // Token amount in base units.
decimals: 0 // Decimals defined on the mint.
})
]);
const calculatedUiAmountBeforeUpdate =
await amountToUiAmountForMintWithoutSimulation(
client.rpc,
mint.address,
tokenAmount
);
const updateMultiplierInstruction = getUpdateMultiplierScaledUiMintInstruction({
mint: mint.address, // Mint account that stores the ScaledUiAmountConfig extension.
authority: client.payer, // Signer authorized to update the multiplier.
multiplier: updatedMultiplier, // New multiplier used for displayed UI amounts.
effectiveTimestamp: 0n // Unix timestamp when the new multiplier takes effect.
});
await client.sendTransaction([updateMultiplierInstruction]);
const calculatedUiAmountAfterUpdate =
await amountToUiAmountForMintWithoutSimulation(
client.rpc,
mint.address,
tokenAmount
);
const mintAccount = await fetchMint(client.rpc, mint.address);
const scaledUiAmountConfig = (
unwrapOption(mintAccount.data.extensions) ?? []
).find((item) => isExtension("ScaledUiAmountConfig", item));
console.log("Mint Address:", mint.address);
console.log("Token Account:", tokenAccount);
console.log(
"Calculated UI Amount Before Update:",
calculatedUiAmountBeforeUpdate
);
console.log(
"Calculated UI Amount After Update:",
calculatedUiAmountAfterUpdate
);
console.log("ScaledUiAmountConfig:", scaledUiAmountConfig);
Console
Click to execute the code.

Web3.js

Instructions
import {
Connection,
Keypair,
PublicKey,
sendAndConfirmTransaction,
SystemProgram,
Transaction,
LAMPORTS_PER_SOL
} from "@solana/web3.js";
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
createAssociatedTokenAccountInstruction,
createInitializeMintInstruction,
createInitializeScaledUiAmountConfigInstruction,
createMintToCheckedInstruction,
createUpdateMultiplierDataInstruction,
ExtensionType,
getAssociatedTokenAddressSync,
getMint,
getMintLen,
getScaledUiAmountConfig,
TOKEN_2022_PROGRAM_ID
} from "@solana/spl-token";
async function calculateScaledUiAmount(
connection: Connection,
mintPublicKey: PublicKey,
tokenAmount: bigint
) {
const mintAccount = await getMint(
connection,
mintPublicKey,
"confirmed",
TOKEN_2022_PROGRAM_ID
);
const scaledUiAmountConfig = getScaledUiAmountConfig(mintAccount);
if (!scaledUiAmountConfig) {
throw new Error("ScaledUiAmountConfig not found");
}
const clockAccount = await connection.getParsedAccountInfo(
new PublicKey("SysvarC1ock11111111111111111111111111111111")
);
if (
!clockAccount.value ||
typeof clockAccount.value.data !== "object" ||
!("parsed" in clockAccount.value.data)
) {
throw new Error("Failed to fetch clock sysvar");
}
const unixTimestamp = Number(
clockAccount.value.data.parsed.info.unixTimestamp
);
const multiplier =
unixTimestamp >=
Number(scaledUiAmountConfig.newMultiplierEffectiveTimestamp)
? scaledUiAmountConfig.newMultiplier
: scaledUiAmountConfig.multiplier;
const scaledAmount = Math.trunc(Number(tokenAmount) * multiplier);
const calculatedUiAmount = scaledAmount / 10 ** mintAccount.decimals;
return {
calculatedUiAmount: calculatedUiAmount.toString(),
scaledUiAmountConfig
};
}
const connection = new Connection("http://localhost:8899", "confirmed");
const feePayer = Keypair.generate();
const recipient = Keypair.generate();
const initialMultiplier = 5.0;
const updatedMultiplier = 10.0;
const tokenAmount = 1_000n;
const airdropSignature = await connection.requestAirdrop(
feePayer.publicKey,
2 * LAMPORTS_PER_SOL
);
await connection.confirmTransaction(airdropSignature, "confirmed");
const mint = Keypair.generate();
const mintLength = getMintLen([ExtensionType.ScaledUiAmountConfig]);
const mintRent = await connection.getMinimumBalanceForRentExemption(mintLength);
const tokenAccount = getAssociatedTokenAddressSync(
mint.publicKey,
recipient.publicKey,
false,
TOKEN_2022_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID
);
const createMintAccountInstruction = SystemProgram.createAccount({
fromPubkey: feePayer.publicKey, // Account funding the new mint account.
newAccountPubkey: mint.publicKey, // New mint account to create.
space: mintLength, // Account size in bytes for the mint plus ScaledUiAmountConfig.
lamports: mintRent, // Lamports funding the mint account rent.
programId: TOKEN_2022_PROGRAM_ID // Program that owns the mint account.
});
const initializeScaledUiAmountInstruction =
createInitializeScaledUiAmountConfigInstruction(
mint.publicKey, // Mint account that stores the ScaledUiAmountConfig extension.
feePayer.publicKey, // Authority allowed to update the multiplier later.
initialMultiplier, // Initial multiplier used for displayed UI amounts.
TOKEN_2022_PROGRAM_ID // Token program that owns the mint.
);
const initializeMintInstruction = createInitializeMintInstruction(
mint.publicKey, // Mint account to initialize.
0, // Number of decimals for the token.
feePayer.publicKey, // Authority allowed to mint new tokens.
feePayer.publicKey, // Authority allowed to freeze token accounts.
TOKEN_2022_PROGRAM_ID // Program that owns the mint account.
);
await sendAndConfirmTransaction(
connection,
new Transaction().add(
createMintAccountInstruction,
initializeScaledUiAmountInstruction,
initializeMintInstruction
),
[feePayer, mint]
);
const createTokenAccountInstruction = createAssociatedTokenAccountInstruction(
feePayer.publicKey, // Account funding the associated token account creation.
tokenAccount, // Associated token account address to create.
recipient.publicKey, // Owner of the token account.
mint.publicKey, // Mint for the associated token account.
TOKEN_2022_PROGRAM_ID, // Token program that owns the token account.
ASSOCIATED_TOKEN_PROGRAM_ID // Associated Token Program that creates the account.
);
const mintToTokenAccountInstruction = createMintToCheckedInstruction(
mint.publicKey, // Mint account that issues the tokens.
tokenAccount, // Token account receiving the newly minted tokens.
feePayer.publicKey, // Signer authorized to mint new tokens.
tokenAmount, // Token amount in base units.
0, // Decimals defined on the mint.
[], // Additional multisig signers.
TOKEN_2022_PROGRAM_ID // Token program that owns the mint and token account.
);
await sendAndConfirmTransaction(
connection,
new Transaction().add(
createTokenAccountInstruction,
mintToTokenAccountInstruction
),
[feePayer]
);
const { calculatedUiAmount: calculatedUiAmountBeforeUpdate } =
await calculateScaledUiAmount(connection, mint.publicKey, tokenAmount);
const updateMultiplierInstruction = createUpdateMultiplierDataInstruction(
mint.publicKey, // Mint account that stores the ScaledUiAmountConfig extension.
feePayer.publicKey, // Signer authorized to update the multiplier.
updatedMultiplier, // New multiplier used for displayed UI amounts.
0n, // Unix timestamp when the new multiplier takes effect.
[], // Additional multisig signers.
TOKEN_2022_PROGRAM_ID // Token program that owns the mint.
);
await sendAndConfirmTransaction(
connection,
new Transaction().add(updateMultiplierInstruction),
[feePayer]
);
const {
calculatedUiAmount: calculatedUiAmountAfterUpdate,
scaledUiAmountConfig
} = await calculateScaledUiAmount(connection, mint.publicKey, tokenAmount);
console.log("Mint Address:", mint.publicKey.toBase58());
console.log("Token Account:", tokenAccount.toBase58());
console.log(
"Calculated UI Amount Before Update:",
calculatedUiAmountBeforeUpdate
);
console.log(
"Calculated UI Amount After Update:",
calculatedUiAmountAfterUpdate
);
console.log("ScaledUiAmountConfig:", scaledUiAmountConfig);
Console
Click to execute the code.

Rust

Rust
use anyhow::Result;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_commitment_config::CommitmentConfig;
use solana_sdk::{
sysvar::clock::{self, Clock},
signature::{Keypair, Signer},
transaction::Transaction,
};
use solana_system_interface::instruction::create_account;
use spl_associated_token_account_interface::{
address::get_associated_token_address_with_program_id,
instruction::create_associated_token_account,
};
use spl_token_2022_interface::{
extension::{
scaled_ui_amount::{instruction, ScaledUiAmountConfig},
BaseStateWithExtensions, ExtensionType, StateWithExtensions,
},
instruction::{initialize_mint, mint_to_checked},
state::Mint,
ID as TOKEN_2022_PROGRAM_ID,
};
#[tokio::main]
async fn main() -> Result<()> {
let client = RpcClient::new_with_commitment(
String::from("http://localhost:8899"),
CommitmentConfig::confirmed(),
);
let fee_payer = Keypair::new();
let recipient = Keypair::new();
let initial_multiplier = 5.0;
let updated_multiplier = 10.0;
let token_amount = 1_000u64;
let airdrop_signature = client
.request_airdrop(&fee_payer.pubkey(), 2_000_000_000)
.await?;
loop {
let confirmed = client.confirm_transaction(&airdrop_signature).await?;
if confirmed {
break;
}
}
let mint = Keypair::new();
let mint_space =
ExtensionType::try_calculate_account_len::<Mint>(&[ExtensionType::ScaledUiAmount])?;
let mint_rent = client
.get_minimum_balance_for_rent_exemption(mint_space)
.await?;
let create_mint_account_instruction = create_account(
&fee_payer.pubkey(), // Account funding the new mint account.
&mint.pubkey(), // New mint account to create.
mint_rent, // Lamports funding the mint account rent.
mint_space as u64, // Account size in bytes for the mint plus ScaledUiAmountConfig.
&TOKEN_2022_PROGRAM_ID, // Program that owns the mint account.
);
let initialize_scaled_ui_amount_instruction = instruction::initialize(
&TOKEN_2022_PROGRAM_ID, // Token program that owns the mint.
&mint.pubkey(), // Mint account that stores the ScaledUiAmountConfig extension.
Some(fee_payer.pubkey()), // Authority allowed to update the multiplier later.
initial_multiplier, // Initial multiplier used for displayed UI amounts.
)?;
let initialize_mint_instruction = initialize_mint(
&TOKEN_2022_PROGRAM_ID, // Program that owns the mint account.
&mint.pubkey(), // Mint account to initialize.
&fee_payer.pubkey(), // Authority allowed to mint new tokens.
Some(&fee_payer.pubkey()), // Authority allowed to freeze token accounts.
0, // Number of decimals for the token.
)?;
let create_mint_transaction = Transaction::new_signed_with_payer(
&[
create_mint_account_instruction,
initialize_scaled_ui_amount_instruction,
initialize_mint_instruction,
],
Some(&fee_payer.pubkey()),
&[&fee_payer, &mint],
client.get_latest_blockhash().await?,
);
client
.send_and_confirm_transaction(&create_mint_transaction)
.await?;
let token_account = get_associated_token_address_with_program_id(
&recipient.pubkey(),
&mint.pubkey(),
&TOKEN_2022_PROGRAM_ID,
);
let create_token_account_instruction = create_associated_token_account(
&fee_payer.pubkey(), // Account funding the associated token account creation.
&recipient.pubkey(), // Owner of the token account.
&mint.pubkey(), // Mint for the associated token account.
&TOKEN_2022_PROGRAM_ID, // Token program that owns the token account.
);
let mint_to_token_account_instruction = mint_to_checked(
&TOKEN_2022_PROGRAM_ID, // Token program that owns the mint and token account.
&mint.pubkey(), // Mint account that issues the tokens.
&token_account, // Token account receiving the newly minted tokens.
&fee_payer.pubkey(), // Signer authorized to mint new tokens.
&[], // Additional multisig signers.
token_amount, // Token amount in base units.
0, // Decimals defined on the mint.
)?;
let create_token_account_transaction = Transaction::new_signed_with_payer(
&[
create_token_account_instruction,
mint_to_token_account_instruction,
],
Some(&fee_payer.pubkey()),
&[&fee_payer],
client.get_latest_blockhash().await?,
);
client
.send_and_confirm_transaction(&create_token_account_transaction)
.await?;
let mint_account_before_update = client.get_account(&mint.pubkey()).await?;
let mint_state_before_update = StateWithExtensions::<Mint>::unpack(&mint_account_before_update.data)?;
let scaled_ui_amount_config_before_update =
mint_state_before_update.get_extension::<ScaledUiAmountConfig>()?;
let clock_account = client.get_account(&clock::ID).await?;
let clock: Clock = clock_account.deserialize_data()?;
let calculated_ui_amount_before_update = scaled_ui_amount_config_before_update
.amount_to_ui_amount(
token_amount,
mint_state_before_update.base.decimals,
clock.unix_timestamp,
)
.unwrap();
let update_multiplier_instruction = instruction::update_multiplier(
&TOKEN_2022_PROGRAM_ID, // Token program that owns the mint.
&mint.pubkey(), // Mint account that stores the ScaledUiAmountConfig extension.
&fee_payer.pubkey(), // Signer authorized to update the multiplier.
&[], // Additional multisig signers.
updated_multiplier, // New multiplier used for displayed UI amounts.
0, // Unix timestamp when the new multiplier takes effect.
)?;
let update_multiplier_transaction = Transaction::new_signed_with_payer(
&[update_multiplier_instruction],
Some(&fee_payer.pubkey()),
&[&fee_payer],
client.get_latest_blockhash().await?,
);
client
.send_and_confirm_transaction(&update_multiplier_transaction)
.await?;
let mint_account_after_update = client.get_account(&mint.pubkey()).await?;
let mint_state_after_update = StateWithExtensions::<Mint>::unpack(&mint_account_after_update.data)?;
let scaled_ui_amount_config_after_update =
mint_state_after_update.get_extension::<ScaledUiAmountConfig>()?;
let calculated_ui_amount_after_update = scaled_ui_amount_config_after_update
.amount_to_ui_amount(
token_amount,
mint_state_after_update.base.decimals,
clock.unix_timestamp,
)
.unwrap();
println!("Mint Address: {}", mint.pubkey());
println!("Token Account: {}", token_account);
println!(
"Calculated UI Amount Before Update: {}",
calculated_ui_amount_before_update
);
println!(
"Calculated UI Amount After Update: {}",
calculated_ui_amount_after_update
);
println!("ScaledUiAmountConfig: {:#?}", scaled_ui_amount_config_after_update);
Ok(())
}
Console
Click to execute the code.

Is this page helpful?

목차

페이지 편집

관리자

© 2026 솔라나 재단.
모든 권리 보유.
연결하기