Linking a namespace to a mosaic

Link a namespace to a mosaic.

Prerequisites

Getting into some code

To make mosaics easier to use and organize them, an account can link a registered name to any mosaic it has created.

Before starting, you must have registered a namespace first. If you already have registered a namespace, define the namespace identifier and the mosaic identifier you want to alias.

const namespaceId = new NamespaceId('foo');
const mosaicId = new MosaicId('7cdf3b117a3c40cc');
const namespaceId = new NamespaceId('foo');
const mosaicId = new MosaicId('7cdf3b117a3c40cc');

Then, announce the AliasTransaction that links the namespace and the mosaic.

const mosaicAliasTransaction = AliasTransaction.createForMosaic(
    Deadline.create(),
    AliasActionType.Link,
    namespaceId,
    mosaicId,
    NetworkType.MIJIN_TEST
);

const privateKey = process.env.PRIVATE_KEY as string;
const account = Account.createFromPrivateKey(privateKey, NetworkType.MIJIN_TEST);
const networkGenerationHash = process.env.NETWORK_GENERATION_HASH as string;
const signedTransaction = account.sign(mosaicAliasTransaction, networkGenerationHash);

const transactionHttp = new TransactionHttp('http://localhost:3000');
transactionHttp
    .announce(signedTransaction)
    .subscribe(x => console.log(x), err => console.error(err));
const mosaicAliasTransaction = AliasTransaction.createForMosaic(
    Deadline.create(),
    AliasActionType.Link,
    namespaceId,
    mosaicId,
    NetworkType.MIJIN_TEST
);

const privateKey = process.env.PRIVATE_KEY;
const account = Account.createFromPrivateKey(privateKey, NetworkType.MIJIN_TEST);
const networkGenerationHash = process.env.NETWORK_GENERATION_HASH;
const signedTransaction = account.sign(mosaicAliasTransaction, networkGenerationHash);

const transactionHttp = new TransactionHttp('http://localhost:3000');
transactionHttp
    .announce(signedTransaction)
    .subscribe(x => console.log(x), err => console.error(err));
nem2-cli transaction mosaicalias --action 1 --mosaic 7cdf3b117a3c40cc --namespace foo

If you want to unlink the alias, change alias action type to AliasActionType.Unlink.

What’s next?

Now you can send transactions using the namespace linked to the mosaic instead of defining the complete mosaicId.

const recipientAddress = Address.createFromRawAddress('SD5DT3-CH4BLA-BL5HIM-EKP2TA-PUKF4N-Y3L5HR-IR54');

const transferTransaction = TransferTransaction.create(
    Deadline.create(),
    recipientAddress,
    [new Mosaic(new NamespaceId('foo'),
            UInt64.fromUint(10000000))],
    EmptyMessage,
    NetworkType.MIJIN_TEST);
const recipientAddress = Address.createFromRawAddress('SD5DT3-CH4BLA-BL5HIM-EKP2TA-PUKF4N-Y3L5HR-IR54');

const transferTransaction = TransferTransaction.create(
    Deadline.create(),
    recipientAddress,
    [new Mosaic(new NamespaceId('foo'),
            UInt64.fromUint(10000000))],
    EmptyMessage,
    NetworkType.MIJIN_TEST);