代币 SPL

在以太坊中,我们可以通过 ERC20 协议发行代币,这种代币统称 ERC20 代币。

那么 Solana 里的 ERC20 代币是什么呢?答案就是 SPL 代币。

The Solana Program Library (SPL) is a collection of on-chain programs targeting the Sealevel parallel runtime.

SPL Token 是 "Solana Program Library"  中的一个组成部分,叫做 "Token Program"。

所有代币都由这个合约来管理,合约代码位于 https://github.com/solana-labs/solana-program-library/tree/master/token

代币信息

在以太坊中,一个代币就是一个 ERC20 合,而 Solana 则不同。

SolanaSPL Token  中,一个代币仅仅是一个归 Token 合约管理的普通的 Account 对象。

在这个对象里面的二进制数据定义了代币的基本属性:

结构如下:

pub struct Mint {
        /// Optional authority used to mint new tokens. The mint authority may only be provided during
        /// mint creation. If no mint authority is present then the mint has a fixed supply and no
        /// further tokens may be minted.
        pub mint_authority: COption,
        /// Total supply of tokens.
        pub supply: u64,
        /// Number of base 10 digits to the right of the decimal place.
        pub decimals: u8,
        /// Is `true` if this structure has been initialized
        pub is_initialized: bool,
        /// Optional authority to freeze token accounts.
        pub freeze_authority: COption,
    }

其中 supply 表示总供应量,decimals 表示精度信息。

SPL Token Account

那么每个用户的拥有的代币数量信息存在哪里呢?

这个合约又定义了一个账号结构,用来表示某个地址拥有代币的数量:

pub struct Account {
        /// The mint associated with this account
        pub mint: Pubkey,
        /// The owner of this account.
        pub owner: Pubkey,
        /// The amount of tokens this account holds.
        pub amount: u64,
        /// If `delegate` is `Some` then `delegated_amount` represents
        /// the amount authorized by the delegate
        pub delegate: COption,
        /// The account's state
        pub state: AccountState,
        /// If is_native.is_some, this is a native token, and the value logs the rent-exempt reserve. An
        /// Account is required to be rent-exempt, so the value is used by the Processor to ensure that
        /// wrapped SOL accounts do not drop below this threshold.
        pub is_native: COption,
        /// The amount delegated
        pub delegated_amount: u64,
        /// Optional authority to close the account.
        pub close_authority: COption,
    }

其中 owner 表示谁的代币,amount 表示代币的数量。

Account 关系

整体结构如下:

这两个结构体都是 SPL Token Program 管理的 Account 对象,其自身所携带的数据,分别为代币信息和存储哪个代币的信息。

这样当需要进行代币的交易时,只需要相应用户的相应代币账号里面的 amount 即可。