Tu Primer Activo Funciable
Este tutorial te enseñará cómo crear tu propio Activo Funciable (FA) llamado FACoin. El Estándar de Activo Funciable proporciona soporte integrado para acuñar, transferir, quemar y rastrear balances de cuenta, por lo que es útil para representar activos fungibles. Usaremos el TypeScript SDK para desplegar el contrato y probarlo una vez que esté on-chain.
A alto nivel, el Estándar de Activo Funciable funciona a través de dos Objetos principales:
- Un Objeto
Metadata
para almacenar información sobre el activo fungible. FungibleStore
s para cada cuenta que tiene el activo fungible para rastrear su balance de cuenta actual.
Enviar un activo fungible a alguien hará que reciban un FungibleStore
y actualicen los balances en ambas cuentas en consecuencia.
Ver Activos Fungibles en Acción
Sección titulada «Ver Activos Fungibles en Acción»Aquí modificaremos, desplegaremos y probaremos el ejemplo del contrato FACoin para ver cómo funciona el Estándar de Activo Funciable. Si estás escribiendo tu propio contrato de activo fungible, también puedes consultar el ejemplo de contrato Stablecoin aquí.
-
Instala el CLI.
Esto será usado por los scripts de despliegue para publicar el contrato
FACoin
onchain. -
Clona el repositorio del SDK de TypeScript.
Este repositorio contiene el código de ejemplo de Activo Funciable.
Ventana de terminal git clone https://github.com/aptos-labs/aptos-ts-sdk.git -
Navega al nivel superior del repositorio clonado.
Ventana de terminal cd aptos-ts-sdk -
Instala las dependencias del SDK.
Ventana de terminal pnpm install -
Compila el SDK de TypeScript.
El ejemplo requiere la compilación local del SDK de TypeScript.
Ventana de terminal pnpm build -
Abre fa_coin.move en un editor.
Puedes encontrar
fa_coin.move
enexamples/typescript/move/facoin/sources/fa_coin.move
.Este es el archivo Move que contiene la mayor parte de la lógica del contrato. Profundizaremos en los detalles de cómo funciona este contrato después de mostrarte un ejemplo de él en acción.
-
Edita ASSET_NAME para ser el nombre de tu nuevo activo fungible.
Ej. “Tutorial Token”. Los valores que establezcas aquí aparecerán en el contrato desplegado y cuando estemos probando cómo funcionan las cosas.
-
Navega a examples/typescript.
Ventana de terminal cd examples/typescript -
Instala las dependencias para los ejemplos.
Ventana de terminal pnpm install -
Ejecuta your_fungible_asset.
Ventana de terminal pnpm run your_fungible_assetDeberías ver una salida que demuestra cómo se crean y transfieren los activos fungibles que se ve así:
Ventana de terminal === Direcciones ===Alice: 0x0c5dd7abbd67db06325fa1a2f37a1833f9a92ff2beb90f32495a9d80972429cdBob: 0x2a796f4255d5c23684fe6cc521069d684516031bb5ae1ad2061ddc5414450807Charlie: 0xd824909be65a224f651ff6e9b82ec99ad5707fcef739d1003be20fc69fb93d7a=== Compilando paquete FACoin localmente ===Para ejecutar la compilación, debes tener el CLI `aptos` instalado.Ejecutando la compilación localmente, en una situación real puedes querer compilar esto con anticipación.aptos move build-publish-payload --json-output-file move/facoin/facoin.json --package-dir move/facoin --named-addresses FACoin=0x0c5dd7abbd67db06325fa1a2f37a1833f9a92ff2beb90f32495a9d80972429cd --assume-yesCompilando, puede tomar un poco de tiempo para descargar dependencias de git...ACTUALIZANDO DEPENDENCIA GIT https://github.com/aptos-labs/aptos-core.gitINCLUYENDO DEPENDENCIA AptosFrameworkINCLUYENDO DEPENDENCIA AptosStdlibINCLUYENDO DEPENDENCIA MoveStdlibCONSTRUYENDO facoin===Publicando paquete FACoin===Transaction hash: 0x0c8a24987bdf2e5e40d8a00f6c97ac55419757bc440097d76959a64dbeafc351metadata address: 0x2e0e90c701233467f27150f42d365e27e72eb0be8e2a74ee529c31b813bbb321All the balances in this example refer to balance in primary fungible stores of each account.Alice's initial balance: 0.Bob's initial balance: 0.Charlie's initial balance: 0.Alice mints Charlie 100 coins.Charlie's updated "Tutorial Token" primary fungible store balance: 0.Alice freezes Bob's account.Alice as the admin forcefully transfers the newly minted coins of Charlie to Bob ignoring that Bob's account is frozen.Bob's updated "Tutorial Token" balance: 0.Alice unfreezes Bob's account.Alice burns 50 coins from Bob.Bob's updated "Tutorial Token" balance: 0.Bob transfers 10 coins to Alice as the owner.Alice's updated "Tutorial Token" balance: 0.Bob's updated "Tutorial Token" balance: 0.done.
Understanding the fa_coin.move
Example Contract
Sección titulada «Understanding the fa_coin.move Example Contract»The full contract for FACoin.move can be found here.
Let’s go step by step through how this contract is written.
-
Move.toml
The Move.toml file allows Move to import dependencies, determine which addresses to use, and includes metadata about the contract.
Regardless of which features you add to your fungible asset, your Move.toml will likely have similar fields to this at a minimum. In this case, we have the primary contract address
FACoin
that needs specifying at deploy time (indicated by leaving the value as “_”). It also includes the GitHub dependency to import the Fungible Asset standard from “AptosFramework”.[package]name = "facoin"version = "1.0.0"authors = [][addresses]FACoin = "_"[dependencies.AptosFramework]git = "https://github.com/aptos-labs/aptos-core.git"rev = "mainnet"subdir = "aptos-move/framework/aptos-framework" -
Imports
The FACoin module uses several important modules:
fungible_asset
contains the logic for granting permission to mint, transfer, burn, and create your FungibleAsset.object
allows for creating Aptos Objects.primary_fungible_store
contains the logic to track account balances for the new Fungible Asset.
module FACoin::fa_coin {use aptos_framework::fungible_asset::{Self, MintRef, TransferRef, BurnRef, Metadata, FungibleAsset};use aptos_framework::object::{Self, Object};use aptos_framework::primary_fungible_store;use std::error;use std::signer;use std::string::utf8;use std::option;//...}These imports are defined in the
Move.toml
file as GitHub dependencies. -
init_module
This function is called when the module is initially published in order to set up the proper permissions and Objects. For FACoin, this is used to initialize the asset’s
MetaData
Object (which contains things like the asset’s name and symbol), as well as getting the relevant ref’s for how our fungible asset will be used.The
ManagedFungibleAsset
standard helps keep track of which permissions this Module is allowed to use.fun init_module(admin: &signer) {let constructor_ref = &object::create_named_object(admin, ASSET_SYMBOL);primary_fungible_store::create_primary_store_enabled_fungible_asset(constructor_ref,option::none(),utf8(ASSET_NAME),utf8(ASSET_SYMBOL),8,utf8(b"http://example.com/favicon.ico"),utf8(b"http://example.com"),);let mint_ref = fungible_asset::generate_mint_ref(constructor_ref);let burn_ref = fungible_asset::generate_burn_ref(constructor_ref);let transfer_ref = fungible_asset::generate_transfer_ref(constructor_ref);let metadata_object_signer = object::generate_signer(constructor_ref);move_to(&metadata_object_signer,ManagedFungibleAsset { mint_ref, transfer_ref, burn_ref })} -
View Functions
When creating your own fungible asset, it can be helpful to add view functions for any data that is needed later on. In this case, we wanted to see the name of the asset in order to report which asset was being traded in our example scenario.
#[view]public fun get_metadata(): Object<Metadata> {let asset_address = object::create_object_address(&@FACoin, ASSET_SYMBOL);object::address_to_object<Metadata>(asset_address)}#[view]public fun get_name(): string::String {let metadata = get_metadata();fungible_asset::name(metadata)} -
Entry Functions
Every fungible asset has a similar interface (mint, transfer, burn, freeze, unfreeze, deposit, and withdraw). Here’s an example of a minimal mint function, which mints and transfers the funds to the proper recipient:
public entry fun mint(admin: &signer, to: address, amount: u64) acquires ManagedFungibleAsset {let asset = get_metadata();let managed_fungible_asset = authorized_borrow_refs(admin, asset);let to_wallet = primary_fungible_store::ensure_primary_store_exists(to, asset);let fa = fungible_asset::mint(&managed_fungible_asset.mint_ref, amount);fungible_asset::deposit_with_ref(&managed_fungible_asset.transfer_ref, to_wallet, fa);}
Summary
Sección titulada «Summary»If you want to build your own Fungible Asset, you can use fa_coin.move
as a starting point, or look to other code examples here.
Regardless, the Fungible Asset Standard will help you mint, transfer, burn, and keep track of balances automatically for whichever fungible assets you want to represent on-chain.
You can find the Move reference for Fungible Assets for more details on the function signatures and implementation details.