Get Account
Returns the authentication key and sequence number for an account address on Aptos.
When to Use This Method​
GET /accounts/{address}
is essential for:
- Account Verification - Check if an account exists on-chain
- Transaction Building - Get sequence number for transaction submission
- Authentication - Retrieve authentication key for account operations
- Account Monitoring - Track account state changes
Parameters​
-
address -
string
(required)- The account address to query
- Format: 64 hex characters with or without
0x
prefix - Example:
0x1
or0x0000000000000000000000000000000000000000000000000000000000000001
-
ledger_version -
string
(optional)- Specific ledger version to query
- If not provided, uses the latest version
- Format: Unsigned 64-bit integer as string
Request Example​
curl -X GET "https://api-aptos-mainnet.n.dwellir.com/v1/YOUR_API_KEY/accounts/0x1" \
-H "Accept: application/json"
Response Format​
{
"sequence_number": "0",
"authentication_key": "0x0000000000000000000000000000000000000000000000000000000000000001"
}
Implementation Examples​
- TypeScript
- Python
- Rust
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
const config = new AptosConfig({
network: Network.MAINNET,
fullnode: "https://api-aptos-mainnet.n.dwellir.com/v1/YOUR_API_KEY",
});
const aptos = new Aptos(config);
async function getAccountInfo(address: string) {
try {
const account = await aptos.getAccountInfo({
accountAddress: address
});
console.log("Sequence Number:", account.sequence_number);
console.log("Authentication Key:", account.authentication_key);
return account;
} catch (error) {
if (error.status === 404) {
console.log("Account does not exist on chain");
return null;
}
throw error;
}
}
// Check multiple accounts
async function checkAccounts(addresses: string[]) {
const results = await Promise.allSettled(
addresses.map(addr => getAccountInfo(addr))
);
return results.map((result, index) => ({
address: addresses[index],
exists: result.status === "fulfilled" && result.value !== null,
data: result.status === "fulfilled" ? result.value : null
}));
}
from aptos_sdk.client import RestClient
from aptos_sdk.account_address import AccountAddress
client = RestClient("https://api-aptos-mainnet.n.dwellir.com/v1/YOUR_API_KEY")
def get_account_info(address: str):
try:
account = client.get_account(AccountAddress.from_str(address))
print(f"Sequence Number: {account['sequence_number']}")
print(f"Authentication Key: {account['authentication_key']}")
return account
except Exception as e:
if "404" in str(e):
print("Account does not exist on chain")
return None
raise e
# Monitor account creation
def wait_for_account(address: str, timeout: int = 30):
import time
start_time = time.time()
while time.time() - start_time < timeout:
account = get_account_info(address)
if account:
print(f"Account {address} found!")
return account
time.sleep(1)
raise TimeoutError(f"Account {address} not found within {timeout} seconds")
use aptos_sdk::rest_client::Client;
use aptos_sdk::types::account_address::AccountAddress;
use std::str::FromStr;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(
"https://api-aptos-mainnet.n.dwellir.com/v1/YOUR_API_KEY"
.parse()?
);
let address = AccountAddress::from_str("0x1")?;
match client.get_account(address).await {
Ok(account) => {
println!("Sequence Number: {}", account.sequence_number);
println!("Authentication Key: {}", account.authentication_key);
}
Err(e) if e.to_string().contains("404") => {
println!("Account does not exist on chain");
}
Err(e) => return Err(e.into()),
}
Ok(())
}
Common Use Cases​
1. Pre-Transaction Validation​
Verify account exists before sending transactions:
async function validateRecipient(recipientAddress: string) {
try {
const account = await aptos.getAccountInfo({
accountAddress: recipientAddress
});
// Account exists
return {
valid: true,
sequenceNumber: account.sequence_number,
authKey: account.authentication_key
};
} catch (error) {
if (error.status === 404) {
// Account doesn't exist - may need to be created
return {
valid: false,
needsCreation: true,
error: "Account not found on chain"
};
}
throw error;
}
}
2. Account Creation Detection​
Monitor when a new account is created on-chain:
class AccountMonitor {
private checkInterval: number = 1000; // 1 second
async waitForAccountCreation(
address: string,
maxAttempts: number = 30
): Promise<any> {
for (let i = 0; i < maxAttempts; i++) {
try {
const account = await aptos.getAccountInfo({
accountAddress: address
});
return account; // Account found
} catch (error) {
if (error.status === 404) {
// Account not yet created, wait and retry
await new Promise(resolve =>
setTimeout(resolve, this.checkInterval)
);
continue;
}
throw error;
}
}
throw new Error(`Account ${address} not created after ${maxAttempts} attempts`);
}
}
3. Sequence Number Management​
Track sequence numbers for transaction submission:
class SequenceTracker {
private sequenceCache = new Map<string, bigint>();
async getNextSequence(address: string): Promise<bigint> {
// Get cached sequence or fetch from chain
if (!this.sequenceCache.has(address)) {
const account = await aptos.getAccountInfo({
accountAddress: address
});
this.sequenceCache.set(address, BigInt(account.sequence_number));
}
const sequence = this.sequenceCache.get(address)!;
// Increment for next use
this.sequenceCache.set(address, sequence + 1n);
return sequence;
}
// Reset cache after errors
resetSequence(address: string) {
this.sequenceCache.delete(address);
}
}
4. Batch Account Queries​
Query multiple accounts efficiently:
async function batchGetAccounts(addresses: string[]) {
const batchSize = 10; // Process 10 at a time
const results = [];
for (let i = 0; i < addresses.length; i += batchSize) {
const batch = addresses.slice(i, i + batchSize);
const batchResults = await Promise.allSettled(
batch.map(addr =>
aptos.getAccountInfo({ accountAddress: addr })
)
);
results.push(...batchResults.map((result, index) => ({
address: batch[index],
success: result.status === "fulfilled",
data: result.status === "fulfilled" ? result.value : null,
error: result.status === "rejected" ? result.reason : null
})));
}
return results;
}
Error Handling​
Common errors and solutions:
Error Code | Description | Solution |
---|---|---|
404 | Account not found | Account may not exist yet, needs creation |
400 | Invalid address format | Ensure address is 64 hex characters |
503 | Service temporarily unavailable | Implement retry with backoff |
async function safeGetAccount(address: string, retries: number = 3) {
for (let i = 0; i < retries; i++) {
try {
return await aptos.getAccountInfo({ accountAddress: address });
} catch (error) {
if (error.status === 404) {
// Account doesn't exist - this is not an error to retry
return null;
}
if (error.status === 503 && i < retries - 1) {
// Service unavailable - wait and retry
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, i) * 1000)
);
continue;
}
throw error;
}
}
}
Response Headers​
Important response headers to monitor:
- X-APTOS-CHAIN-ID - Current chain ID
- X-APTOS-LEDGER-VERSION - Current ledger version
- X-APTOS-LEDGER-TIMESTAMP - Current ledger timestamp
- X-APTOS-EPOCH - Current epoch number
- X-APTOS-BLOCK-HEIGHT - Current block height
// Access response headers
const response = await fetch(
`https://api-aptos-mainnet.n.dwellir.com/v1/YOUR_API_KEY/accounts/${address}`,
{ headers: { 'Accept': 'application/json' } }
);
console.log("Chain ID:", response.headers.get("X-APTOS-CHAIN-ID"));
console.log("Ledger Version:", response.headers.get("X-APTOS-LEDGER-VERSION"));
Need help? Contact our support team or check the Aptos documentation.