APTOS Developer’s Guide | Your First COIN | Typescript

This guide details how to deploy and manage your new Coin. The steps are as follows:

  1. Deploy the moon_coin module. Call it moon_coin.
  2. Initialize MoonCoin with the standard framework module Coin.
  3. Register a recipient account to receive MoonCoin.
  4. Transfer MoonCoin to the recipient as the owner of the MoonCoin.

This guide is based on your first transaction as the library for this example. The following tutorial contains the example code, which you can download in full below:

In this tutorial, we will focus on the first_coin.ts file and reuse the first_transaction.ts library from the previous tutorial.

You can find the typescript project here.

Step 1: Deploying the moon_coin module

Step 1.1 Download Aptos-core

For the simplicity of this exercise, Aptos-core has a move-examples directory which makes it easy to build and test Move modules without loading additional resources. Over time, we will expand this section to describe how to use Move tools for development.

For now, download and prepare Aptos-core:

git clone https://github.com/aptos-labs/aptos-core.git
cd aptos-core
./scripts/dev_setup.sh
source ~/.cargo/env
git checkout origin/devnet
Enter fullscreen mode Exit fullscreen mode.

Install the Aptos command line utility. Learn more about the Aptos command line utility.

cargo install --git https://github.com/aptos-labs/aptos-core.git aptos
Enter fullscreen mode Exit fullscreen mode

Step 1.2 module overview

In this terminal change the contents of the directory to aptos-move/move-examples/moon_coin. Save this terminal window for the rest of this tutorial — we will call it the «Move window» later. In this section we will look at the sources/MoonCoinType.move file.

This module allows users to create a new MoonCoinType::moon_coin::MoonCoin, which can be used to register in the Coin module of the (0x1::coin) framework to create the Coin standard. Developers can write their own functionality in the moon_coin module if they want to do more than the standard 0x1::coin or 0x1::managed_coin (adds mining/burning functionality).

module MoonCoinType::moon_coin {
    struct MoonCoin {}
}
Enter fullscreen mode Exit fullscreen mode

The code is very simple because we do not add more functions to MoonCoin than the standard ones provided by the Coin framework (transfer, deposit, withdrawal, mining, burning). The most important part is the struct MoonCoin, which defines a new type of Coin that can be registered in 0x1::coin.

Step 1.3 Deploying the Move module containing the MoonCoin type

For Typescript:

  • Download a sample project.
  • Open your favorite terminal and go to where you downloaded the above example project.
  • Install the required libraries: yarn install.
  • Run the example: yarn first_coin moon_coin.mv

Step 1.4 Checking Output

  • After a few minutes a message will appear: "Update module with Alice address, build, copy to specified path and press Enter."
  • In the terminal "Move window" and for the Move file we looked at earlier:

  • Copy the Alice address.

  • Compile the modules with the Alice address using aptos move compile --package-dir . --named-addresses MoonCoinType=0x{alice_address_here}. Here we replace the generic named address MoonCoinType='_' in the moon_coin/move.toml file with the Alice address.

  • Copy build/Examples/bytecode_modules/MoonCoin.mv into the same folder as the code in this project manual

  • Go back to another terminal window and press "enter" on the prompt to continue executing the rest of the code

The output should look like this:

=== Addresses ===
Alice: 11c32982d04fbcc79b694647edff88c5b5d5b1a99c9d2854039175facbeefb40
Bob: 7ec8f962139943bc41c17a72e782b7729b1625cf65ed7812152a5677364a4f88

Update the module with Alice's address, build, copy to the provided path, and press enter.
Enter fullscreen mode Exit fullscreen mode

Step 2: Initializing MoonCoin

The moon_coin module has already been deployed. The next step is to initialize MoonCoin. In this example, we will use 0x1::managed_coin::initialize since we want to be able to mine/burn our new MoonCoin. This adds standard MoonCoin functions such as transferring, mining, burning and standard events (registration, deposit, withdrawal).

const client = new AptosClient(NODE_URL);
/** Initializes the new coin */
async function initializeCoin(accountFrom: AptosAccount, coinTypeAddress: HexString): Promise<string> {
  const token = new TxnBuilderTypes.TypeTagStruct(
    TxnBuilderTypes.StructTag.fromString(`${coinTypeAddress.hex()}::moon_coin::MoonCoin`),
  );

  const serializer = new BCS.Serializer();
  serializer.serializeBool(false);

  const entryFunctionPayload = new TxnBuilderTypes.TransactionPayloadEntryFunction(
    TxnBuilderTypes.EntryFunction.natural(
      "0x1::managed_coin",
      "initialize",
      [token],
      [BCS.bcsSerializeStr("Moon Coin"), BCS.bcsSerializeStr("MOON"), BCS.bcsSerializeUint64(6), serializer.getBytes()],
    ),
  );

  const [{ sequence_number: sequenceNumber }, chainId] = await Promise.all([
    client.getAccount(accountFrom.address()),
    client.getChainId(),
  ]);

  const rawTxn = new TxnBuilderTypes.RawTransaction(
    TxnBuilderTypes.AccountAddress.fromHex(accountFrom.address()),
    BigInt(sequenceNumber),
    entryFunctionPayload,
    1000n,
    1n,
    BigInt(Math.floor(Date.now() / 1000) + 10),
    new TxnBuilderTypes.ChainId(chainId),
  );

  const bcsTxn = AptosClient.generateBCSTransaction(accountFrom, rawTxn);
  const pendingTxn = await client.submitSignedBCSTransaction(bcsTxn);

  return pendingTxn.hash;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Register a beneficiary account to receive MoonCoin

In other networks, since tokens/coins are just balance numbers in a contract, anyone can "send" anyone else a random coin, even if the recipient does not want to receive it. In Aptos, the user must explicitly register to receive Coin<RandomCoin> before it can be sent to them.

The recipient just needs to call 0x1::coins::register<CoinType> to register:

/** Receiver needs to register the coin before they can receive it */
async function registerCoin(coinReceiver: AptosAccount, coinTypeAddress: HexString): Promise<string> {
  const token = new TxnBuilderTypes.TypeTagStruct(
    TxnBuilderTypes.StructTag.fromString(`${coinTypeAddress.hex()}::moon_coin::MoonCoin`),
  );

  const entryFunctionPayload = new TxnBuilderTypes.TransactionPayloadEntryFunction(
    TxnBuilderTypes.EntryFunction.natural("0x1::coins", "register", [token], []),
  );

  const [{ sequence_number: sequenceNumber }, chainId] = await Promise.all([
    client.getAccount(coinReceiver.address()),
    client.getChainId(),
  ]);

  const rawTxn = new TxnBuilderTypes.RawTransaction(
    TxnBuilderTypes.AccountAddress.fromHex(coinReceiver.address()),
    BigInt(sequenceNumber),
    entryFunctionPayload,
    1000n,
    1n,
    BigInt(Math.floor(Date.now() / 1000) + 10),
    new TxnBuilderTypes.ChainId(chainId),
  );

  const bcsTxn = AptosClient.generateBCSTransaction(coinReceiver, rawTxn);
  const pendingTxn = await client.submitSignedBCSTransaction(bcsTxn);

  return pendingTxn.hash;
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Transfer MoonCoin to the recipient as a MoonCoin owner

When a new Coin is initialized (step 2), the owner account gets the ability to mine/burn the new Coin. The owner account can mine MoonCoin by calling 0x1::managed_coin::mint.

/** Mints the newly created coin to a specified receiver address */
async function mintCoin(
  coinOwner: AptosAccount,
  coinTypeAddress: HexString,
  receiverAddress: HexString,
  amount: number,
): Promise<string> {
  const token = new TxnBuilderTypes.TypeTagStruct(
    TxnBuilderTypes.StructTag.fromString(`${coinTypeAddress.hex()}::moon_coin::MoonCoin`),
  );

  const entryFunctionPayload = new TxnBuilderTypes.TransactionPayloadEntryFunction(
    TxnBuilderTypes.EntryFunction.natural(
      "0x1::managed_coin",
      "mint",
      [token],
      [BCS.bcsToBytes(TxnBuilderTypes.AccountAddress.fromHex(receiverAddress.hex())), BCS.bcsSerializeUint64(amount)],
    ),
  );

  const [{ sequence_number: sequenceNumber }, chainId] = await Promise.all([
    client.getAccount(coinOwner.address()),
    client.getChainId(),
  ]);

  const rawTxn = new TxnBuilderTypes.RawTransaction(
    TxnBuilderTypes.AccountAddress.fromHex(coinOwner.address()),
    BigInt(sequenceNumber),
    entryFunctionPayload,
    1000n,
    1n,
    BigInt(Math.floor(Date.now() / 1000) + 10),
    new TxnBuilderTypes.ChainId(chainId),
  );

  const bcsTxn = AptosClient.generateBCSTransaction(coinOwner, rawTxn);
  const pendingTxn = await client.submitSignedBCSTransaction(bcsTxn);
  return pendingTxn.hash;
}
Enter fullscreen mode Exit fullscreen mode

Step 5. Check MoonCoin balance at Boba

/** Return the balance of the newly created coin */
async function getBalance(accountAddress: MaybeHexString, coinTypeAddress: HexString): Promise<string | number> {
  try {
    const resource = await client.getAccountResource(
      accountAddress,
      `0x1::coin::CoinStore<${coinTypeAddress.hex()}::moon_coin::MoonCoin>`,
    );

    return parseInt((resource.data as any)["coin"]["value"]);
  } catch (_) {
    return 0;
  }
}
Enter fullscreen mode Exit fullscreen mode

You can check the data by visiting either the REST interface or the Explorer:

  • Alice account through the Aptos REST interface.
  • Bob account via Aptos Explorer.

Оцените статью
devanswers.ru
Добавить комментарий