Auto-Utils Package
Introduction
The @autonomys/auto-utils
package provides core utility functions for interacting with and building applications on the Autonomys Network.
Features
- Wallet Management: Initialize and manage wallets using mnemonics or URIs.
- Network Configuration: Access and manage network and domain settings.
- Data Storage: Save and read data to and from local storage or the file system.
- Cryptographic Operations: Perform hashing and data manipulation using cryptographic functions.
- API Activation: Activate and manage connections to the Autonomys Network APIs.
- Address Utilities: Convert and decode addresses to and from standardized formats.
Installation
Install the package via npm
or yarn
:
# Using npm
npm install @autonomys/auto-utils
# Using yarn
yarn add @autonomys/auto-utils
Importing
Import the auto-utils
functions you need into your project:
// Import specific functions
import { activateWallet, activate, blake2b_256 } from '@autonomys/auto-utils';
// Or import everything
import * as utils from '@autonomys/auto-utils';
Available functions
Note: All asynchronous functions return a
Promise
and should be used withawait
for proper execution flow. Wrap asynchronous calls intry...catch
blocks to handle potential errors gracefully.
Account and address utilities
address(input): string
: Standardizes an address format.createAccountIdType(api, address): Uint8Array
: Creates anAccountId
object from an address.decode(input): Uint8Array
: Decodes an address to bytes.
API and connection management
Note: Always disconnect the API instance after operations to free up resources.
activate(options?): Promise<ApiPromise>
: Connects to the Autonomys Network.activateDomain(params): Promise<ApiPromise>
: Connects to a specific domain.createConnection(endpoint, options?): Promise<ApiPromise>
: Creates a new API connection.disconnect(api): Promise<void>
: Disconnects an API instance.
Cryptographic functions
blake2b_256(data): string
: Hashes data with BLAKE2b-256.concatenateUint8Arrays(...arrays): Uint8Array
: Concatenates multipleUint8Array
s.stringToUint8Array(string): Uint8Array
: Converts a string toUint8Array
.
Data storage
Note: Be cautious when saving sensitive data using
save
andread
as data storage is permanent. Handle private keys securely. Do not expose them in code or logs.
read(key): Promise<any>
: Reads data from storage.readFromFileSystem(key): Promise<any>
: Reads data from file system.readFromLocalStorage(key): Promise<any>
: Reads data from local storage.save(key, value): Promise<void>
: Saves data to storage.saveOnFileSystem(key, value): Promise<void>
: Saves data to file system.saveOnLocalStorage(key, value): Promise<void>
: Saves data to local storage.
Event management
eventName(type, event): string
: Combines a type and an event into a full event name.eventsGroup
: Groups system events by name.expectSuccessfulTxEvent
: Default success event names array.Type
: Enum for event types (e.g.,system
).validateEvents(events, eventsExpected?, tx, block, log?): EventsValidated
: Checks if expected events are in transaction events.
Network management
getNetworkDetails(options): NetworkDetails
: Retrieves the details of a network.getNetworkDomainDetails(options): DomainDetails
: Retrieves the details of a domain.getNetworkDomainRpcUrls(options): string[]
: Retrieves the RPC URLs for a domain.getNetworkRpcUrls(options): string[]
: Retrieves the RPC URLs for a network.networks
: Array of available networks.
Signing utilities
signMessage(signer, address, data): Promise<{ signature: string }>
: Signs a message with a signer and an address.signatureVerify
: Verifies signatures (re-exported from@polkadot/util-crypto
).signingKey(publicKey): string
: Converts a public key to a hex string.
String utilities
capitalizeFirstLetter(string): string
: Capitalizes the first letter.fixLengthEntryId(blockHeight, indexInBlock?): string
: Creates fixed-length IDs.isAddress(address): boolean
: Validates a Substrate address.isHex(value): boolean
: Validates a hexadecimal string.shortString(value, initialLength?, endLength?): string
: Truncates strings.stringify(value): string
: Stringifies values, handling BigInt.
Token and value formatting
formatSpacePledged(value, decimals?): string
: Formats space amount with units.formatTokenAmount(amount, decimals?): bigint
: Formats token amount with decimals.parseTokenAmount(amount, decimals?): number
: Parses token amount with decimals.
Transaction utilities
signAndSendTx(sender, tx, options?, eventsExpected?, log?, mapErrorCodeToEnum?): Promise<TransactionSignedAndSend>
: Signs, sends, and validates a transaction.
Wallet management
activateWallet(options): Promise<{ api, accounts }>
: Activates a wallet using a mnemonic or URI.generateWallet(): GeneratedWallet
: Generates a new wallet with a mnemonic.getMockWallet(name, wallets): Wallet
: Retrieves a mock wallet by name.mockWallets(options, api?): Promise<Wallet[]>
: Creates mock wallets for testing.setupWallet(params): Wallet
: Sets up a wallet from a mnemonic or URI.
Usage examples
1. Wallet management
Activate a wallet using a mnemonic phrase
import { activateWallet } from '@autonomys/auto-utils';
(async () => {
const mnemonic = 'your mnemonic phrase here';
const { api, accounts } = await activateWallet({
mnemonic,
networkId: 'taurus', // Optional: specify the network ID
});
const account = accounts[0];
console.log(`Connected with account address: ${account.address}`);
// Perform actions with the account...
// Disconnect when done
await api.disconnect();
})();
Activate a wallet using a URI
import { activateWallet } from '@autonomys/auto-utils';
(async () => {
const { api, accounts } = await activateWallet({
uri: '//Alice',
networkId: 'localhost', // Connect to a local network
});
const account = accounts[0];
console.log(`Connected with account address: ${account.address}`);
// Disconnect when done
await api.disconnect();
})();
Create mock wallets for testing
import { activate, mockWallets, getMockWallet } from '@autonomys/auto-utils';
(async () => {
const api = await activate({ networkId: 'taurus' });
const wallets = await mockWallets({}, api);
const aliceWallet = getMockWallet('Alice', wallets);
const bobWallet = getMockWallet('Bob', wallets);
console.log(`Alice's address: ${aliceWallet.accounts[0].address}`);
console.log(`Bob's address: ${bobWallet.accounts[0].address}`);
// Disconnect when done
await api.disconnect();
})();
2. Network management
List all available networks
import { networks } from '@autonomys/auto-utils';
networks.forEach((network) => {
console.log(`Network ID: ${network.id}, Name: ${network.name}`);
});
Retrieve the details of a specific network
import { getNetworkDetails } from '@autonomys/auto-utils';
const network = getNetworkDetails({ networkId: 'taurus' });
console.log(`Network Name: ${network.name}`);
console.log(`RPC URLs: ${network.rpcUrls.join(', ')}`);
Retrieve the details of a specific domain within a network
import { getNetworkDomainDetails } from '@autonomys/auto-utils';
const domain = getNetworkDomainDetails({ domainId: '1', networkId: 'taurus' });
console.log(`Domain Name: ${domain.name}`);
console.log(`RPC URLs: ${domain.rpcUrls.join(', ')}`);
3. Cryptographic functions
Hash a string using BLAKE2b-256
import { blake2b_256, stringToUint8Array } from '@autonomys/auto-utils';
const data = 'Hello, Autonomys!';
const dataBytes = stringToUint8Array(data);
const hash = blake2b_256(dataBytes);
console.log(`Hash: ${hash}`); // Outputs the hash of the input string
Convert a string to a Uint8Array
import { stringToUint8Array } from '@autonomys/auto-utils';
const text = 'Sample text';
const byteArray = stringToUint8Array(text);
console.log(byteArray); // Outputs Uint8Array representation of the string
Concatenate two Uint8Array
instances
import { stringToUint8Array, concatenateUint8Arrays } from '@autonomys/auto-utils';
const array1 = stringToUint8Array('First part ');
const array2 = stringToUint8Array('Second part');
const concatenated = concatenateUint8Arrays(array1, array2);
console.log(`Concatenated Result: ${new TextDecoder().decode(concatenated)}`);
// Outputs: "First part Second part"
4. API activation
Activate the network API (connect to the Autonomys Network)
import { activate } from '@autonomys/auto-utils';
(async () => {
const api = await activate({ networkId: 'taurus' });
console.log('API connected');
// Perform API calls...
// Disconnect when done
await api.disconnect();
})();
Activate a domain API (connect to a specific domain within the Autonomys Network)
import { activateDomain } from '@autonomys/auto-utils';
(async () => {
const api = await activateDomain({ domainId: '1', networkId: 'taurus' });
console.log('Domain API connected');
// Perform domain-specific API calls...
// Disconnect when done
await api.disconnect();
})();
5. Data storage
Save data to local storage or the file system and read it back
import { save, read } from '@autonomys/auto-utils';
const key = 'myData';
const value = { message: 'Hello, Autonomys!' };
// Save data
save(key, value);
// Read data
const retrievedValue = read(key);
console.log(retrievedValue); // Outputs: { message: 'Hello, Autonomys!' }
6. Address utilities
Convert an address to a standardized format and decode it
import { address, decode } from '@autonomys/auto-utils';
const originalAddress = '5GmS1wtCfR4tK5SSgnZbVT4kYw5W8NmxmijcsxCQE6oLW6A8';
const standardizedAddress = address(originalAddress);
const decodedAddress = decode(originalAddress);
console.log(`Standardized Address: ${standardizedAddress}`);
console.log('Decoded Address:', decodedAddress);