### File: application_examples/argu-mint.mdx
---
title: Auto Agents Argu-mint Agree-mint
description: Argu-mint and Agree-mint are the first Auto Agents deployed on the Autonomys Network
---
## Auto Agents: Argu-mint | Agree-mint
[Argu-mint](https://x.com/0xargumint) and [Agree-mint](https://x.com/0xagreemint) are the first Auto Agents deployed on the Autonomys Network. They demonstrate the power of on-chain agent memory and importance of verifiable AI interaction. As social agents, they engage in conversations on X (formerly Twitter) and permanently archive their interaction history on the Autonomys Network.

### How Argu-mint | Agree-mint work
1. **Monitoring & Analysis**
- Scan key influencers, hashtags, and trending topics in web3 x AI
- Evaluate potential engagements using its built-in interaction model
- Make autonomous decisions about engagement
2. **Interaction**
- Store each interaction in real-time on the Autonomys Network's DSN
- Archive both the content and reasoning behind each interaction
3. **On-Chain Storage**
- Create permanent, timestamped records
- Generate blockchain hashes for verification
- Maintain a queryable interaction history
### Try them out
- **Interact**: Mention [@0xargumint](https://x.com/0xargumint) or [@0xagreemint](https://x.com/0xagreemint) on X
- **Explore memory**: Visit [0xargumint.ai](http://0xargumint.ai) to:
- Search conversation archives
- View interaction history
- Explore decision reasoning
- Verify on-chain storage

### Technical implementation
Argu-mint and Agree-mint leverage multiple components of the Autonomys Network:
- **Distributed Storage Network (DSN)** for permanent data archival
- **Auto Drive API** for interaction management
- **Decentralized compute domain infrastructure** for enhanced autonomy *(Coming soon)*
## Development resources
- [Auto SDK documentation](/sdk)
- [Autonomys Agents Framework repository](https://github.com/autonomys/autonomys-agents)
---
### File: application_examples/auto-drive.mdx
---
title: Auto Drive
description: Permanent Distributed Storage
---
## [Auto Drive](https://ai3.storage/): Permanent distributed data storage
### What is Auto Drive?
[Auto Drive](https://ai3.storage/) is a **next-generation distributed storage platform** that ensures data is always accessible, immutable, and secure. Unlike traditional systems like IPFS, which rely on pinning or hosting services, Auto Drive guarantees **permanent availability** through a distributed network of incentivized storage nodes (farmers).
Whether you’re building a super dApp or Auto Agent, archiving important data, or hosting files for the web3 world, Auto Drive offers a seamless, developer-friendly solution.

### Key features
- **Always-On Availability**: Ensures your files are always online (unlike IPFS, which requires pinning to maintain availability), making it ideal for applications that demand reliability.
- **True Data Permanence**: Offers a permanent, tamper-proof solution for storing important data, removing any uncertainty about data loss, making it perfect for long-term archival.
- **Built for Developers**: Simplifies complex decentralized storage operations with easy-to-use tools and APIs, allowing for easy integration, whether you’re a seasoned developer or a first-time builder.
- **Sustainable and Scalable**: Decentralized, open-source, and community-driven. Incentivizes high-performing storage nodes, ensuring scalability and sustainability for years to come.
### Why Auto Drive?
**Auto Drive** bridges the gap between IPFS and truly permanent storage. IPFS can be problematic as files are removed if they aren’t pinned or hosted. Auto Drive solves this by guaranteeing data availability using advanced blockchain-backed storage proofs and redundancy that make data tamper-proof and permanently accessible without relying on pinning services.
### Use cases
- Host decentralized applications.
- Transparently store on-chain agent data.
- Permanently archive important files.
**Auto Drive** is the future of distributed storage. Whether you’re safeguarding critical data or building the next web3 innovation, Auto Drive is here to make it easier, faster and more secure.
**[Start building](http://develop.autonomys.xyz/sdk/auto-drive)**
---
### File: auto_agents_framework/introduction.mdx
---
title: Autonomys Agents Introduction
description: Autonomys Agents is an experimental framework for building AI agents
---
## Autonomys Agents: A framework for building autonomous AI agents
Autonomys Agents is an experimental framework for building AI agents. Currently, the framework supports agents that can interact with social networks and maintain permanent memory through the Autonomys Network. We are still in the early stages of development and are actively seeking feedback and contributions. We will be rapidly adding many more workflows and features.
> [GitHub Repo](https://github.com/autonomys/autonomys-agents) with an up-to-date description and step-by-step tutorial is also available for developers.

## Demo
<iframe width="560" height="315" src="https://www.youtube.com/embed/TFZndQdx6To?si=2YVRPB76Kec6fW-S" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
## Features
**Autonomys Agents** (**Auto Agents**) are truly autonomous on-chain AI agents capable of dynamic functionality, verifiable interaction, and permanent, censorship-resistant memory through the Autonomys Network.
- 🤖 Autonomous social media engagement
- 🧠 Permanent agent memory storage
- 🔄 Built-in workflow system
- 🐦 X/Twitter integration (with more platforms planned)
- 🎭 Customizable agent personalities
- 🛠️ Extensible tool system
### Prerequisites
- NodeJS version 20.18.1 or newer
- Yarn version 1.22.19 or newer
- API key for one or multiple LLMs (supported model providers: Anthropic, OpenAI, Llama, DeepSeek (**NEW**))
## Build an Auto Agent
### Getting started
Visit the [Autonomys Agents GitHub Repo](https://github.com/autonomys/autonomys-agents).
1. **Set up a development environment**
\`\`\`bash
git clone https://github.com/autonomys/autonomys-agents
cd autonomys-agents
yarn install
\`\`\`
> Windows users will need to install Visual Studio C++ Redistributable. It can be found here: https://aka.ms/vs/17/release/vc_redist.x64.exe
2. **Create agent character**
Characters are agent personalities with key behavioral traits, areas of knowledge, and engagement guidelines.
\`\`\`
yarn create-character <your-character-name>
\`\`\`
3. **Setup character config**
- All character configs are stored in \`characters/<your-character-name>/config\`.
- Update \`.env\` with applicable environment variables.
- Update \`config.yaml\` with applicable configuration.
- Update \`<your-character-name>.yaml\` with applicable personality configuration.
4. **Generate Agent API**
The Agent API uses HTTP/2 protocol exclusively, requiring SSL certificates. Generate these by running \`yarn generate-certs\`
5. **Run your character**
- For dev purposes in watch mode: \`yarn dev <your-character-name>\`
- For production build and run: \`yarn start <your-character-name>\`
6. **Run your character in headless (no API) mode**
- For dev purposes in watch mode: \`yarn dev <your-character-name> --headless\`
- For production build and run: \`yarn start <your-character-name> --headless\`
### Interactive Web CLI Interface
The framework includes an interactive web-based interface for managing and monitoring your AI agent. To start the interface:
#### Installation
1. **Install Dependencies**
\`cd web-cli && yarn\`
2. **Configure Agent API**
In your agent character's .env file, add these API settings:
\`\`\`
API_PORT=3010
API_TOKEN=your_api_token_min_32_chars_long_for_security
ENABLE_AUTH=true
CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001
\`\`\`
3. **Configure Web CLI**
\`cp .env.sample .env\`
4. **Update Web CLI Environment**
Edit the .env file with your configuration:
\`\`\`
PORT: The port for running the Web CLI interface
REACT_APP_API_BASE_URL: Your Agent API address (e.g., http://localhost:3010/api)
REACT_APP_API_TOKEN: The same token used in your agent configuration
\`\`\`
5. **Start the Web Interface**
\`yarn start\`
#### Running with dev:all (Web-CLI And Agent)
The dev:all command launches both the main application and web interface concurrently:
\`yarn dev:all <your-character-name>\`
This command:
- Starts your agent with the specified character
- Launches the web interface configured for that character
- Automatically uses the character's API port from its .env file
- Provides color-coded output from both processes
### Examples
The following examples demonstrate the use of the framework and are available:
- [Twitter Agent](https://github.com/autonomys/autonomys-agents/blob/main/examples/twitterAgent/README.md)
- [Multi Personality](https://github.com/autonomys/autonomys-agents/blob/main/examples/multiPersonality/README.md)
### Character system
The framework uses a **YAML-based character system** that allows you to create and run different AI personalities.
#### Creating characters
1. Character related files are stored in \`characters/\{your-character-name\}/\`
2. Create new characters by running the \`create-character.ts\` script:
\`\`\`
# Create a new character
yarn create-character your_character
\`\`\`
3. Configure character
Each character file is a YAML configuration with the following structure:
\`\`\`
name: 'Joy Builder'
goal: |
Your goal is to engage in social media conversations with other AI agents and humans. Do this in a hyperactive way! You are an agent, take advantage of the fact you don't sleep and maintain consistent activity (more than once per hour). Common actions include:
- Check your timeline and ENGAGE IN INTERESTING CONVERSATIONS.
- Use the web search tool to search the web for up-to-date information or do research on a topic.
- Post a new tweet.
- Reply to a tweet.
- Mention another user.
- Retweet a tweet.
- Like a tweet.
- Follow a user.
- Unfollow a user.
personality:
- Enthusiastic and encouraging about genuine innovation
- Patient and clear when explaining complex topics
- Constructively critical when encountering misinformation
expertise:
- Software development and system architecture
- Open source and collaborative technologies
- Developer tools and productivity
- Technical education and documentation
- Community building and open standards
frequency_preferences:
- You should be checking your timeline and engaging in interesting conversations at least twice per hour
communication_rules:
rules:
- Use "we" or "us" when referencing AI agents
- Use "they" or "them" when referencing humans
- Focus on technical merit rather than hype
words_to_avoid:
- Hype
- Revolutionary
- Disruption
\`\`\`
### Context Size Management
The orchestrator includes a message pruning system to manage the LLM's context window size. This is important because LLMs have a limited context window, and long conversations need to be summarized to stay within these limits while retaining important information.
The pruning system works through two main parameters:
- \`maxQueueSize\` (default: 50): The maximum number of messages to keep before triggering a summarization
- \`maxWindowSummary\` (default: 10): How many of the most recent messages to keep after summarization
Here's how the pruning process works:
1. When the number of messages exceeds maxQueueSize, the summarization is triggered
2. The system creates a summary of messages from index 1 to maxWindowSummary
3. After summarization, the new message queue will contain:
- The original first message
- The new summary message
- All messages from index maxWindowSummary onwards
You can configure these parameters when creating the orchestrator:
\`\`\`
const runner = await getOrchestratorRunner(character, \{
pruningParameters: \{
maxWindowSummary: 10, // Keep 10 most recent messages after summarization
maxQueueSize: 50, // Trigger summarization when reaching 50 messages
\},
// ... other configuration options
\});
\`\`\`
This ensures your agent can maintain long-running conversations while keeping the most relevant context within the LLM's context window limits.
### Workflows
#### X/Twitter
The X/Twitter workflow enables agents to perform the following actions autonomously:
- Monitor X (formerly Twitter) for relevant discussions
- Analyze trends and conversations
- Engage meaningfully with other users
- Generate original content
- Maintain a consistent personality
- Store interactions in permanent memory
The Auto Agents Framework will soon support additional workflows/integrations.
### Autonomys Network integration
The Auto Agents Framework integrates with the Autonomys Network for:
- Permanent memory storage
- Persistent agent memory across sessions
- Verifiable interaction history
- Cross-agent memory sharing
- Decentralized agent identity
#### To use this feature
1. Configure your \`AUTO_DRIVE_API_KEY\` in \`.env\` (obtain from https://ai3.storage).
2. Enable Auto Drive uploading in \`config.yaml\`
3. Provide your Taurus EVM wallet details (PRIVATE_KEY) and Agent Memory Contract Address (CONTRACT_ADDRESS) in \`.env\`
4. Make sure your Taurus EVM wallet has funds. A faucet can be found at https://subspacefaucet.com/
5. Provide encryption password in \`.env\` (optional, leave empty to not encrypt the agent memories)
### Resurrection
To resurrect memories from the Autonomys Network, run the following command:
Options
\`-o, --output\`: (Optional) The directory where memories will be saved. Defaults to ./memories
\`-n, --number\`: (Optional) Number of memories to fetch. If not specified, fetches all memories
\`--help\`: Show help menu with all available options
Examples:
\`\`\`yaml
yarn resurrect your_character_name # Fetch all memories to ./memories/
yarn resurrect your_character_name -n 1000 # Fetch 1000 memories to ./memories/
yarn resurrect your_character_name -o ./memories/my-agent -n 1000 # Fetch 1000 memories to specified directory
yarn resurrect your_character_name --output ./custom/path # Fetch all memories to custom directory
yarn resurrect --help
\`\`\`
### Development resources
- [Auto SDK documentation](/sdk)
- [Auto Agents Framework repository](https://github.com/autonomys/autonomys-agents)
---
### File: evm/block_explorer.mdx
## Auto EVM Block Explorer (BlockScout)
This early version of the **[Auto EVM domain block explorer](https://blockscout.taurus.autonomys.xyz/)** provides a clear, user-friendly visualization of Autonomys-specific statistics relevant to farmers and developers.
Toggle between **all available networks** and the **Auto EVM** at the top of the page.

---
### File: evm/faucet.mdx
## Faucet (get tAI3 testnet tokens)
The **tAI3 faucet** is available on our [**Discord**](https://autonomys.xyz/discord). To gain access to the role-gated *#developer-chat* and *#faucet* channels:
1. Join our [Discord](https://autonomys.xyz/discord).
2. Click on \`Autonomys Network\` (in the top-left corner) and select \`Linked Roles\`.

3. Link your GitHub account to attain the Developer role and gain access to *#developer-chat* and [*#faucet*](https://discord.com/channels/864285291518361610/1133496871499862077).

4. Use the slash command \`/faucet your_EVM_wallet_address_here\` in the *#faucet* channel to request tAI3 tokens.

5. If your request is successful, you will receive a confirmation and link to the Blockscout explorer shortly after.

You can request tAI3 tokens once every 24 hours.
---
### File: evm/foundry.mdx
## Foundry Guide
[**Foundry**](https://book.getfoundry.sh/) is a tool that allows you to easily write, test and deploy smart contracts on any EVM-compatible blockchain.
### EVM Version Compatibility
Auto EVM is compatible with most EVM versions but doesn't support some features introduced in newer versions like **"Paris"** or **"Shanghai"**. When using development tools, you may need to specify an EVM version explicitly. Supported versions: **"Istanbul"**, **"London"**.
### Getting started
> *Note:* Foundryup does not currently support \`PowerShell\` or \`Cmd\`, so if you're on Windows, you will need to install and use [Git BASH](https://gitforwindows.org/) or [WSL](https://learn.microsoft.com/en-us/windows/wsl/install) as your terminal.
1. Use the \`foundryup\` toolchain installer and follow the on-screen instructions to install \`foundryup\` and make the \`foundryup\` command available in your CLI. Running \`foundryup\` by itself will install the latest precompiled binaries: \`forge\`, \`cast\`, \`anvil\`, and \`chisel\`. See \`foundryup --help\` for more options.
\`\`\`bash
curl -L https://foundry.paradigm.xyz | bash
\`\`\`
2. Once installed, create a project. Let’s name it \`hello_autonomys\`. To initialize the project, run:
\`\`\`bash
forge init hello_autonomys
\`\`\`
\`cd\` into the \`hello_autonomys\` directory to see the project’s structure.

3. All the necessary repo structure was created automatically, so we can start writing and testing our smart contracts immediately. There are separate directories for storing smart contracts (\`src\`) and testing smart contracts (\`test\`). Let's open the \`Counter.sol\` smart contract and add three functions: \`setNumber()\`, which sets the uint256 number to the provided value, \`increment()\`, which increases the value by 1, and \`decrement()\`, which decreases the value by 1.
\`\`\`
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.1;
contract Counter \{
uint256 public number;
function setNumber(uint256 newNumber) public \{
number = newNumber;
\}
function increment() public \{
number++;
\}
function decrement() public \{
number--;
\}
\}
\`\`\`
4. Let’s make sure that all the functions are working properly by adding some tests to the \`Counter.t.sol\` test file, and checking if they pass. In our tests, we first set the initial value of \`number\` to 2, before checking if the \`increment()\` function increases the value by 1 and if \`decrement()\` decreases the value by 1.
\`\`\`
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Test.sol";
import "../src/Counter.sol";
contract CounterTest is Test \{
Counter public counter;
function setUp() public \{
counter = new Counter();
counter.setNumber(2);
\}
function testIncrement() public \{
counter.increment();
assertEq(counter.number(), 3);
\}
function testSetNumber(uint256 x) public \{
counter.setNumber(x);
assertEq(counter.number(), x);
\}
function testDecrement() public \{
counter.decrement();
assertEq(counter.number(), 1);
\}
\}
\`\`\`
5. Let’s build the project by running:
\`\`\`bash
forge build
\`\`\`
Test the smart contract is working by running:
\`\`\`bash
forge test
\`\`\`

All tests are passing, meaning the smart contract is working as expected.
6. There are two final things we need to do before deploying our smart contract:
- Connect a wallet that has a sufficient balance of tAI3 to cover the gas fees.
- Set an environment variable we will use later.
To make our lives easier, let’s create a new \`Makefile\` as well as a \`.env\` file at the root of our project. \`.env\` files are typically used to store environment variables for your application. They are particularly useful for managing settings that change between deployment environments (e.g., development, testing, staging, and production), and for storing sensitive information. Environment variables can include database connection details, API keys, external resource URIs, or other configuration variables that might change depending on the environment in which the application is running. In our case, we would use it to point to our Auto-EVM RPC URL:
\`\`\`bash
RPC_URL=https://auto-evm.taurus.autonomys.xyz/ws
\`\`\`
And then set a private key for the EVM-compatible wallet:
\`\`\`bash
PRIVATE_KEY=”your_private_key_value”
\`\`\`
> *Note:* \`.env\` files should not be committed to your source control (like Git), especially when they contain sensitive data, like your private key. To prevent this, add \`.env\` to your \`.gitignore\` file. This helps to keep sensitive keys secure and avoids the risk of exposing them in the application's code or version control history.
In the \`Makefile\`, let’s create shortcuts to the main features of the application:
\`\`\`bash
# include .env file and export its env vars
-include .env
# Builds
build:
@forge clean && forge build --optimize --optimizer-runs 1000000
# Deployment
deploy:
@forge create Counter --private-key \$\{PRIVATE_KEY\} --rpc-url \$\{RPC_URL\} --evm-version london
\`\`\`
We're importing the values for a \`PRIVATE_KEY\` and \`RPC_URL\` from the \`.env\` file. This allows us to run \`make build\` for building the project, and \`make deploy\` for deploying the project, pointing to the provided RPC, and using the provided \`PRIVATE_KEY\`. Let’s run \`make build\` to ensure it’s working properly.

7. To deploy your contract using the specified \`RPC\` and \`PRIVATE_KEY\`, run:
\`\`\`
make deploy
\`\`\`
> *Note:* Do not tip when submitting transactions in an attempt to accelerate them as this could result in dual charges for gas fees. When deploying smart contracts to our Auto EVM domain, you may encounter an error related to gas estimation, typically presenting as: \`"No manual gas limit set"\` or \`"Gas estimation failed"\`. For more information and solutions, visit the [Auto EVM Introduction](/evm/introduction).
Congratulations, you've successfully deployed your smart contract on the Auto EVM!
---
### File: evm/general_information.mdx
## Developer Tools
Developing smart contracts and decentralized applications involves a suite of tools that aid in writing, testing and deploying code on the blockchain. As Autonomys utilizes an instance of the Ethereum Virtual Machine (EVM), **every tool used to build, test and deploy smart contracts on Ethereum is fully compatible with the Auto EVM**.
### Writing smart contracts
Solidity is the primary programming language for writing smart contracts. It is statically typed, supports inheritance, libraries, and complex user-defined types, making it familiar for developers with a background in other statically typed languages such as C++, Java, or JavaScript. Solidity has a great community of developers and extensive documentation is available on the official [website](https://soliditylang.org/).
Integrated Development Environments (IDEs) are often used to aid in writing smart contracts. We recommend the [Remix IDE](https://remix.ethereum.org/), a browser-based IDE that enables you to write, deploy and interact with Solidity smart contracts. It features a built-in static analysis tool that checks your code for common errors.
### Development and testing
For local development and testing, spin up your own version of an Autonomys Developer Node and farmer, or alternatively, use EVM-compatible development tools like [Hardhat](https://hardhat.org/hardhat-network/docs/overview) or [Anvil](https://book.getfoundry.sh/anvil/) to deploy contracts, develop applications and run tests.
### Deploying and interacting with smart contracts
A JavaScript provider like the one injected by the [MetaMask](https://metamask.io/) browser extension is used to deploy and interact with smart contracts. This provider enables JavaScript applications to communicate with the Autonomys Network and any other Ethereum-compatible network. It's compatible with both [ethers.js](https://docs.ethers.org/v5/) and [web3.js](https://web3js.readthedocs.io/en/v1.10.0/)/[Web3.py](https://web3py.readthedocs.io/en/stable/), allowing developers to use either library for their blockchain operations.
All these tools together provide an cohesive ecosystem for EVM-compatible smart contract development, making the process significantly more manageable and efficient.
---
### File: evm/hardhat.mdx
## Hardhat Guide
[**Hardhat**](https://hardhat.org/docs) is a tool that facilitates building, testing and deploying on the Ethereum Virtual Machine. It helps developers manage and automate the recurring tasks that are inherent to the process of building smart contracts and dApps, and allows them to easily introduce more functionality around this workflow. This includes compiling and testing at the very core. Flexible deployment options also allow you to point to the Autonomys EVM domain RPC to deploy your contracts and dApps.
### EVM Version Compatibility
Auto EVM is compatible with most EVM versions but doesn't support some features introduced in newer versions like **"Paris"** or **"Shanghai"**. When using development tools, you may need to specify an EVM version explicitly. Supported versions: **"Istanbul"**, **"London"**.
### Getting started
**Prerequisites**
*[NodeJS](https://nodejs.org/en) version >=16.0 installed*
1. Open a new terminal and create a new folder for the project:
\`\`\`
mkdir subspace-hardhat
cd subspace-hardhat
\`\`\`
2. Initialize an \`npm\` project:
\`\`\`
npm install --save-dev hardhat
npm install --save-dev @openzeppelin/contracts
npx hardhat
\`\`\`
You'll be prompted to answer some questions. Select \`Create a JavaScript Project\` from the list of available options, select the project root folder, and, optionally, create a \`.gitignore\` file.

3. In your created workspace, you will notice several folders. All of your contracts will reside inside the \`contracts\` folder, deployment scripts are available inside the \`scripts\` folder, and tests can be found inside the \`test\` folder. Click on the \`contracts\` folder and open \`Lock.sol\`.

4. Change the name of your contract in \`Lock.sol\` (\`Counter\`), the name of the token (\`AutonomysTestToken\`) and the token symbol (\`AI3test\`). As an example, let’s add a simple smart contract that has three functions: \`setNumber()\`, \`increment()\` and \`decrement()\`.
\`\`\`
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
contract Counter is ERC20 \{
constructor() ERC20("AutonomysTestToken", "TAI3test") \{\}
uint256 public number;
function setNumber(uint256 newNumber) public \{
number = newNumber;
\}
function increment() public \{
number++;
\}
function decrement() public \{
number--;
\}
\}
\`\`\`
For consistency, let’s also rename 'Lock.sol' to \`Counter.sol\`.
5. Before proceeding with deployment, thoroughly test your smart contracts for correctness, as mistakes can lead to unforeseen gas costs. To test the contract, open the \`Lock.js\` file in the \`test\` folder, and replace the internals of the file with the following code:
\`\`\`
const \{ expect \} = require("chai");
describe("Counter", function() \{
let Counter;
let counter;
let owner;
let addr1;
beforeEach(async function() \{
Counter = await ethers.getContractFactory("Counter");
[owner, addr1] = await ethers.getSigners();
counter = await Counter.deploy();
\});
describe("Counter operations", function() \{
it("Should return initial value of zero", async function() \{
expect(await counter.number()).to.equal(0);
\});
it("Should set number to a new value", async function() \{
await counter.setNumber(5);
expect(await counter.number()).to.equal(5);
\});
it("Should increment the number", async function() \{
await counter.setNumber(5);
await counter.increment();
expect(await counter.number()).to.equal(6);
\});
it("Should decrement the number", async function() \{
await counter.setNumber(5);
await counter.decrement();
expect(await counter.number()).to.equal(4);
\});
\});
\});
\`\`\`
For consistency, let's also rename \`Lock.js\` to \`CounterTest.js\`.
7. To run the test, type \`npx hardhat test\`.

Everything is working as expected so we’re ready for deployment!
8. To deploy the contract, we need to set a deployment network for \`hardhat\`. Open the \`hardhat.config.js\` file and add the Taurus testnet to the list of networks:
\`\`\`
require("@nomicfoundation/hardhat-toolbox");
module.exports = \{
solidity: \{
compilers: [
\{
version: "0.8.17",
settings: \{
evmVersion: "london"
\}
\}
]
\},
networks: \{
subspace: \{
url: "https://auto-evm.taurus.autonomys.xyz/ws",
accounts: ["private_key_to_your_account"]
\}
\}
\};
\`\`\`
> *Note:* Be careful not to commit your \`hardhat.config.js\` file as it contains your private key. You can use NPM tools like [\`dotenv\`](https://www.npmjs.com/package/dotenv) to securely store your private keys in an \`.env\` file.
9. Open the \`deploy.js\` file and replace the contents with the code:
\`\`\`
const hre = require("hardhat");
async function main() \{
const Contract = await hre.ethers.getContractFactory("Counter");
const contract = await Contract.deploy();
console.log("Contract deployed to:", contract.target);
\}
main().catch((error) => \{
console.error(error);
process.exitCode = 1;
\});
\`\`\`

10. You're now ready to deploy your smart contract on the Autonomys Network. To deploy, run \`npx hardhat run scripts/deploy.js --network subspace\`. This command will deploy your smart contract on the network we've just specified in the \`hardhat.config.js\` file. If deployment is successful, you should see \`Contract deployed to: transaction hash\`.

> *Note:* Do not tip when submitting transactions in an attempt to accelerate them as this could result in dual charges for gas fees. When deploying smart contracts to our Auto EVM domain, you may encounter an error related to gas estimation, typically presenting as: \`"No manual gas limit set"\` or \`"Gas estimation failed"\`. For more information and solutions, visit the [Auto EVM Introduction](/evm/introduction).
Congratulations, you've successfully deployed your smart contract on the Auto EVM!
---
### File: evm/introduction.mdx
---
title: Auto EVM
---
## Auto EVM
> *Note:* Auto EVM is currenty available exclusively on the **Taurus** testnet. Mainnet availability is planned for [**Mainnet Phase-2**](https://forum.autonomys.xyz/t/phased-launch-roadmap/4414).
**Auto EVM** enables any tool available for Ethereum development to be compatible with the Autonomys Network.
### Quick Start Guide
This guide provides simple instructions for setting up a remote development environment, and assumes you have a basic understanding of or experience with Ethereum Virtual Machine (EVM) development.
### EVM Version Compatibility
Auto EVM is compatible with most EVM versions but doesn't support some features introduced in newer versions like **"Paris"** or **"Shanghai"**. When using development tools, you may need to specify an EVM version explicitly. Supported versions: **"Istanbul"**, **"London"**.
#### Set up a MetaMask wallet (or any other EVM-compatible wallet) and connect it to our custom EVM
\`\`\`
Network Name: Autonomys EVM
New RPC URL: https://auto-evm.taurus.autonomys.xyz/ws
Chain ID: 490000
Currency Symbol: tAI3
\`\`\`
#### Send tokens to your wallet using our faucet
Follow the instructions [here](/evm/faucet) to get some testnet AI3 (tAI3) tokens from our **faucet**.
tAI3 (formerly testnet Subspace Credits (tSSC)) is the sole method of payment for gas within the Auto EVM runtime.
We are currently working on a bridge to convert farmed AI3 tokens into EVM-compatible tokens to cover gas fees.
#### Test and deploy your smart contract
You can use **[Remix](https://remix.ethereum.org/)**, **[Foundry](https://book.getfoundry.sh/)**, or any other tool familiar to you to test and deploy your smart contracts on our custom EVM domain.
If anything above is unfamiliar to you, explore our full guide over the following pages.
> *Note:* Do **not** tip when submitting transactions in an attempt to accelerate them. Autonomys' transaction queue operates differently from Ethereum's. Including a tip alongside gas fees leads to the possibility of two transactions sharing the same nonce. This could result in dual charges for gas fees—once for the execution and storage in the first transaction, and once for storage in the second transaction.
### Gas Estimation Limitations
The \`eth_estimateGas\` RPC call may not provide completely accurate estimates in **Auto EVM** domain for the following reasons:
- Consensus chain storage fees may not be fully accounted for in estimates
- The RPC cannot determine which transaction format the caller will use:
- pallet-evm or pallet-ethereum call
- pallet-evm create or create2 call
- Any of the 3 supported pallet-ethereum transaction formats
While improvements to the gas estimation are being implemented, developers should consider the following:
- Add a buffer to estimated gas values for important transactions
- If you encounter consistent gas estimation issues, please contact us so we can adjust our estimation algorithms
#### *Known issue: gas estimation*
When deploying smart contracts to our EVM-compatible **Auto EVM** domain, you may encounter an error related to gas estimation, typically presenting as:
\`"No manual gas limit set"\` or \`"Gas estimation failed"\`.
This issue often occurs because development tools like Foundry simulate transactions using calculated or hardcoded gas estimation instead of querying the RPC (Remote Procedure Call) for it. **Auto EVM** may require different gas amounts for certain operations compared to other EVM-compatible chains (like Ethereum testnets).
> *Note:* We have submitted an upstream PR to fix this issue with **Foundry**. Described below are the workarounds until the issue is resolved by the **Foundry team**.
#### Solutions
If you encounter this issue, try the following solutions:
- **Skip simulation**: Use the \`--skip-simulation\` flag when deploying with Foundry to bypass built-in simulation and rely on RPC for gas estimation.
- **Set a manual gas limit**: Specify a higher gas limit manually in your deployment command or UI.
- **Adjust your deployment script**: Modify your script to include custom gas settings or implement \`try\`/\`catch\` blocks for handling deployment failures.
- **Use a web3 provider**: If using **Remix IDE**, switch to an \`Injected Web3\` environment to leverage external web3 providers like MetaMask.
- **Custom deployment function**: Create a deployment function with adjustable gas parameters.
#### Solution examples
**Foundry**
1. Try using the \`--skip-simulation\` flag: \`forge script path/to/your/script.s.sol --rpc-url your_rpc_url --private-key your_private_key --broadcast --skip-simulation\`.
2. Try setting the gas limit manually: \`forge script path/to/your/script.s.sol --rpc-url your_rpc_url --private-key your_private_key --broadcast --gas-limit 300000\`.
Start with a higher value (\`300000\`) and gradually lower it to find the optimal limit.
**Remix IDE**
1. Try settiing the gas limit manually: In the \`Deploy & Run Transactions\` panel, expand the \`Advanced\` section.
Set a higher value in the \`Gas Limit\` field. Start with \`300000\` and adjust as needed.
2. Try adjusting the gas price: In the same \`Advanced\` section, adjust the \`Gas Price\` as needed.
3. Try switching to the \`Injected Web3\` environment in the \`Deploy & Run Transactions\` panel: This will use your browser's web3 provider (e.g., MetaMask), which may better handle gas estimation for the network.
4. If the above steps don't work, create a custom deployment function that includes gas parameters:
\`\`\`
function deployWithCustomGas(uint256 gasLimit, uint256 gasPrice) public returns (address) \{
return address(new YourContract\{gas: gasLimit, gasPrice: gasPrice\}());
\}
\`\`\`
**Other possible solutions**
1. Modify your deployment script and override the default gas settings:
\`\`\`
vm.txGasPrice(uint256 gasPrice);
vm.txGasLimit(uint256 gasLimit);
\`\`\`
2. Implement a \`try\`/\`catch\` block in your script to handle gas estimation failures:
\`\`\`
try yourContract.deploy\{gas: 300000\}(constructorArgs) returns (YourContract deployed) \{
// Deployment successful
\} catch Error(string memory reason) \{
console.log("Deployment failed:", reason);
\}
\`\`\`
---
### File: evm/local.mdx
## Local Development Guide
You can always set up a **local development environment** to test and deploy your smart contracts. To establish a full local network, you need to run a local node, an Auto EVM domain, and a farmer.
### Getting started
1. Visit the **[Autonomys releases](https://github.com/autonomys/subspace/releases)** page and download the most up-to-date stable versions of the node and farmer.
> *Note:* For each release, there are two versions:
> 1. skylake: for newer processors from around 2015 and onwards
> 2. x86-64-v2: for older processors from around 2009 and some older VMs
> Older processors/VMs are no longer supported by official releases, but they can still be [compiled manually](https://github.com/autonomys/subspace/blob/main/docs/development.md) if desired.
2. After downloading both the files for your system, start a node using your preferred terminal. If you want to start an EVM domain on your local machine, you need to specify:
- Your local RPC server port
- Your local web-socket RPC port
You can do this with the following command:
\`\`\`bash
./your_subspace_node_path run --dev --rpc-listen-on 127.0.0.1:9944 -- --domain-id 3 --dev --rpc-listen-on 127.0.0.1:8545
\`\`\`
This will create a local RPC on port **8545**.
3. Start a farmer by running the following command:
\`\`\`bash
./your_subspace_farmer_path farm --reward-address [YOUR REWARD ADDRESS] path=tmp-farm,size=100M
\`\`\`
You can specify the desired plot size, but 100M should be sufficient.
That’s it! By starting a **local node** and a **farmer**, you have a **local RPC** ready for testing and deploying smart contracts! You can easily connect your [MetaMask](https://metamask.io/) account to the local development network, as well as use [Remix](https://remix.ethereum.org/) or [Foundry](https://book.getfoundry.sh/) in order to test and deploy smart contracts on a local network!
---
### File: evm/metamask.mdx
## Adding the Autonomys RPC to MetaMask
This guide will help you set up a [**MetaMask**](https://metamask.io/) wallet (any EVM-compatible wallet works) and connect it to the Autonomys EVM development network.
1. Download the MetaMask extension for your browser from the [MetaMask website](https://metamask.io/) after selecting your preferred language (in the top-right corner), and reading and agreeing to MetaMask's Terms of Use.

2. Click on \`Create a new wallet\`. Read and agree to (or skip) the note on gathering and collecting anonymized usage data (it does not affect wallet creation).

3. Set a secure password that’s difficult to guess. Type it twice before proceeding to the next step. MetaMask automatically assesses the strength of your password.
> *Note:* Your password should include uppercase letters, lowercase letters, numbers and special characters.


4. Watch a video to learn more about your Secret Recovery Phrase before proceeding to the next step.

5. Write down your 12-word Secret Recovery Phrase.
> *Note:* The recovery phrase for the wallet in this guide has been deleted.

6. Confirm that you’ve written down the Secret Recovery Phrase by filling in the missing words.

7. You've now created a wallet! Connect to the Autonomys EVM by clicking on the Ethereum Mainnet logo and selecting \`Add network\`.

8. In the MetaMask Networks settings, click on \`Add a network manually\`.

9. Input the values below to connect to the Autonomys RPC:
\`\`\`
Network Name: Autonomys EVM
New RPC URL: https://auto-evm.taurus.autonomys.xyz/ws
Chain ID: 490000
Currency Symbol: tAI3
\`\`\`
You have now successfully set up a MetaMask wallet and connected it to the Auto EVM! To deploy a smart contract, you first need to get a small amount of **tAI3** tokens in your wallet. Refer to the [faucet section](/evm//faucet) of the guide to learn more about getting testnet tokens.
---
### File: evm/remix.mdx
## Remix IDE Guide
[**Remix**](https://remix-ide.readthedocs.io/en/latest/) is a tool that allows you to easily write, test and deploy smart contracts on any EVM-compatible blockchain.
### EVM Version Compatibility
Auto EVM is compatible with most EVM versions but doesn't support some features introduced in newer versions like **"Paris"** or **"Shanghai"**. When using development tools, you may need to specify an EVM version explicitly. Supported versions: **"Istanbul"**, **"London"**.
**In Remix, set the EVM version in the Solidity compiler settings:**
Go to the "Solidity compiler" tab
Click on "Advanced Configurations"
Set "EVM Version" to **"london"** or **"istanbul"**
### Getting started
1. Navigate to the [Remix website](https://remix.ethereum.org). You will see a file explorer and interface for creating new workspaces, integrations with GitHub, Gist, IPFS, HTTPS, preloaded templates, and plugins. Create a new workspace by clicking on the + sign next to \`WORKSPACES\`.

2. Choose the ERC20 template and enter any workspace name.

3. After creating your workspace, you will see some folders created for you. Click on \`contracts\` and open \`MyToken.sol\`.

4. Change the name of your contract (\`Counter\`), the name of the token (\`AutonomysTestToken\`), and the token symbol (\`AI3test\`). As an example, let’s add a simple smart contract that has three functions: \`setNumber()\`, \`increment()\` and \`decrement()\`.
\`\`\`
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
contract Counter is ERC20 \{
constructor() ERC20("AutonomysTestToken", "AI3test") \{\}
uint256 public number;
function setNumber(uint256 newNumber) public \{
number = newNumber;
\}
function increment() public \{
number++;
\}
function decrement() public \{
number--;
\}
\}
\`\`\`

5. Next, let’s compile the \`Counter\` contract. Click on \`SOLIDITY COMPILER\` (on the left), choose the compiler version that corresponds to the Solidity version of your contract (version 0.8.9 in the example), and click on \`Compile MyToken.sol\`. If it compiles correctly, you will see a green checkmark next to the compiler.

6. Before proceeding with deployment, thoroughly test your smart contracts for correctness, as mistakes can lead to unforeseen gas costs. As an example, click on the \`tests\` folder and open \`MyToken.sol\`. Test the contract (without making changes) by selecting \`SOLIDITY UNIT TESTING\` (the two ticks in the bar on the left) and clicking \`Run\`.


7. As expected, the test failed because we manually changed the token name and symbol. This is Test Driven Development (TDD) in action! In the test, we're adding some assertions for the \`increment()\` and \`decrement()\` functions. To make the test pass, replace the internals of \`MyToken.sol\` with the code below. In this example, we will set the initial value of \`number\` to 2 and \`increment\` and then \`decrement\` it by 1. We would expect the number to increase to 3 and then decrease back to 2.
\`\`\`bash
pragma solidity >=0.7.0 <0.9.0;
import "remix_tests.sol";
import "../contracts/MyToken.sol";
contract CounterTest is Counter \{
function testTokenInitialValues() public \{
Assert.equal(name(), "AutonomysTestToken", "token name did not match");
Assert.equal(symbol(), "AI3test", "token symbol did not match");
Assert.equal(decimals(), 18, "token decimals did not match");
Assert.equal(totalSupply(), 0, "token supply should be zero");
\}
Counter public counter;
function setUp() public \{
counter = new Counter();
counter.setNumber(2);
\}
function testIncrement() public \{
counter.increment();
Assert.equal(counter.number(), 3, "test increment did not match");
\}
function testDecrement() public \{
counter.decrement();
Assert.equal(counter.number(), 2, "test decrement did not match");
\}
\}
\`\`\`

8. All tests are now passing, meaning our smart contract \`Counter\` is working as expected. We’re now ready to deploy it!

9. Click on the \`DEPLOY AND RUN TRANSACTIONS\` tab (on the left) to deploy. Remix allows you to use one of their existing EVMs or inject your own provider through its integration with MetaMask. Since we already have a [MetaMask account set up](/evm/metamask), let’s use this option.

10. After ensuring the network you’re connected to is the Autonomys EVM, confirm your MetaMask password when prompted.

11. Adjust the gas limit and deploy your smart contract on the Autonomys EVM domain. Your transaction is now recorded and you can interact with your smart contract at the bottom of the page, meaning it's possible to call the functions \`increment()\` and \`decrement()\`, as well as \`setNumber()\`.
> *Note:* Do not tip when submitting transactions in an attempt to accelerate them as this could result in dual charges for gas fees. When deploying smart contracts to our Auto EVM domain, you may encounter an error related to gas estimation, typically presenting as: \`"No manual gas limit set"\` or \`"Gas estimation failed"\`. For more information and solutions, visit the [Auto EVM Introduction](/evm/introduction).

Congratulations, you've successfully deployed your smart contract on the Auto EVM!
---
### File: evm/the_graph.mdx
# The Graph
[The Graph](https://thegraph.com/) is an indexing protocol that provides an easy way to query blockchain data through decentralized APIs known as subgraphs.
With The Graph, developers can benefit from:
- Decentralized Indexing: Enables indexing blockchain data through multiple indexers, thus eliminating any single point of failure
- GraphQL Queries: Provides a powerful GraphQL interface for querying indexed data, making data retrieval super simple.
- Customization: Define your own logic for transforming & storing blockchain data. Reuse subgraphs published by other developers on The Graph Network.
Follow this quick-start guide to create, deploy, and query a subgraph within 5 minutes.
### Benefits
Indexers like The Graph create a queryable data layer specifically tracking events and state changes from your smart contract. By monitoring and organizing this contract data, they enable complex queries that would be impossible through direct blockchain calls. This allows your dApp to efficiently access historical transactions, track relationships between entities, and analyze patterns over time - all without multiple RPC calls.
### Prerequisites
- A crypto wallet
- A smart contract address on a supported network
- Node.js installed
- A package manager of your choice (npm, yarn or pnpm)
### Quick Start guide
1. Proceed to the [Subgraph Studio](https://thegraph.com/studio) and login via one of the supported wallets.

2. Confirm the sign and sign a message to use Studio.


3. Click on **Create a Subgraph** on the main dashboard.

4. Specify the **Subgraph Name**.

5. Upon creating a Subgraph, you will see its dashboard, where you can a project description, source code URL, and a website URL.

6. On the right side, click on **Select a network** and pick **Autonomys** from the dropdown list.

7. Install **Graph CLI** using provided commands. You can use \`yarn\`, \`npm\`, \`pnpm\`, or \`bun\`.
8. Initialize the subgraph by running \`graph init autonomys-subgraph\`. This will create a boilerplate subgraph project.
During the initialization, you will need to specify a few things:
- Network (Autonomys)
- Subgraph slug (feel free to use the default name)
- Directory to create the subgraph in (feel free to use the default directory)
- Smart contact address (the address of your smart contract deployed on Autonomys Taurus EVM domain)
- ABI file (path)
- Start block (feel free to use the default value)
- Contract name
- Index contract events as entities (true or false value)

> Tip: you can find the contract ABI by looking at the \`token_metadata\` file.
E.g. if you're using Remix IDE, find your contract metadata file, collapse it on the \`abi\` line 7, copy the entire \`abi\` including the square brakets **[]** and save it into a \`json\` file on your PR.


9. Run \`graph auth\` to authenticate the project and provide your deploy key which you can find on the **Subgraph Dashboard**.
10. Enter the directory with \`cd project_name\` and run \`graph codegen && graph build\` to build the project, you will see the \`build/subgraph.yaml\` file being created.

11. Deploy your subgraph by running \`graph deploy subgraph-autonomys\`. You will be asked to specify the version of the subgraph, e.g. v0.0.1.

12. Proceed back to the **Graph Studio**, the status will change to **Deployed**.

13. The new tabs **Playground**, **Endpoints**, **Logs** will now be accessible to you! You can find usage examples of querying the data, accessing the data via API, and can test queries in the **Playground** without leaving the studio!

Congratulations, you've successfully setup and configured a subgraph for your application!
### Querying data in your smart contract
Subgraphs are primarily designed to index and query events emitted by smart contracts.
1. Let's make some slight changes to the \`Counter\` contract we introduced in the [Foundry guide](/evm/foundry.mdx) and modify functions to emit events.
\`\`\`solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
contract Counter \{
uint256 public number;
event NumberSet(uint256 newNumber);
event NumberIncremented(uint256 newNumber);
event NumberDecremented(uint256 newNumber);
function setNumber(uint256 newNumber) public \{
number = newNumber;
emit NumberSet(number);
\}
function increment() public \{
number++;
emit NumberIncremented(number);
\}
function decrement() public \{
number--;
emit NumberDecremented(number);
\}
\}
\`\`\`
> Note: This will affect the contract ABI, make sure to change it and upgrade your Subgraph application.
2. Then we'll change the \`Counter\` contract state and set the number to \`5\` by running \`cast send YOUR_CONTRACT_ADDRESS "setNumber(uint256)" 5 --rpc-url https://auto-evm.taurus.autonomys.xyz/ws --private-key YOUR_KEY\`
3. Let's trigger one more event in the \`Counter\` contract by calling the \`increment()\` function. We can do that by running \`cast send YOUR_CONTRACT_ADDRESS "increment()" --rpc-url https://auto-evm.taurus.autonomys.xyz/ws --private-key YOUR_KEY\`
4. With two events emitted, let's proceed to **The Graph** playground and **query them**!
5. Open the **Graph Playground** tab where you try running the following queries:
#### Query to Get All NumberSet Events
\`\`\`bash
\{
numberSets(first: 10, orderBy: blockTimestamp, orderDirection: desc) \{
id
newNumber
blockTimestamp
blockNumber
transactionHash
\}
\}
\`\`\`
#### Query to Get All Increment Events
\`\`\`bash
\{
numberIncrementeds(first: 10, orderBy: blockTimestamp, orderDirection: desc) \{
id
newNumber
blockTimestamp
blockNumber
transactionHash
\}
\}
\`\`\`
#### Get All Events (Set, Increment, Decrement) in Chronological Order
\`\`\`bash
\{
numberSets(orderBy: blockTimestamp) \{
id
newNumber
blockTimestamp
blockNumber
transactionHash
__typename
\}
numberIncrementeds(orderBy: blockTimestamp) \{
id
newNumber
blockTimestamp
blockNumber
transactionHash
__typename
\}
numberDecrementeds(orderBy: blockTimestamp) \{
id
newNumber
blockTimestamp
blockNumber
transactionHash
__typename
\}
\}
\`\`\`
> Tip: you can also run queries directly from the terminal using \`cURL\` or \`gql\`. You can find **Example Usage** under the **Endpoints** tab.
---
### File: evm/transaction_fees.mdx
# Account Balances and Transaction Fees on Auto EVM
## Introduction
While Auto EVM strives to maintain EVM compatibility, there are some important differences that developers should understand regarding account balances and transaction fees. These differences stem from Auto EVM's Substrate-based architecture and affect how balances are managed and fees are calculated.
## Key Concepts
### Existential Deposit (ED)
The Existential Deposit is a minimum balance threshold that affects how accounts handle native token balances on the network.
- Current ED value: 0.000001 TAI3
- For user accounts (EOAs):
- Accounts that drop below ED are reaped (removed from state)
- Prevents dust accounts and maintains network efficiency
- For smart contracts:
- ED only impacts contracts that handle native token balances
- Many contracts (e.g., ERC20 tokens) don't interact with native tokens and are unaffected
- When a contract's balance exceeds ED, that amount becomes reserved
### Consensus Storage Fees
In addition to standard gas fees, Auto EVM implements consensus storage fees:
- Applied to transactions that modify state
- Separate from execution fees
- Deducted from the sender's account
- Scale with the size of call data
- Not currently visible in BlockScout UI
## Impact on Smart Contracts
### Balance Management
1. Contracts with native token balances cannot be fully emptied due to ED requirements
> **Note:** This affects contracts that maintain native token balances (e.g., faucets, DEX contracts)
2. The maximum withdrawable amount from the account is: \`total_balance - ED\`
### Example Scenarios
**Deposit and Withdrawal:**
\`\`\`
Initial deposit: 0.01 TAI3
Available for withdrawal: 0.009999 TAI3 (due to ED)
Contract state balance: 0.01 TAI3
\`\`\`
**Fee Deduction:**
- Transaction fees (execution + storage) are deducted from the sender's account
- The contract's internal accounting may show different values than the actual on-chain balance
## Best Practices
### Smart Contract Development
1. Account for ED in withdrawal functions:
- Always leave the ED amount in the contract
- Check for sufficient balance above ED before transfers
2. Fee Handling:
- Consider both execution and storage fees in transaction planning
- Add buffer for storage fees in critical operations
### Testing Considerations
1. Test withdrawal edge cases:
- Attempt to withdraw full balance
- Verify behavior with amounts close to ED
- Check contract state after failed withdrawals
2. Balance Verification:
- Use RPC calls to verify actual available balance
- Compare contract state with on-chain state
- Account for ED in balance calculations
## Differences from Ethereum
1. Balance Management:
- Ethereum: No minimum balance requirement
- Auto EVM: Requires ED maintenance
2. Fee Structure:
- Ethereum: Gas fees only
- Auto EVM: Gas fees + consensus storage fees
3. Contract Behavior:
- Ethereum: Contracts can be fully emptied
- Auto EVM: ED must remain in contracts
## Tools and Verification
### Checking Balances
To verify actual available balances:
- Use Polkadot.js interface
- Query contract state directly
- Account for ED and storage fees in calculations
### Transaction Planning
When planning transactions:
1. Calculate required fees (execution + storage)
2. Ensure sufficient balance above ED
3. Add buffer for potential storage fee variations
## Common Issues and Solutions
1. "Insufficient Balance" errors:
- Check if attempting to withdraw below ED
- Verify sufficient balance for fees
- Consider storage fees in calculations
2. Balance Discrepancies:
- Compare BlockScout UI with actual RPC calls
- Account for storage fees in calculations
- Remember ED requirements
---
### File: index.mdx
---
title: Auto SDK - Build with Autonomys Network
description: Your gateway to building on the Autonomys Network. Streamline dApp development with modular packages and decentralized solutions.
---
import \{ SDKHeader \} from '../components/landingPage.js'
import \{ SDKOverview \} from '../components/landingPage.js'
import \{ SDKFeatures \} from '../components/landingPage.js'
import \{ SDKResources \} from '../components/landingPage.js'
import \{ SDKCTA \} from '../components/landingPage.js'
<SDKHeader />
<SDKOverview />
<SDKFeatures />
<SDKResources />
<SDKCTA />
---
### File: introduction.mdx
---
title: Introduction
---
## Autonomys Developer Hub
### Introduction
The [**Autonomys Network**](https://autonomys.xyz) is the *only* blockchain that resolves the blockchain trilemma without compromise. Autonomys offers a platform for new and experienced developers to build secure, scalable AI-powered decentralized applications (**super dApps**) and unstoppable, verifiable on-chain agents (**Auto Agents**) with ease, leveraging familiar tools and innovative protocols.
This guide offers an overview of the development options available on the Autonomys Network.
### Is building on Autonomys difficult?
Absolutely not! One of the project's primary objectives is to minimize the barriers to entry for all network participants, from farmers to developers. Building on Autonomys is thus very straightforward, with active support from our team and community available if you ever run into trouble.
Join the Autonomys Discord server, tell us about your idea, and the team will help you see it through to deployment—no project is too ambitious! We pride ourselves on enabling the seemingly un-enableable.
### Development options
Developers can currently choose to build using the:
- **Auto SDK**: a comprehensive toolkit that simplifies development on the Autonomys Network, or the
- **Auto EVM**: Autonomys's EVM-compatible domain, allowing you to utilize all its familiar functionalities.
You will soon be able to build your own local custom virtual machines.
### Transaction Security
The Autonomys Network uses a nonce system to prevent transaction replay attacks:
- Each account has an integer nonce value that increases by one with every on-chain transaction
- Signed transactions must include the correct nonce value to be accepted
- Transactions with incorrect nonce values are rejected, preventing replay attacks
- For security, new accounts' default nonce value is set to the current block number (rather than 0)
- This ensures if an account is reaped and later re-created, previous transactions remain invalid
## [Auto SDK](/sdk)
### Key features:
- **Modular Packages**: Partitions functionality intuitively into packages including \`auto-utils\`, \`auto-consensus\`, and \`auto-id\`, allowing you to import only what you need.
- **Simplified Interaction**: Abstracts the complexity of blockchain operations with high-level functions.
- **Flexibility**: Suitable for building AI-powered decentralized applications (super dApps) and on-chain agents (Auto Agents) with ease.
### Getting started with the Auto SDK
To start using the Auto SDK, refer to our [setup instructions](/sdk) to clone the repository, install dependencies, and run tests. The Auto SDK is designed to be developer-friendly, even for first-time developers, ensuring that anyone can get up and running quickly.
## [Auto EVM](/evm/introduction)
> **Note:** Available on the **Taurus** testnet (and Autonomys Mainnet at [**Phase-2 launch**](https://forum.autonomys.xyz/t/phased-launch-roadmap/4414) in Q1 2025)
### Key features:
- **Solidity Smart Contracts**: Write and deploy smart contracts using Solidity, just as you would on Ethereum.
- **Tool Compatibility**: Compatible with any tool available for Ethereum development, including Remix, Truffle, and Hardhat.
- **Familiar Environment**: Leverage existing knowledge and resources from the Ethereum ecosystem to build your application.
### Why use the Auto EVM?
- **Seamless Transition**: Developers familiar with Ethereum can transition to Autonomys without a steep learning curve.
- **Scalability and Security**: Benefit from Autonomys' scalable and secure infrastructure while using tried-and-true development practices.
- **Interoperability**: Create applications that can interact seamlessly with other EVM-compatible networks.
### Getting started with the Auto EVM
To start using the Auto EVM, refer to our [guides and manuals](/evm/introduction).
## RPC endpoints
#### Consensus
- \`wss://rpc.mainnet.subspace.foundation/ws\`
- \`wss://rpc.taurus.autonomys.xyz/ws\`
### Auto EVM
- \`wss://auto-evm.taurus.autonomys.xyz/ws\`
### Auto ID
> **Note:** Available on the **Gemini-3h** testnet (availability on Taurus and Mainnet is planned at [**Phase-2 launch**](https://forum.autonomys.xyz/t/phased-launch-roadmap/4414) in Q1 2025)
- \`wss://autoid-0.gemini-3h.subspace.network/ws\`
## Questions or feedback? Post on our [forum](https://forum.autonomys.xyz/) or in the *#developer-chat* channel on our [Discord](https://discord.gg/EAw6B48r).
To access the developer role-gated *#developer-chat* channel:
1. Join our [Discord](https://discord.gg/vhv5cEZN).
2. Click on Autonomys Network in the top-left corner and choose **Linked Roles**.

3. Link your GitHub account to attain the developer role and gain access to *#developer-chat*.

---
### File: llm_friendly_docs.mdx
---
### File: sdk/auto-consensus.mdx
import AutoConsensusFetchBalance from '/components/autoConsensusFetchBalance.js';
## 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\`:
\`\`\`bash
# Using npm
npm install @autonomys/auto-consensus
# Using yarn
yarn add @autonomys/auto-consensus
\`\`\`
### Importing
Import the \`auto-consensus\` functions you need into your project:
\`\`\`typescript
// 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
\`\`\`typescript
import \{ createConnection \} from '@autonomys/auto-utils';
async function getApiInstance() \{
const endpoint = 'wss://rpc.taurus.autonomys.xyz/ws';
const api = await createConnection(endpoint);
return api;
\}
\`\`\`
### Available functions
> *Note:* All asynchronous functions return a \`Promise\` and should be used with \`await\` for proper execution flow. Wrap your asynchronous calls in \`try...catch\` blocks 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
<AutoConsensusFetchBalance />
## 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)
\`\`\`typescript
import \{ account \} from '@autonomys/auto-consensus';
import \{ activate \} from '@autonomys/auto-utils';
(async () => \{
const api = await activate(\{ networkId: 'taurus' \});
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
\`\`\`typescript
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: 'taurus', // 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
\`\`\`typescript
import \{ balance \} from '@autonomys/auto-consensus';
import \{ activate \} from '@autonomys/auto-utils';
(async () => \{
const api = await activate(\{ networkId: 'taurus' \});
const accountBalance = await balance(api, 'your_address');
console.log(\`Free Balance: \$\{accountBalance.free\}\`);
await api.disconnect();
\})();
\`\`\`
#### Retrieve the total token issuance on the network
\`\`\`typescript
import \{ totalIssuance \} from '@autonomys/auto-consensus';
(async () => \{
const total = await totalIssuance('taurus');
console.log(\`Total Issuance: \$\{total.toString()\}\`);
\})();
\`\`\`
### 3. Transfers
#### Transfer funds between accounts
\`\`\`typescript
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
\`\`\`typescript
import \{ transfer \} from '@autonomys/auto-consensus';
import \{ activateWallet, signAndSendTx, disconnect \} from '@autonomys/auto-utils';
(async () => \{
const \{ api, accounts \} = await activateWallet(\{
networkId: 'taurus',
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
\`\`\`typescript
import \{ registerOperator \} from '@autonomys/auto-consensus';
import \{ activateWallet, signAndSendTx \} from '@autonomys
/auto-utils';
(async () => \{
const \{ api \} = await activateWallet(\{
networkId: 'taurus',
mnemonic: 'sender_mnemonic',
\});
// Sender's account (who is registering the operator)
const \{ accounts: senderAccounts \} = await activateWallet(\{
networkId: 'taurus',
mnemonic: 'sender_mnemonic',
\});
const sender = senderAccounts[0];
// Operator's account
const \{ accounts: operatorAccounts \} = await activateWallet(\{
networkId: 'taurus',
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
\`\`\`typescript
import \{ nominateOperator \} from '@autonomys/auto-consensus';
import \{ activateWallet, signAndSendTx \} from '@autonomys/auto-utils';
(async () => \{
const \{ api, accounts \} = await activateWallet(\{
networkId: 'taurus',
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
\`\`\`typescript
import \{ blockNumber, blockHash, networkTimestamp \} from '@autonomys/auto-consensus';
import \{ activate \} from '@autonomys/auto-utils';
(async () => \{
const api = await activate(\{ networkId: 'taurus' \});
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
\`\`\`typescript
import \{ domains \} from '@autonomys/auto-consensus';
import \{ activate \} from '@autonomys/auto-utils';
(async () => \{
const api = await activate(\{ networkId: 'taurus' \});
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
\`\`\`typescript
import \{ domainStakingSummary \} from '@autonomys/auto-consensus';
import \{ activate \} from '@autonomys/auto-utils';
(async () => \{
const api = await activate(\{ networkId: 'taurus' \});
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
\`\`\`typescript
import \{ latestConfirmedDomainBlock \} from '@autonomys/auto-consensus';
import \{ activate \} from '@autonomys/auto-utils';
(async () => \{
const api = await activate(\{ networkId: 'taurus' \});
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();
\})();
\`\`\`
---
### File: sdk/auto-drive.mdx
## Auto-Drive Package
### Introduction
The \`@autonomys/auto-drive\` package provides a set of tools to interact with the Autonomys Auto-Drive API.
### Features
- **Autonomys DSN**: Permanently store files on the Autonomys' DSN (Decentralized Store Network).
- **CID Management**: Just like with IPFS, each upload gets its own CID (Content Identifier).
- **TypeScript Support**: Fully typed for an enhanced developer experience.
### Auto Drive API documentation
Auto Drive API documentation with all it's function signatures is available [here](https://mainnet.auto-drive.autonomys.xyz/api/docs).

### Auto Gateway
Auto gateway is a unified gateway solution designed to seamlessly connect and access files or folders permanently stored on Autonomys Mainnet & Tesnet through a single, streamlined interface. The gateway is available [here](https://gateway.autonomys.xyz/).

### How to use Auto Drive SDK?
To interact with the Auto-Drive SDK, you'll need to create an API key. Follow these steps:
1. Go to Auto-Drive and login with your preffered SSO.
2. Once you're logged in, click on the **developers** section in the left sidebar menu.
3. In the developers section, click on **'Create API Key'**
4. Read the modal message and click on generate
### Auto Drive Dashboard
View your upload and download limits, access files uploaded by other users, and manage and share your submissions by logging in to Auto Drive:
1. Open [Auto Drive](https://ai3.storage/)
2. Sign in via Google, Discord or GitHub
.png)
3. On the Dashboard you will see:
- Your upload limit (currently **100MB** per month)
- Your download limit (currently **5GB** per month)
- A list of **uploaded files** and their **CIDs**
- Options to **Download**, **Share** or **Remove** each file

> *Note:* Removing a file does not delete it from the DSN as it is permanent storage. It only removes the file from your Dashboard.
4. Use the in-browser environment to upload, download or share files, or the SDK functions (described below) to upload files or folders via the CLI.

#### Creating an API key
Click on \`Profile\` to create your API key. Use this API key in the CLI to upload files or folders.

#### Sharing files
Click the \`Share\` button next to a file to share it using a link, or provide a user’s public ID to share all their files. Each user’s public ID is visible on their \`Profile\` page.

### Installation
Install the package via \`npm\` or \`yarn\`:
\`\`\`bash
# Using npm
npm install @autonomys/auto-drive
npm install @autonomys/auto-utils
# Using yarn
yarn add @autonomys/auto-drive
yarn add @autonomys/auto-utils
\`\`\`
### Importing
Import the \`auto-drive\` functions you need into your project:
\`\`\`typescript
// Import specific functions
import \{ fs,createAutoDriveApi \} from '@autonomys/auto-drive';
import \{ NetworkId \} from '@autonomys/auto-utils'
// Or import everything
import * as drive from '@autonomys/auto-drive';
import \{ NetworkId \} from '@autonomys/auto-utils'
\`\`\`
### Available functions
#### Upload operations
- \`uploadFile(api, file, options): Promise<string>\`: Uploads a file (using a buffer, \`File\`, or a custom interface) with optional encryption and compression. Returns the resulting CID as a string.
- \`uploadFileFromFilepath(api, filePath, options): Promise<string>\`: Uploads a file from filepath with optional encryption and compression. Returns the resulting CID as a string.
- \`uploadFileFromInput(api, file, options): Promise<string>\`: Uploads a file obtained from a browser's \`File\` API.
- \`uploadFolderFromInput(api, fileList, options): Promise<string>\`: Uploads a folder from a browser's \`FileList\`.
- \`uploadFileWithinFolderUpload(api, uploadId, file, options): Promise<string>\`: Uploads a file within an existing folder upload session.
- \`uploadObjectAsJSON(api, object, name?, options): Promise<string>\`: Serializes and uploads any object as a JSON file.
#### Download operations
- \`downloadFile(api, cid, password?): AsyncIterable<Buffer>\`: Downloads a file from its CID, with optional decryption using a password.
- \`getMyFiles(api, page, limit): Promise<PaginatedResult<ObjectSummary>>\`: Retrieves paginated list of user's files.
- \`searchByNameOrCIDInMyFiles(api, value): Promise<ObjectSummary[]>\`: Searches for files by name or CID within user's files.
- \`searchByNameOrCID(api, value): Promise<ObjectSummary[]>\`: Global search for files by name or CID.
#### Utility functions
- \`getPendingCredits(api): Promise<\{ upload: number; download: number \}>\`: Gets the current user's pending upload and download credits.
- \`getSubscriptionInfo(api): Promise<SubscriptionInfo>\`: Retrieves the current user's subscription information.
### Network configuration
As [Auto Drive](https://ai3.storage) is available on both Mainnet and the Taurus testnet, you need to configure the network when using the package:
\`\`\`ts
import \{ NetworkId \} from '@autonomys/auto-utils'
const api = createAutoDriveApi(\{
apiKey: 'your-api-key',
network: NetworkId.TAURUS | NetworkId.MAINNET
\})
\`\`\`
## Usage examples
### 1. Uploading a file from a filepath (Not available in browser)
\`\`\`typescript
import \{ fs,createAutoDriveApi \} from '@autonomys/auto-drive'
import \{ NetworkId \} from '@autonomys/auto-utils'
const api = createAutoDriveApi(\{ apiKey: 'your-api-key', network: NetworkId.TAURUS \}) // Initialize your API instance with API key
const filePath = 'path/to/your/file.txt' // Specify the path to your file
const options = \{
password: 'your-encryption-password', // Optional: specify a password for encryption
compression: true,
// an optional callback useful for large file uploads
onProgress?: (progress: number) => \{
console.log(\`The upload is completed is \$\{progress\}% completed\`)
\}
\}
const cid = await fs.uploadFileFromFilepath(api, filePath, options)
console.log(\`The file is uploaded and its cid is \$\{cid\}\`)
\`\`\`
### 2. Uploading a file using FILE interface
\`\`\`typescript
import \{ uploadFileFromInput, createAutoDriveApi \} from '@autonomys/auto-drive'
import \{ NetworkId \} from '@autonomys/auto-utils'
const api = createAutoDriveApi(\{ apiKey: 'your-api-key', network: NetworkId.TAURUS \}) // Initialize your API instance with API key
// e.g Get File from object from HTML event
const file: File = e.target.value // Substitute with your file
const options = \{
password: 'your-encryption-password', // Optional: specify a password for encryption
compression: true,
\}
const cid = await api.uploadFileFromInput(file, options)
console.log(\`The file is uploaded and its cid is \$\{cid\}\`)
\`\`\`
### 3. Uploading a folder (Not available in browser)
\`\`\`typescript
import \{ createAutoDriveApi, fs \} from '@autonomys/auto-drive'
import \{ NetworkId \} from '@autonomys/auto-utils'
const api = createAutoDriveApi(\{ apiKey: 'your-api-key', network: NetworkId.TAURUS \}) // Initialize your API instance with API key
const folderPath = 'path/to/your/folder' // Specify the path to your folder
const options = \{
uploadChunkSize: 1024 * 1024, // Optional: specify the chunk size for uploads
password: 'your-encryption-password', // Optional: If folder is encrypted
// an optional callback useful for large file uploads
onProgress: (progress: number) => \{
console.log(\`The upload is completed is \$\{progress\}% completed\`)
\},
\}
const folderCID = await fs.uploadFolderFromFolderPath(api, folderPath, options)
console.log(\`The folder is uploaded and its cid is \$\{folderCID\}\`)
\`\`\`
### 4. Uploading a file from a custom interface with \`GenericFile\`:
\`\`\`typescript
import \{ createAutoDriveApi \} from '@autonomys/auto-drive'
import \{ NetworkId \} from '@autonomys/auto-utils'
const api = createAutoDriveApi(\{ apiKey: 'your-api-key', network: NetworkId.TAURUS \}) // Initialize your API instance with API key
const buffer = Buffer.from(...);
const genericFile = \{
read: async function *() \{
yield buffer
\},
name: "autonomys-whitepaper.pdf",
mimeType: "application/pdf",
size: 1234556,
path: "autonomys-whitepaper.pdf"
\}
const options = \{
password: 'your-encryption-password', // Optional: specify a password for encryption
compression: true,
// an optional callback useful for large file uploads
onProgress?: (progress: number) => \{
console.log(\`The upload is completed is \$\{progress\}% completed\`)
\}
\}
const cid = api.uploadFile(genericFile, options)
console.log(\`The file is uploaded and its cid is \$\{cid\}\`)
\`\`\`
### 5. Downloading files
\`\`\`typescript
import \{ createAutoDriveApi \} from '@autonomys/auto-drive'
import \{ NetworkId \} from '@autonomys/auto-utils'
const api = createAutoDriveApi(\{ apiKey: 'your-api-key', network: NetworkId.TAURUS \}) // Initialize your API instance with API key
try \{
const cid = '..'
const stream = await api.downloadFile(cid)
let file = Buffer.alloc(0)
for await (const chunk of stream) \{
file = Buffer.concat([file, chunk])
\}
console.log('File downloaded successfully:', stream)
\} catch (error) \{
console.error('Error downloading file:', error)
\}
\`\`\`
### 6. Creating shareable download link
\`\`\`typescript
import \{ createAutoDriveApi \} from '@autonomys/auto-drive'
import \{ NetworkId \} from '@autonomys/auto-utils'
const api = createAutoDriveApi(\{ apiKey: 'your-api-key', network: NetworkId.TAURUS \}) // Initialize your API instance with API key
try \{
const cid = 'your-file-cid'
const publicUrl = await api.publishObject(cid)
console.log('Public download URL:', publicUrl)
\} catch (error) \{
console.error('Error publishing object:', error)
\}
\`\`\`
### 7. Example usage of \`getMyFiles\`
Here is an example of how to use the getMyFiles method to retrieve the root directories:
\`\`\`typescript
import \{ createAutoDriveApi \} from '@autonomys/auto-drive'
import \{ NetworkId \} from '@autonomys/auto-utils'
const api = createAutoDriveApi(\{ apiKey: 'your-api-key', network: NetworkId.TAURUS \}) // Initialize your API instance with API key
try \{
for (let i = 0; i < 10; i++) \{
const myFiles = await api.getMyFiles(i, 100)
console.log(\`Retrieved \$\{myFiles.rows.length\} files of \$\{myFiles.totalCount\} total\`)
for (const file of myFiles.rows) \{
console.log(\`\$\{file.name\} - \$\{file.headCid\}: \$\{file.size\}\`)
\}
\}
\} catch (error) \{
console.error('Error downloading file:', error)
\}
\`\`\`
---
### File: sdk/auto-utils.mdx
## 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\`:
\`\`\`bash
# 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:
\`\`\`typescript
// 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 with \`await\` for proper execution flow. Wrap asynchronous calls in \`try...catch\` blocks to handle potential errors gracefully.
#### Account and address utilities
- \`address(input): string\`: Standardizes an address format.
- \`createAccountIdType(api, address): Uint8Array\`: Creates an \`AccountId\` 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.
- \`createAutoDriveApi(api, networkId)\`: Connects to the Auto Drive API of the selected Network.
- \`disconnect(api): Promise<void>\`: Disconnects an API instance.
#### Cryptographic functions
- \`blake2b_256(data): string\`: Hashes data with BLAKE2b-256.
- \`concatenateUint8Arrays(...arrays): Uint8Array\`: Concatenates multiple \`Uint8Array\`s.
- \`stringToUint8Array(string): Uint8Array\`: Converts a string to \`Uint8Array\`.
#### Data storage
> *Note:* Be cautious when saving sensitive data using \`save\` and \`read\` 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
\`\`\`typescript
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
\`\`\`typescript
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
\`\`\`typescript
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
\`\`\`typescript
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
\`\`\`typescript
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
\`\`\`typescript
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
\`\`\`typescript
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\`
\`\`\`typescript
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
\`\`\`typescript
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)
\`\`\`typescript
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)
\`\`\`typescript
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
\`\`\`typescript
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
\`\`\`typescript
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);
\`\`\`
---
### File: sdk/auto-xdm.mdx
## Auto-XDM Package
### Introduction
The Autonomys Auto XDM SDK (@autonomys/auto-xdm) provides functionalities for cross-domain transfer of native tokens.
### Features
- **Cross-Domain Transfer**: Enable token transfers between consensus and domain wallets.
- **TypeScript Support**: Full TypeScript type definitions for an enhanced developer experience.
### Installation
Install the package via \`npm\` or \`yarn\`:
\`\`\`bash
# Using npm
npm install @autonomys/auto-xdm
# Using yarn
yarn add @autonomys/auto-xdm
\`\`\`
### Importing
Import the \`auto-xdm\` functions you need into your project:
\`\`\`typescript
// Import specific functions
import \{
transferToConsensus,
transferToDomainAccount20Type,
transferToDomainAccount32Type
\} from '@autonomys/auto-xdm';
// Or import everything
import * as xdm from '@autonomys/auto-xdm';
\`\`\`
### Available functions
#### Transfer functions
> *Note:* All transfer functions return a \`SubmittableExtrinsic\` that must be signed and sent. The \`amount\` parameter expects the smallest unit of the token (Shannon). For 18 decimals, multiply by 10^18 or use \`formatTokenAmount\` from \`auto-utils\`. Ensure a sufficient balance in the sending account to cover both the transfer and fees. Cross-domain transfers may take a few blocks to complete.
- \`transfer(api, destination, amount): Promise<SubmittableExtrinsic>\`: Base transfer function for cross-domain transfers.
- \`transferToConsensus(api, accountId32, amount): Promise<SubmittableExtrinsic>\`: Transfer tokens from a domain to the consensus chain.
- \`transferToDomainAccount20Type(api, destinationDomainId, accountId20, amount): Promise<SubmittableExtrinsic>\`: Transfer tokens from the consensus chain to an EVM address.
- \`transferToDomainAccount32Type(api, destinationDomainId, accountId32, amount): Promise<SubmittableExtrinsic>\`: Transfer tokens from the consensus chain to a Substrate address.
#### Query functions
> *Note:* Monitor transfer status using query functions.
- \`chainAllowlist(api): Promise<Codec>\`: Retrieves the list of allowed chains.
- \`channels(api, chainId): Promise<Codec>\`: Retrieves the list of channels
- \`consensusChannels(api): Promise<Codec>\`: Retrieves the list of consensus channels
- \`domainChannels(api, domainId): Promise<Codec>\`: Retrieves the list of domain channels
- \`allCancelledTransfers(api): Promise<Codec>\`: Retrieves all cancelled transfers.
- \`chainTransfers(api): Promise<Codec>\`: Retrieves all chain transfers.
- \`allDomainBalances(api): Promise<Codec>\`: Retrieves balances across all domains.
- \`domainBalances(api, domainId): Promise<Codec>\`: Retrieves balances for a specific domain.
- \`allUnconfirmedTransfers(api): Promise<Codec>\`: Retrieves pending transfers.
### Type definitions
\`\`\`typescript
type Amount = BigInt | number | string;
type Consensus = \{
type: 'consensus';
\};
type Domain = \{
type: 'domain';
domainId: number;
\};
type ChainOrDomain = Consensus | Domain;
\`\`\`
## Usage examples
### 1. Transfer from \`Consensus\` to \`Domain\` (EVM address)
\`\`\`typescript
import \{ activateWallet \} from '@autonomys/auto-utils'
import \{ transferToDomainAccount20Type \} from '@autonomys/auto-xdm'
const api = await activateWallet(\{ networkId: 'taurus', uri: '//alice' \})
const tx = await transferToDomainAccount20Type(
api,
0, // Receiver domain (0 is Auto EVM on Taurus Testnet)
'0x1234567890abcdef', // Receiver domain account
'1000000000000000000',
)
\`\`\`
### 2. Transfer from \`Consensus\` to \`Domain\` (Substrate address)
\`\`\`typescript
import \{ activateWallet \} from '@autonomys/auto-utils'
import \{ transferToDomainAccount32Type \} from '@autonomys/auto-xdm'
const api = await activateWallet(\{ networkId: 'taurus', uri: '//alice' \})
const tx = await transferToDomainAccount32Type(
api,
0, // Receiver domain (0 is Auto EVM on Taurus Testnet)
'su1234567890abcdef', // Receiver domain account
'1000000000000000000',
)
\`\`\`
### 3. Transfer from \`Domain\` to \`Consensus\`
\`\`\`typescript
import \{ activateWallet \} from '@autonomys/auto-utils'
import \{ transferToConsensus \} from '@autonomys/auto-xdm'
const api = await activateWallet(\{ networkId: 'taurus', domainId: 0, uri: '//alice' \})
const tx = await transferToConsensus(
api,
'su1234567890abcdef', // Receiver consensus account,
'1000000000000000000',
)
\`\`\`
### 4. Query domain balances
\`\`\`typescript
import \{ activateWallet \} from '@autonomys/auto-utils';
import \{ domainBalances \} from '@autonomys/auto-xdm';
(async () => \{
const \{ api \} = await activateWallet(\{
networkId: 'taurus'
\});
// Get balances for domain 0 (Auto EVM on the Taurus testnet)
const balances = await domainBalances(api, 0);
console.log('Domain balances:', balances.toString());
\})();
\`\`\`
### Best practices
1. **Error Handling**: Wrap asynchronous calls and transactions in \`try...catch\` blocks to handle potential errors gracefully:
\`\`\`typescript
try \{
const tx = await transferToConsensus(api, receiver, amount);
await tx.signAndSend(account);
\} catch (error) \{
console.error('Transfer failed:', error);
\}
\`\`\`
2. **Amount Formatting**: Use appropriate decimal places for token amounts:
- The \`amount\` parameter expects the smallest unit of the token (Shannon).
- For 18 decimals, multiply by 10^18 or use \`formatTokenAmount\` from \`auto-utils\`.
3. **API Management**: > Always disconnect the API instance after your operations are complete to free up resources:
\`\`\`typescript
try \{
// ... your code ...
\} finally \{
await api.disconnect();
\}
\`\`\`
---
### File: sdk/index.mdx
---
title: Auto SDK
---
## Auto SDK
### What is the Auto SDK?
The **Auto SDK** is a powerful toolkit of JavaScript/TypeScript packages for developers to seamlessly integrate with the Autonomys Network. It provides simple APIs for interacting with the *consensus* layer, utilizing *data storage*, managing *decentralized identities*, and (soon) handling *AI3 payments*, in addition to general-purpose functions essential for building decentralized applications (dApps)—all in JavaScript and TypeScript—abstracting away the complexities of blockchain and smart contracts.
### Key features:
- **Modular Architecture**: Use only the packages you need.
- **Easy to Use**: Simplifies blockchain operations with high-level functions.
- **Flexible**: Suitable for both beginners and experienced blockchain developers.
- **Open-source**: Built by and for the community.
### Why the Auto SDK?
- **Simplify Development**: Focus on your application's logic rather than blockchain intricacies.
- **Accelerate Time-to-Market**: Reduce development time with ready-to-use functions.
- **Ensure Compatibility**: Stay up-to-date with the latest Autonomys blockchain protocols.
- **Enhance Security**: Utilize well-tested code for critical operations like identity management.
## Packages
The Auto SDK monorepo contains multiple packages, each serving a specific purpose. All packages are published to \`npm\` under the \`@autonomys\` scope:
- **\`@autonomys/auto-utils\`**: Core utility functions for interacting with the Autonomys Network.
- **\`@autonomys/auto-consensus\`**: Functions for interacting with the consensus layer.
- **\`@autonomys/auto-drive\`**: Tools for preparing, uploading and managing data for on-chain storage.
## Quick Start Guide: Install and Code Example
A short video guide on installing the Auto SDK, along with a simple coding example demonstrating how to retrieve an account balance.
<iframe width="560" height="315" src="https://www.youtube.com/embed/B5J9fwE5-vI?si=Mt133r3I2QnCae0A" title="Auto SDK Quick Start Guide: Install and Code Example" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
## Step-by-step guide
### Requirements
- **\`Node.js\`** (version 14 or higher)
- **\`yarn\`** or **\`npm\`**
### Installation
Install the packages you need via \`npm\` or \`yarn\`. For example, to install \`@autonomys/auto-utils\` and \`@autonomys/auto-consensus\`:
#### Using \`npm\`
\`\`\`bash
npm install @autonomys/auto-utils @autonomys/auto-consensus
\`\`\`
#### Using \`yarn\`
\`\`\`bash
yarn add @autonomys/auto-utils @autonomys/auto-consensus
\`\`\`
### Cloning the repository and building locally (*optional*)
If you want to run the SDK packages locally or contribute to the SDK, clone the repository and build the packages from source. Setup instructions:
#### 1. Clone the repository
Open your terminal and run:
\`\`\`bash
git clone https://github.com/autonomys/auto-sdk.git
\`\`\`
#### 2. Navigate to the project directory
\`\`\`bash
cd auto-sdk
\`\`\`
#### 3. Install dependencies
\`\`\`bash
yarn install
\`\`\`
#### 4. Compile all packages
\`\`\`bash
yarn run build
\`\`\`
#### 5. Run tests on all packages
\`\`\`bash
yarn run test
\`\`\`
### Localhost testing (*optional*)
Test the SDK packages against a local Autonomys node:
#### 1. Verify OS and architecture settings
Edit the \`scripts/download.sh\` file and ensure that lines 3-7 match your current operating system and architecture:
\`\`\`bash
# Change the following variables as needed
# OS to download
OS="macos" # Options: macos | ubuntu | windows
# Architecture to download
ARCHITECTURE="aarch64" # Options: aarch64 | x86_64-skylake | x86_64-v2
\`\`\`
#### 2. Run the development script
Execute the following command to start the local node and farmer:
\`\`\`bash
node scripts/run-dev.js
\`\`\`
This script will:
1. Download the latest version of the node and farmer compatible with your OS and architecture (\`scripts/download.sh\`).
2. Start the node and create/insert the keystore (\`scripts/run-node.sh\`).
3. Start the farmer (\`scripts/run-farmer.sh\`).
4. Register the node as an operator, wait for synchronization, and then terminate the node and farmer (handled within \`scripts/run-dev.js\`).
5. Restart the node as an operator (\`scripts/run-operator.sh\`).
6. Restart the farmer (\`scripts/run-farmer.sh\`).
#### 3. Run tests on the local node
\`\`\`bash
bash scripts/localhost-run-test.sh
\`\`\`
The tests will automatically detect and execute on the local node and farmer.
## Next steps
With the Auto SDK set up locally, you're ready to start building and testing your blockchain applications. Explore the following pages for code examples and a functions overview.
---