Auto-Consensus Package
Introduction
The @autonomys/auto-consensus package provides functions for interacting with the consensus layer of the Autonomys Network. It allows developers to perform actions involving account management, balance inquiries, transfers, staking operations, and more. @autonomys/auto-consensus works hand-in-hand with @autonomys/auto-utils to simplify blockchain interactions.
Installation
Install the package via npm or yarn:
# Using npm
npm install @autonomys/auto-consensus
# Using yarn
yarn add @autonomys/auto-consensusImporting
Import the auto-consensus functions you need into your project:
// Import specific functions
import { balance, transfer, account } from '@autonomys/auto-consensus';
// Or import everything
import * as consensus from '@autonomys/auto-consensus';Overview of the api object
Many functions in the auto-consensus package require an api object as a parameter. This api object is an instance of ApiPromise from the Polkadot.js API library that serves as a gateway for interacting with the blockchain node.
api core components
Note: Always disconnect the API instance after your operations are complete to free up resources.
api.rpc: Methods to perform remote procedure calls to the node.api.query: Access the blockchain’s runtime storage.api.tx: Create and submit extrinsics (transactions) to the blockchain.api.consts: Runtime constants defined in the blockchain’s metadata.api.events: Access events emitted by the blockchain.api.types: Type definitions used by the chain.
Example
import { createConnection } from '@autonomys/auto-utils';
async function getApiInstance() {
const endpoint = 'wss://auto-evm.chronos.autonomys.xyz/ws';
const api = await createConnection(endpoint);
return api;
}Available functions
Note: All asynchronous functions return a
Promiseand should be used withawaitfor proper execution flow. Wrap your asynchronous calls intry...catchblocks to handle potential errors gracefully.
Account management
account(api, address): Promise<AccountData>: Retrieves an account’s nonce and balance data.balance(api, address): Promise<BalanceData>: Retrieves an account’s balance details.
Balances
totalIssuance(networkId?): Promise<BigInt>: Retrieves the total token issuance on the network.batch(api, txs[]): SubmittableExtrinsic: Creates a batch transaction for multiple operations.
Blockchain information
block(api): Promise<RawBlock>: Retrieves the latest block data.header(api): Promise<RawBlockHeader>: Retrieves the latest block header.blockHash(api): Promise<string>: Retrieves the latest block hash.blockNumber(api): Promise<number>: Retrieves the current block number.networkTimestamp(api): Promise<bigint>: Retrieves the network timestamp.
Consensus information
blockchainSize(api): Promise<bigint>: Calculates the blockchain’s total size.spacePledged(api): Promise<bigint>: Calculates the total space pledged by farmers.solutionRanges(api): Promise<SolutionRanges>: Retrieves the current and next solution ranges.shouldAdjustSolutionRange(api): Promise<boolean>: Checks if the solution range needs adjustment.segmentCommitment(api): Promise<[StorageKey<AnyTuple>, Codec][]>: Retrieves segment commitment entries.slotProbability(api): [number, number]: Returns slot probability constants.maxPiecesInSector(api): bigint: Returns the maximum pieces in a sector.
Domains
domainStakingSummary(api): Promise<DomainStakingSummary[]>: Retrieves domain staking summaries.domains(api): Promise<DomainRegistry[]>: Retrieves domain registries.latestConfirmedDomainBlock(api): Promise<ConfirmedDomainBlock[]>: Retrieves the latest confirmed blocks per domain.
Operators and staking
operators(api): Promise<Operator[]>: Retrieves a list of all operators.operator(api, operatorId): Promise<OperatorDetails>: Retrieves the details of a specific operator.deposits(api, operatorId, account?): Promise<Deposit[]>: Retrieves the deposits for a specific operator.withdrawals(api, operatorId, account?): Promise<Withdrawal[]>: Retrieves the withdrawals for a specific operator.registerOperator(params): SubmittableExtrinsic: Creates a transaction to register a new operator.nominateOperator(params): SubmittableExtrinsic: Creates a transaction to nominate an operator.withdrawStake(params): SubmittableExtrinsic: Creates a transaction to withdraw staked tokens.deregisterOperator(params): SubmittableExtrinsic: Creates a transaction to deregister an operator.unlockFunds(params): SubmittableExtrinsic: Creates a transaction to unlock staked funds.unlockNominator(params): SubmittableExtrinsic: Creates a transaction to unlock nominator funds.
Transfers
transfer(api, receiver, amount, allowDeath?): SubmittableExtrinsic: Creates a transaction to transfer funds.transferAll(api, receiver, keepAlive?): SubmittableExtrinsic: Creates a transaction to transfer all tokens.
Utility functions
query<T>(api, methodPath, params?): Promise<T>: Queries the blockchain state for a method.remark(api, remark, withEvent?): SubmittableExtrinsic: Creates a remark transaction.rpc<T>(api, methodPath, params?): Promise<T>: Performs an RPC call.
Interactive usage example
Fetching the wallet balance (unlocked, locked) and nonce for a wallet
Usage examples
Code examples demonstrating how to use the functions provided by @autonomys/auto-consensus.
1. Account management
Retrieve detailed account information (including the nonce and balance data)
import { account } from '@autonomys/auto-consensus';
import { activate } from '@autonomys/auto-utils';
(async () => {
const api = await activate({ networkId: 'chronos' });
const accountData = await account(api, 'your_address');
console.log(`Nonce: ${accountData.nonce}`);
console.log(`Free Balance: ${accountData.data.free}`);
console.log(`Reserved Balance: ${accountData.data.reserved}`);
await api.disconnect();
})();Activate a wallet and check its balance
import { activateWallet } from '@autonomys/auto-utils';
import { balance } from '@autonomys/auto-consensus';
(async () => {
// Activate a wallet using a mnemonic phrase
const { api, accounts } = await activateWallet({
mnemonic: 'your mnemonic phrase here', // Replace with your mnemonic
networkId: 'chronos', // Optional: specify the network ID
});
const account = accounts[0];
console.log(`Connected with account address: ${account.address}`);
// Check the account balance
const accountBalance = await balance(api, account.address);
console.log(`Account balance: ${accountBalance.free}`);
// Disconnect when done
await api.disconnect();
})();2. Balance operations
Retrieve the free balance of an account
import { balance } from '@autonomys/auto-consensus';
import { activate } from '@autonomys/auto-utils';
(async () => {
const api = await activate({ networkId: 'chronos' });
const accountBalance = await balance(api, 'your_address');
console.log(`Free Balance: ${accountBalance.free}`);
await api.disconnect();
})();Retrieve the total token issuance on the network
import { totalIssuance } from '@autonomys/auto-consensus';
(async () => {
const total = await totalIssuance('chronos');
console.log(`Total Issuance: ${total.toString()}`);
})();3. Transfers
Transfer funds between accounts
import { activateWallet } from '@autonomys/auto-utils';
import { transfer } from '@autonomys/auto-consensus';
(async () => {
// Activate the sender's wallet
const senderWallet = await activateWallet({
mnemonic: 'sender mnemonic phrase', // Replace with the sender's mnemonic
});
const sender = senderWallet.accounts[0];
// Activate the receiver's wallet
const receiverWallet = await activateWallet({
mnemonic: 'receiver mnemonic phrase', // Replace with the receiver's mnemonic
});
const receiver = receiverWallet.accounts[0];
// Transfer 1 AI3 from the sender to the receiver
const amount = 1; // Amount in AI3
const transferTx = await transfer(senderWallet.api, receiver.address, amount);
// Sign and send the transaction
await transferTx.signAndSend(sender, ({ status, txHash, events }) => {
if (status.isInBlock) {
console.log(`Transaction included at blockHash ${status.asInBlock}`);
console.log(`Transaction hash: ${txHash}`);
} else if (status.isFinalized) {
console.log(`Transaction finalized at blockHash ${status.asFinalized}`);
}
});
// Disconnect when done
await senderWallet.api.disconnect();
await receiverWallet.api.disconnect();
})();Transfer tokens from one wallet to another
import { transfer } from '@autonomys/auto-consensus';
import { activateWallet, signAndSendTx, disconnect } from '@autonomys/auto-utils';
(async () => {
const { api, accounts } = await activateWallet({
networkId: 'chronos',
mnemonic: 'your_mnemonic',
});
const sender = accounts[0];
const recipientAddress = 'recipient_address';
const amount = '1000000000000'; // Amount in the smallest unit (Shannon)
const tx = await transfer(api, recipientAddress, amount);
// Sign and send the transaction
await signAndSendTx(sender, tx);
console.log(`Transferred ${amount} tokens to ${recipientAddress}`);
await disconnect(api);
})();4. Staking operations
Register a new operator for staking
import { registerOperator } from '@autonomys/auto-consensus';
import { activateWallet, signAndSendTx } from '@autonomys
/auto-utils';
(async () => {
const { api } = await activateWallet({
networkId: 'chronos',
mnemonic: 'sender_mnemonic',
});
// Sender's account (who is registering the operator)
const { accounts: senderAccounts } = await activateWallet({
networkId: 'chronos',
mnemonic: 'sender_mnemonic',
});
const sender = senderAccounts[0];
// Operator's account
const { accounts: operatorAccounts } = await activateWallet({
networkId: 'chronos',
mnemonic: 'operator_mnemonic',
});
const operatorAccount = operatorAccounts[0];
const tx = await registerOperator({
api,
senderAddress: sender.address,
Operator: operatorAccount,
domainId: '0', // Domain ID where the operator will be registered
amountToStake: '1000000000000000000', // Amount in smallest units
minimumNominatorStake: '10000000000000000',
nominationTax: '5', // Percentage as a string (e.g., '5' for 5%)
});
// Sign and send the transaction
await signAndSendTx(sender, tx);
console.log('Operator registered successfully');
})();Nominate an existing operator by staking tokens
import { nominateOperator } from '@autonomys/auto-consensus';
import { activateWallet, signAndSendTx } from '@autonomys/auto-utils';
(async () => {
const { api, accounts } = await activateWallet({
networkId: 'chronos',
mnemonic: 'nominator_mnemonic',
});
const nominator = accounts[0];
const operatorId = '1'; // The ID of the operator to nominate
const amountToStake = '5000000000000000000'; // Amount in smallest units
const tx = await nominateOperator({
api,
operatorId,
amountToStake,
});
// Sign and send the transaction
await signAndSendTx(nominator, tx);
console.log(`Nominated operator ${operatorId} with ${amountToStake} stake`);
})();5. Blockchain information
Retrieve the current block number, block hash, and network timestamp
import { blockNumber, blockHash, networkTimestamp } from '@autonomys/auto-consensus';
import { activate } from '@autonomys/auto-utils';
(async () => {
const api = await activate({ networkId: 'chronos' });
const currentBlockNumber = await blockNumber(api);
const currentBlockHash = await blockHash(api);
const currentTimestamp = await networkTimestamp(api);
console.log(`Current Block Number: ${currentBlockNumber}`);
console.log(`Current Block Hash: ${currentBlockHash}`);
console.log(`Network Timestamp: ${currentTimestamp}`);
await api.disconnect();
})();6. Domain interactions
Retrieve the list of domains registered on the network
import { domains } from '@autonomys/auto-consensus';
import { activate } from '@autonomys/auto-utils';
(async () => {
const api = await activate({ networkId: 'chronos' });
const domainList = await domains(api);
domainList.forEach((domain) => {
console.log(`Domain ID: ${domain.id}`);
console.log(`Owner Address: ${domain.owner}`);
console.log(`Creation Block: ${domain.creationBlock}`);
// ...other domain properties
});
await api.disconnect();
})();Retrieve staking summaries for all domains
import { domainStakingSummary } from '@autonomys/auto-consensus';
import { activate } from '@autonomys/auto-utils';
(async () => {
const api = await activate({ networkId: 'chronos' });
const stakingSummaries = await domainStakingSummary(api);
stakingSummaries.forEach((summary) => {
console.log(`Domain ID: ${summary.domainId}`);
console.log(`Total Stake: ${summary.totalStake}`);
// ...other summary properties
});
await api.disconnect();
})();Retrieve the latest confirmed blocks for each domain
import { latestConfirmedDomainBlock } from '@autonomys/auto-consensus';
import { activate } from '@autonomys/auto-utils';
(async () => {
const api = await activate({ networkId: 'chronos' });
const confirmedBlocks = await latestConfirmedDomainBlock(api);
confirmedBlocks.forEach((blockInfo) => {
console.log(`Domain ID: ${blockInfo.id}`);
console.log(`Block Number: ${blockInfo.number}`);
console.log(`Block Hash: ${blockInfo.hash}`);
// ...other block properties
});
await api.disconnect();
})();