Read Data

In this section, we will learn how to retrieve data from the Aptos blockchain using the SDK, as well as the distinctions between data retrieval in Web3 vs Web2.



Overview

As illustrated in this diagram, a smart contract functions much like a backend does in Web2. The Aptos SDK serves as a smart contract tool for reading and writing data to the Aptos blockchain.

Unlike for Web2, where data reading may require permissions, Web3 operates differently.

Instead, all data is public on-chain, allowing unrestricted access.


Web2Web3
Tools for Reading DataRESTful APIs, GraphQL, etc.Aptos SDK
Public Data AccessNo (permissioned)Yes (fully transparent)


Aptogotchi Example

Aptogotchi shuffle animation

Source Code

1. Install the Aptos SDK

Install the Aptos SDK in the frontend code directory.


import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
const config = new AptosConfig({ network: Network.TESTNET });
const aptosClient = new Aptos(config);


2. Prepare payload

Construct a payload object for the get_aptogotchi smart contract function:


const payload = {
function: `${CONTRACT_ADDRESS}::main::get_aptogotchi`,
functionArguments: [account.address],
};

${CONTRACT_ADDRESS}::main::get_aptogotchi

  • CONTRACT_ADDRESS is the address where this smart contract is deployed
  • main is the Module name, under the aptogotchi contract
  • get_aptogotchi is this view function's name

arguments:


3. Call the view function

Call the aptosClient.view function, passing in our payload object


const response = await aptosClient.view({ payload });
const [name, birthday, energyPoints, parts] = response;
const typedParts = parts as { body: number; ear: number; face: number };

Verify that an actual Aptogotchi Pet object is returned

Note: Move functions return Move types, thus you will have to cast each response field into its respective type

  • Ex: name: name as string