EOS で扱う型 symbol・asset 編
symbol_code クラスの記述
code:symbol.hpp
class symbol_code {
public:
constexpr symbol_code() : value(0) {}
constexpr explicit symbol_code( uint64_t raw )
:value(raw)
{}
constexpr explicit symbol_code( std::string_view str )
:value(0)
{
if( str.size() > 7 ) {
eosio_assert( false, "string is too long to be a valid symbol_code" );
}
for( auto itr = str.rbegin(); itr != str.rend(); ++itr ) {
if( *itr < 'A' || *itr > 'Z') {
eosio_assert( false, "only uppercase letters allowed in symbol_code string" );
}
value <<= 8;
value |= *itr;
}
}
symbol クラスの記述
code:symbol.hpp
class symbol {
public:
constexpr symbol() : value(0) {}
constexpr explicit symbol( uint64_t raw ) : value(raw) {}
constexpr symbol( symbol_code sc, uint8_t precision )
: value( (sc.raw() << 8) | static_cast<uint64_t>(precision) )
{}
constexpr symbol( std::string_view ss, uint8_t precision )
: value( (symbol_code(ss).raw() << 8) | static_cast<uint64_t>(precision) )
{}
例えば、ネイティブトークンとして扱われている EOS の symbol は、下図のような 8 bytes のデータである。
https://gyazo.com/2674283d61aca38201b8e3f120507169
symbol_code : トークンの種類の表示に関する部分。最大7文字までで、AからZまでを使用可能。
row() メソッド : uint64 型表記を返す。
precision : トークンの所持数の表示に関する部分。0から255までの整数で指定する。例えば、 precision が4ならば、$ 10^{-4} ( = 0.0001 )がそのトークン所持数の最小単位となる。
symbol : symbol_code と precision の組。
row() メソッド : symbol の uint64 型表記を返す。
code() メソッド : uint64 型表記で 1 byte 右にシフトさせて、symbol_code だけを返す。
precision() メソッド : uint64 型表記で uint8 型にキャストして、 precision だけを返す。
(注意)symbol クラスのインスタンス sym に対して、sym.code().row() と sym.row() とは別の値を返す。
ここで定義された symbol はトークンの単位として使われます。
code:asset.hpp
struct asset {
int64_t amount = 0;
symbol symbol;
// 中略 //
void print()const {
int64_t p = (int64_t)symbol.precision();
int64_t p10 = 1;
while( p > 0 ) {
p10 *= 10; --p;
}
p = (int64_t)symbol.precision();
auto change = amount % p10;
for( int64_t i = p -1; i >= 0; --i ) {
fractioni = (change % 10) + '0'; change /= 10;
}
printi( amount / p10 );
prints(".");
prints_l( fraction, uint32_t(p) );
prints(" ");
symbol.print(false);
}
EOSLIB_SERIALIZE( asset, (amount)(symbol) )
};
例えば、 1.0000 EOS は下図のような 16 bytes のデータである(ただし、raw メソッドが用意されているわけではない)。
https://gyazo.com/0f514dc7195adef8d2116bae2e55303e
関連ワード