### Supra Account Example: Project Setup and Usage Source: https://docs.supra.com/network/move/typescript-sdk/guides/create-supra-accounts A comprehensive example demonstrating the setup of a TypeScript project with Supra's SDK and the usage of the SupraAccount class. It covers generating new accounts, importing from private keys, and deriving from mnemonics. ```typescript npm init && npm add -D typescript @types/node ts-node && npx tsc --init ``` ```bash npm install supra-l1-sdk ``` ```typescript import { SupraAccount} from "supra-l1-sdk"; ``` ```typescript const newAccount = new SupraAccount(); ``` ```typescript const accountFromPk = new SupraAccount( Buffer.from("YOUR_PRIVATE_KEY", "hex") ); ``` ```typescript const path = "m/44'/637'/0'/0'/0'"; const mnemonic = ""; const accountFromMnemonics = SupraAccount.fromDerivePath(path, mnemonic); ``` ```typescript import { SupraAccount } from "supra-l1-sdk"; async function main(){ const newAccount = new SupraAccount(); console.log("newAccount: ", newAccount.address()); const accountFromPk = new SupraAccount(Buffer.from("YOUR_PRIVATE_KEY", "hex")); console.log("accountFromPk Address: ", accountFromPk.address()); const path = "m/44'/637'/0'/0'/0'"; const mnemonic = ""; const accountFromMnemonics = SupraAccount.fromDerivePath(path, mnemonic); console.log("accountFromMnemonics: ", accountFromMnemonics.address()); } main(); ``` ```bash npx ts-node supra_account_example.ts ``` -------------------------------- ### Run EVM Client Example (Bash) Source: https://docs.supra.com/oracles/data-feeds/pull-oracle This command executes the EVM client example. Navigate to your project directory in the terminal and run this command to start the EVM client. ```bash cargo run --example evm_client ``` -------------------------------- ### Solidity: Example Consumer Contract Implementation Source: https://docs.supra.com/oracles/data-feeds/push-oracle A comprehensive example of a Solidity contract that integrates with Supra Oracles. It includes constructor setup, methods to update the S-Value feed, and functions to fetch single, multiple, and derived price data. ```solidity pragma solidity 0.8.19; import "./ISupraSValueFeed.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract ConsumerContract is Ownable { ISupraSValueFeed internal sValueFeed; constructor(ISupraSValueFeed _sValueFeed) { sValueFeed=_sValueFeed; } function updateSupraSvalueFeed(ISupraSValueFeed _newSValueFeed) external onlyOwner { sValueFeed = _newSValueFeed; } function getSupraSvalueFeed() external view returns(ISupraSValueFeed){ return sValueFeed; } function getPrice(uint256 _priceIndex) external view returns (ISupraSValueFeed.priceFeed memory) { return sValueFeed.getSvalue(_priceIndex); } function getPriceForMultiplePair(uint256[] memory _pairIndexes) external view returns (ISupraSValueFeed.priceFeed[] memory) { return sValueFeed.getSvalues(_pairIndexes); } function getDerivedValueOfPair(uint256 pair_id_1,uint256 pair_id_2,uint256 operation) external view returns(ISupraSValueFeed.derivedData memory){ return sValueFeed.getDerivedSvalue(pair_id_1,pair_id_2,operation); } } ``` -------------------------------- ### Supra L1 TypeScript SDK Quickstart Example Source: https://docs.supra.com/move/typescript-sdk A comprehensive example demonstrating how to initialize the SupraClient and SupraAccount, fund an account, set a receiver, and transfer Supra coins using the Supra L1 TypeScript SDK. ```typescript import { HexString, SupraAccount, SupraClient } from "supra-l1-sdk"; (async () => { // To Create Instance Of Supra Client, But In This Method We Don't Need To Pass ChainId. // ChainId Will Be Identified At Instance Creation Time By Making RPC Call. let supraClient = await SupraClient.init( "https://rpc-autonet.supra.com/" ); //Init a SupraAccount from a private key. let senderAccount = new SupraAccount( Uint8Array.from( Buffer.from( "2b9654793a999d1d487dabbd1b8f194156e15281fa1952af121cc97b27578d89", "hex" ) ) ); //Fund the sender account with the testnet faucet await supraClient.fundAccountWithFaucet(senderAccount.address()) //Set the receiver address let receiverAddress = new HexString( "0xb8922417130785087f9c7926e76542531b703693fdc74c9386b65cf4427f4e80" ); // To Transfer Supra Coin From Sender To Receiver let txResData = await supraClient.transferSupraCoin( senderAccount, receiverAddress, BigInt(1000), { enableTransactionWaitAndSimulationArgs: { enableWaitForTransaction: true, enableTransactionSimulation: true, }, } ); //Output the transaction data console.log("Transfer SupraCoin TxRes: ", txResData); })(); ``` -------------------------------- ### Run Supra Example Application (Rust) Source: https://docs.supra.com/oracles/data-feeds/pull-oracle Command to execute a specific example 'aptos_client' within the Supra project using Cargo. Assumes the project is cloned and dependencies are installed. ```rust cargo run --example aptos_client ``` -------------------------------- ### Solidity Complete VRF Callback Example Source: https://docs.supra.com/dvrf/build-supra-l1/request-random-numbers Provides a full example of a Solidity callback function that includes security verification using `supra_vrf::verify_callback` and then stores the verified random numbers. It demonstrates a typical workflow for integrating Supra's VRF into a smart contract. ```solidity public entry fun distribute( nonce: u64, message: vector, signature: vector, caller_address: address, rng_count: u8, client_seed: u64, ) acquires RandomNumberList { // SECURITY: Verify the callback is legitimate let verified_num: vector = supra_vrf::verify_callback( nonce, message, signature, caller_address, rng_count, client_seed ); // Store the verified random numbers let random_num_list = &mut borrow_global_mut(@example).random_numbers; let random_numbers = table::borrow_mut(random_num_list, nonce); *random_numbers = verified_num; // Your application logic here // Example: Use random numbers for lottery, NFT traits, etc. } ``` -------------------------------- ### Struct Serialization Example in Move Source: https://docs.supra.com/network/move/binary-canonical-serialization-bcs-standard-guide Illustrates the serialization of a struct in Move. The example shows a 'Color' struct with r, g, and b components, and explains how its fields are serialized in order. ```move struct Color { r: u8, // Red component g: u8, // Green component b: u8, // Blue component } // Color { r: 1, g: 2, b: 3 } serializes to [0x01, 0x02, 0x03] ``` -------------------------------- ### Initialize Supra Dapp Project Source: https://docs.supra.com/network/move/dev/supra-dapp-templates Npx command to execute the Supra Dapp Templates package and start the dapp scaffolding process. Requires Node.js and npm to be installed. It prompts the user for project name and template selection. ```sh npx @supranpm/supra-dapp-templates ``` -------------------------------- ### Run the Application (Bash) Source: https://docs.supra.com/oracles/data-feeds/pull-oracle Executes the main Javascript file to start the oracle pull example application. This command initiates the process of fetching proof data and interacting with the configured smart contract. ```bash node main.js ``` -------------------------------- ### Example Usage of Compute RSI - Move Source: https://docs.supra.com/oracles/technical-indicators/developer-guide/relative-strength-index-rsi Demonstrates how to call the `compute_rsi` function to get the 14-period RSI for SUPRA on a 4-hour timeframe with a 5% missing candle tolerance and how to interpret the results for overbought/oversold conditions. ```move // Get 14-period RSI for SUPRA on 4-hour timeframe let (rsi, missing) = supra_oracle_ti::compute_rsi( 2, // pair_id (SUPRA) 14, // period 14_400_000, // candle_duration (4 hours) 500 // 5% tolerance ); if (option::is_some(&rsi)) { let rsi_value = option::extract(&mut rsi); if (rsi_value < 30) { // Oversold condition } else if (rsi_value > 70) { // Overbought condition } } ``` -------------------------------- ### Managing Tasks - Estimate Automation Fees Source: https://docs.supra.com/automation/getting-started Provides an estimation of the automation fees for a given task, helping developers budget gas costs. ```APIDOC ## GET /websites/supra/automation/estimate-fees ### Description Estimates the automation fees required for a given task based on current network conditions and task parameters. ### Method GET ### Endpoint /websites/supra/automation/estimate-fees ### Parameters #### Query Parameters - **task_id** (string) - Required - The unique identifier of the task for which to estimate fees. - **function_id** (string) - Required - The identifier of the function to be executed. - **args** (string) - Optional - A JSON string representing the arguments for the function call. ### Request Example ``` GET /websites/supra/automation/estimate-fees?task_id=your_task_id_here&function_id=0x1::your_module::function_name&args={"recipient":"address_here","amount":"u64_value"} ``` ### Response #### Success Response (200) - **estimated_fee** (integer) - The estimated gas fee in Wei or the network's native currency. #### Response Example ```json { "estimated_fee": 100000000000000 } ``` #### Error Response (4xx/5xx) - **error** (string) - A message describing the error (e.g., invalid task ID, insufficient parameters). ``` -------------------------------- ### Initialize ExampleHolder Resource Source: https://docs.supra.com/oracles/data-feeds/push-oracle Initializes the `ExampleHolder` resource by creating a new object ID and an empty `VecMap` for feeds. The initialized resource is then shared, making it available for other modules. ```move fun init(ctx: &mut TxContext) { let resource = ExampleHolder { id: object::new(ctx), feeds: vec_map::empty(), }; transfer::share_object(resource); } ``` -------------------------------- ### Get Subscription Details (Aptos) Source: https://docs.supra.com/dvrf/build-supra-l1/v2-guide Retrieves subscription information for a given client address, including the start and end dates of the subscription and whether the user is part of the SNAP program. ```move get_subscription_by_client(client_address: address) ``` -------------------------------- ### Example: Query ETH Candles from Specific Time in Move Source: https://docs.supra.com/oracles/technical-indicators/developer-guide Demonstrates how to use the `get_latest_candles_from_specific_time` function to fetch 50 candles for the ETH/USDT pair on a 15-minute timeframe, starting from a specific Unix timestamp. ```move // Get candles for ETH on 15-min timeframe after a specific time let start_time = 1704067200000; // Jan 1, 2024 00:00:00 UTC let candles = supra_oracle_ti::get_latest_candles_from_specific_time( 50, // num_of_candles 3, // pair_id (ETH) 900_000, // candle_duration (15 min) start_time ); ``` -------------------------------- ### GET /rpc/v2/accounts/1/resources/0x1%3A%3Areconfiguration%3A%3AConfiguration (Get Last Epoch Start) Source: https://docs.supra.com/automation/your-first-automation-task/calculate-task-expiry-time-and-task-automation-fee Retrieves the start time of the last epoch, which is a crucial component in calculating the task expiry time. ```APIDOC ## GET /rpc/v2/accounts/1/resources/0x1%3A%3Areconfiguration%3A%3AConfiguration (Get Last Epoch Start) ### Description Fetches the start time of the last epoch. The returned timestamp is in microseconds. ### Method GET ### Endpoint `https://rpc-testnet.supra.com/rpc/v2/accounts/1/resources/0x1%3A%3Areconfiguration%3A%3AConfiguration` ### Parameters None ### Request Example ```bash curl -X 'GET' \ 'https://rpc-testnet.supra.com/rpc/v2/accounts/1/resources/0x1%3A%3Areconfiguration%3A%3AConfiguration' \ -H 'accept: application/json' ``` ### Response #### Success Response (200) - **last_reconfiguration_time** (string) - The timestamp in microseconds representing the start of the last epoch. #### Response Example ```json { "last_reconfiguration_time": "1747163851854115" } ``` #### Note Convert the `last_reconfiguration_time` from microseconds to seconds by dividing by 1,000,000 before using it in calculations. ``` -------------------------------- ### Get Events by Type (v1) - API Specification Source: https://docs.supra.com/network/move/rest-api/mainnet/events This OpenAPI 3.1.0 specification describes the 'Get events by type (v1)' endpoint for the Supra RPC Node. It allows fetching events within a specified block range (start and end) for a given event type. The maximum range allowed is 10 blocks. The response includes a list of events, each with a unique GUID, sequence number, type, and data. ```json { "openapi": "3.1.0", "info": { "title": "Supra RPC Node", "version": "59f32573d4ca6e9e0f8e04896600ea56ff9fd0bc" }, "tags": [ { "name": "Events", "description": "Events Api" } ], "servers": [ { "url": "https://rpc-mainnet.supra.com", "description": "RPC For Supra Scan and Faucet" }, { "url": "https://rpc-mainnet1.supra.com", "description": "RPC For nodeops group1" }, { "url": "https://rpc-mainnet2.supra.com", "description": "RPC For nodeops group2" }, { "url": "https://rpc-mainnet3.supra.com", "description": "RPC For nodeops group3" }, { "url": "https://rpc-mainnet4.supra.com", "description": "RPC For nodeops group4" }, { "url": "https://rpc-mainnet5.supra.com", "description": "RPC For nodeops group5" }, { "url": "https://rpc-wallet-mainnet.supra.com", "description": "RPC For Supra Wallet Mainnet" }, { "url": "https://rpc-suprascan-mainnet.supra.com", "description": "RPC For SupraScan Mainnet" }, { "url": "http://localhost:27000", "description": "LocalNet" } ], "paths": { "/rpc/v1/events/{event_type}": { "get": { "tags": [ "Events" ], "summary": "Get events by type (v1)", "description": "Get events by type.", "operationId": "events_by_type", "parameters": [ { "name": "start", "in": "query", "description": "Starting block height (inclusive).", "required": true, "schema": { "type": "integer", "format": "u-int64", "minimum": 0 }, "style": "form" }, { "name": "end", "in": "query", "description": "Ending block height (exclusive). The max range is 10 blocks, a.k.a. end - start <= 10.", "required": true, "schema": { "type": "integer", "format": "u-int64", "minimum": 0 }, "style": "form" }, { "name": "event_type", "in": "path", "description": "Canonical string representation of event type. E.g. 0000000000000000000000000000000a::module_name::type_name", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "List of Events contained in blocks", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Events" } } } } } } } }, "components": { "schemas": { "Events": { "type": "object", "required": [ "data" ], "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Event" } } } }, "Event": { "type": "object", "description": "On-chain event.", "required": [ "guid", "sequence_number", "type", "data" ], "properties": { "guid": { "type": "string", "description": "The globally unique identifier of this event stream." }, "sequence_number": { "type": "integer", "format": "u-int64", "minimum": 0 }, "type": { "type": "string", "description": "The `MoveType` of the event" }, "data": { "description": "The JSON representation of the event" } } } } } } ``` -------------------------------- ### Run Supra Project Source: https://docs.supra.com/network/move/getting-started/your-first-dapp-with-starkey This command is used to start the Supra project after setting up the necessary files and configurations. It assumes that the project has been initialized with npm. ```bash npm start ``` -------------------------------- ### Initialize TypeScript Project and Install SDK Source: https://docs.supra.com/network/move/typescript-sdk/guides/publish-a-package These commands set up a new TypeScript project and install the necessary dependencies, including the Supra SDK. It initializes an npm project, adds TypeScript and its types, and configures TypeScript compilation. ```bash npm init && npm add -D typescript @types/node ts-node && npx tsc --init ``` ```bash npm install supra-l1-sdk ``` -------------------------------- ### Run Supra Node Management Scripts Installer Source: https://docs.supra.com/network/node/node-upgrade-guide-mainnet/download-the-node-management-scripts Executes the `install_management_scripts.sh` script to install the node management tools. This script handles the setup of utilities for node operations. ```shell ./install_management_scripts.sh ``` -------------------------------- ### Initialize Hardhat Project for SupraDAO Source: https://docs.supra.com/network/evm/overview/build-on-supraevm/hardhat/start-building Sets up the project directory, initializes Hardhat, and prepares the configuration file. Requires Node.js and npm/yarn to be installed. This step creates the basic project structure. ```bash mkdir SupDAO cd SupDAO npx hardhat init ``` -------------------------------- ### Get account resources (v2) Source: https://docs.supra.com/network/move/rest-api/testnet/accounts Get account resources by address. Supports pagination using count and start parameters. ```APIDOC ## GET /rpc/v2/accounts/{address}/resources ### Description Get account resources by address. ### Method GET ### Endpoint /rpc/v2/accounts/{address}/resources ### Parameters #### Path Parameters - **address** (string) - Required - Address of account with or without a 0x prefix #### Query Parameters - **count** (integer) - Optional - Maximum number of items to return. Default is 20. - **start** (string) - Optional - Cursor specifying where to start for pagination. Use the cursor returned by the API when making the next request. ### Request Example ```json { "example": "request body not applicable for GET request" } ``` ### Response #### Success Response (200) - **resources** (array) - A list of Move Resources. - **cursor** (string) - The hex-encoded bytes of the state key of the last resource in the list. #### Response Example ```json { "resources": [ { "type": "string", "data": {} } ], "cursor": "0x..." } ``` ``` -------------------------------- ### Build and Run Frontend Source: https://docs.supra.com/network/move/dev/supra-dapp-templates npm commands to build the frontend of the dapp and start the development server. Assumes the Supra StarKey Wallet Dapp Template has been used. Requires Node.js and npm. ```bash npm run build npm start ``` -------------------------------- ### Initialize Foundry Project Source: https://docs.supra.com/network/evm/overview/build-on-supraevm/foundry/start-building Creates a new Foundry project and navigates into its directory. This is the first step to start building on SupraEVM. ```bash forge init foundry-project cd foundry-project ``` -------------------------------- ### Get Table Item (v2) Request Body Examples Source: https://docs.supra.com/network/move/rest-api/mainnet/tables Examples of the JSON request body for the 'Get table item (v2)' endpoint. These demonstrate how to specify the key type, value type, and the key itself for retrieving an item from a Move table. The API returns a 400 error if these types cannot be parsed correctly. ```json { "key_type": "u64", "value_type": "0x1::multisig_voting::Proposal<0x1::governance_proposal::GovernanceProposal>", "key": "12" } ``` ```json { "key_type": "u64", "value_type": "0x1::string::String", "key": "42" } ``` -------------------------------- ### Define ExampleHolder and ExampleEntry Structs for Price Feeds Source: https://docs.supra.com/oracles/data-feeds/push-oracle Defines the `ExampleHolder` resource to store price feeds and `ExampleEntry` to represent individual feed details. `ExampleHolder` contains a map of feed IDs to `ExampleEntry` objects. ```move struct ExampleHolder has key, store { id: UID, feeds: VecMap, } struct ExampleEntry has store, copy, drop { value: u128, decimal: u16, timestamp: u128, round: u64, } ``` -------------------------------- ### Initialize Project and Install TypeScript Source: https://docs.supra.com/network/move/typescript-sdk Initializes a new Node.js project, installs TypeScript and its types, configures TypeScript, and sets up a source directory for your code. This prepares the environment for using the SDK. ```sh npm init && npm add -D typescript @types/node ts-node && npx tsc --init && mkdir src && > src/quickstart.ts ``` -------------------------------- ### Install Node Monitoring Telegraf Script (Other Distributions) Source: https://docs.supra.com/network/node/node-operator-faq This command installs the Telegraf monitoring agent on distributions other than CentOS. It requires the API key to be exported beforehand. This script is used for general node monitoring setup. ```bash sudo -E ./nodeops-monitoring-telegraf.sh ``` -------------------------------- ### Create Deployment Script for SimpleStorage Source: https://docs.supra.com/network/evm/overview/build-on-supraevm/foundry/start-building A Foundry script to deploy the SimpleStorage contract. It reads the private key from environment variables and uses vm.startBroadcast to handle transaction broadcasting. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "forge-std/Script.sol"; import "../src/SimpleStorage.sol"; contract DeploySimpleStorage is Script { function run() external { uint256 privateKey = vm.envUint("PRIVATE_KEY"); vm.startBroadcast(privateKey); new SimpleStorage(); vm.stopBroadcast(); } } ``` -------------------------------- ### Enum Serialization Example in Move Source: https://docs.supra.com/network/move/binary-canonical-serialization-bcs-standard-guide Provides an example of enum serialization in Move. Enums are serialized using a Uleb128 variant index, followed by the serialized data of the chosen variant. ```move // Example enum definition enum PaymentMethod has drop { Cash(u64), // Variant 0 CreditCard(vector), // Variant 1 Crypto(address), // Variant 2 } // Serialization examples: // PaymentMethod::Cash(1000) => [0x00, 0xe8, 0x03] (variant 0 + amount) // PaymentMethod::CreditCard(b"1234") => [0x01, 0x04, 0x31, 0x32, 0x33, 0x34] (variant 1 + length + data) // PaymentMethod::Crypto(@0x1) => [0x02, ...32 bytes of address] (variant 2 + address) ``` -------------------------------- ### SupraClient Constructor Example Source: https://docs.supra.com/network/move/python-sdk Demonstrates how to initialize the SupraClient with a base URL for connecting to the Supra blockchain's RPC endpoint. An optional client configuration can also be provided. ```python from supra_sdk.clients.rest import SupraClient # Initialize client with RPC endpoint client = SupraClient("https://rpc-testnet.supra.com") # The client will be used for subsequent network interactions. # Remember to close the client when done, e.g., await client.close() ``` -------------------------------- ### Solidity - Gas Optimization for Automation Contracts Source: https://docs.supra.com/automation/your-first-automation-task/create-the-move-smart-contract Demonstrates gas optimization techniques for Supra automation contracts by initializing storage once in `init_module` and avoiding repeated initialization within the automation task function. This minimizes gas fees by performing storage creation only when necessary. ```solidity fun init_module(account: &signer) { move_to(account, Counter { value: 0, ... }); } public entry fun auto_increment(account: &signer) acquires Counter { let counter = borrow_global_mut(account_addr); counter.value = counter.value + 1; } ``` -------------------------------- ### Solidity: Get S-Values for Multiple Crypto Prices Source: https://docs.supra.com/oracles/data-feeds/push-oracle Retrieves S-Value price feeds for multiple trading pairs simultaneously using an array of price indexes. This is an efficient way to get data for several pairs at once. ```solidity // requesting s-values for multiple pairs function getPriceForMultiplePair(uint256[] memory _pairIndexes) external view returns (ISupraSValueFeed.priceFeed[] memory) { return sValueFeed.getSvalues(_pairIndexes); } ``` -------------------------------- ### GET /rpc/v2/accounts/{address}/transactions Source: https://docs.supra.com/network/move/rest-api/mainnet/accounts Retrieves a list of finalized transactions sent by a specified move account. Supports pagination with 'count' and 'start' parameters. ```APIDOC ## GET /rpc/v2/accounts/{address}/transactions ### Description List of finalized transactions sent by the move account. Return max 100 transactions per request. ### Method GET ### Endpoint `/rpc/v2/accounts/{address}/transactions` ### Parameters #### Path Parameters - **address** (string) - Required - Address of account with or without a 0x prefix #### Query Parameters - **count** (integer) - Optional - Maximum number of items to return. Default is 20. - **start** (integer) - Optional - Starting sequence number. If provided, return `:count` of transactions starting from this sequence number in ascending order. If not provided, return `:count` of most recent transactions in descending order. ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **record** (array) - List of transactions from the move account. - **authenticator** (object) - The cryptographic material that was submitted with the transaction, according to its type. - **hash** (string) - Hex encoded hash - **header** (object) - Transaction header information. - **payload** (object) - The deserialized payload of the transaction according to its type. - **status** (object) - Transaction execution status. #### Response Example ```json { "record": [ { "authenticator": {}, "hash": "0x123abc", "header": {}, "payload": {}, "status": {} } ] } ``` ``` -------------------------------- ### Navigate to Directory Source: https://docs.supra.com/network/move/dev/supra-dapp-templates Shell command to navigate to a desired workspace directory before initiating dapp template setup. No external dependencies are required. ```sh cd your/workspace ``` -------------------------------- ### Start Supra CLI Container with Docker Compose (Bash) Source: https://docs.supra.com/network/move/getting-started/supra-cli-with-docker Downloads the latest Docker Compose file for the Supra CLI and uses it to create and start the CLI container in detached mode. This command ensures you have the latest version of the CLI and its dependencies running. ```bash curl https://raw.githubusercontent.com/supra-labs/supra-dev-hub/refs/heads/main/Scripts/cli/compose.yaml | docker compose -f - up -d ``` -------------------------------- ### Supra NFT Collection and Token Management Example Source: https://docs.supra.com/network/move/python-sdk A comprehensive example demonstrating the creation and management of an NFT collection and individual tokens using the Supra Python SDK. This example covers account generation, faucet usage, creating collections and tokens, retrieving data, and transferring tokens between accounts. ```python import asyncio import json from examples.common import RPC_NODE_URL from supra_sdk.account import Account from supra_sdk.clients import SupraTokenClient from supra_sdk.clients.rest import SupraClient async def main(): supra_client = SupraClient(RPC_NODE_URL) token_client = SupraTokenClient(supra_client) alice = Account.generate() bob = Account.generate() collection_name = "Alice's" token_name = "Alice's first token" property_version = 0 print(f"Alice account address: {alice.address()}") print(f"Bob account address: {bob.address()}") await supra_client.faucet(alice.address()) await supra_client.faucet(bob.address()) print("\n=== Creating Collection and Token ===") await token_client.create_collection( alice, collection_name, "Alice's simple collection", "https://supra.com" ) await token_client.create_token( alice, collection_name, token_name, "Alice's simple token", 1, "https://supra.dev/img/temp.jpeg", 0, ) collection_data = await token_client.get_collection( alice.address(), collection_name ) print( f"Alice's collection: {json.dumps(collection_data, indent=4, sort_keys=True)}" ) balance = await token_client.get_token_balance( alice.address(), alice.address(), collection_name, token_name, property_version ) print(f"Alice's token balance: {balance}") token_data = await token_client.get_token_data( alice.address(), collection_name, token_name ) print(f"Alice's token data: {json.dumps(token_data, indent=4, sort_keys=True)}") print("\n=== Transferring the token to Bob ===") await token_client.offer_token( alice, bob.address(), alice.address(), collection_name, token_name, property_version, 1, ) await token_client.claim_token( bob, alice.address(), alice.address(), collection_name, token_name, property_version, ) alice_balance = token_client.get_token_balance( alice.address(), alice.address(), collection_name, token_name, property_version ) bob_balance = token_client.get_token_balance( bob.address(), alice.address(), collection_name, token_name, property_version ) [alice_balance, bob_balance] = await asyncio.gather(*[alice_balance, bob_balance]) print(f"Alice's token balance: {alice_balance}") print(f"Bob's token balance: {bob_balance}") print("\n=== Transferring the token back to Alice using MultiAgent ===") await token_client.direct_transfer_token( bob, alice, alice.address(), collection_name, token_name, 0, 1 ) alice_balance = token_client.get_token_balance( alice.address(), alice.address(), collection_name, token_name, property_version ) bob_balance = token_client.get_token_balance( bob.address(), alice.address(), collection_name, token_name, property_version ) [alice_balance, bob_balance] = await asyncio.gather(*[alice_balance, bob_balance]) print(f"Alice's token balance: {alice_balance}") print(f"Bob's token balance: {bob_balance}") await supra_client.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Last Epoch Start Time (Supra Network) Source: https://docs.supra.com/automation/your-first-automation-task/calculate-task-expiry-time-and-task-automation-fee Retrieves the last epoch start time from the Supra network. The response contains `last_reconfiguration_time` in microseconds, which needs to be converted to seconds for further calculations. This is a crucial step in determining task expiry. ```powershell curl -X 'GET' \ 'https://rpc-testnet.supra.com/rpc/v2/accounts/1/resources/0x1%3A%3Areconfiguration%3A%3AConfiguration' \ -H 'accept: application/json' ``` -------------------------------- ### Initialize StarKey Provider and State Hooks Source: https://docs.supra.com/network/move/getting-started/your-first-dapp-with-starkey Sets up the main React component to interact with the StarKey wallet. It initializes state variables for StarKey installation status, connected accounts, and network data, and obtains the 'supraProvider' instance. ```typescript import React, {useEffect, useState} from "react"; import { HexString, TxnBuilderTypes, BCS } from "supra-l1-sdk"; function App() { let supraProvider: any = typeof window !== "undefined" && (window as any)?.starkey?.supra; const [isStarkeyInstalled, setIsStarkeyInstalled] = useState(!!supraProvider); const [accounts, setAccounts] = useState([]); const [networkData, setNetworkData] = useState(); return
; } ``` -------------------------------- ### Navigate into Project Directory Source: https://docs.supra.com/network/move/getting-started/your-first-dapp-with-starkey Changes the current working directory to the newly created 'supra-dapp' project folder. This is a standard command-line operation to access project files and run subsequent commands within the project context. ```bash cd supra-dapp ``` -------------------------------- ### Get Coin Transactions (v2) - API Endpoint Source: https://docs.supra.com/network/move/rest-api/testnet/accounts This OpenAPI 3.1.0 definition describes the GET endpoint for retrieving v2 coin transactions for a given account. It supports pagination with 'count' and 'start' parameters and returns a list of finalized transactions. Dependencies include OpenAPI 3.1.0. ```json { "openapi": "3.1.0", "info": { "title": "Supra RPC Node", "version": "59f32573d4ca6e9e0f8e04896600ea56ff9fd0bc" }, "tags": [ { "name": "Accounts", "description": "Accounts Api" } ], "servers": [ { "url": "https://rpc-testnet.supra.com", "description": "RPC For Supra Scan and Faucet" }, { "url": "https://rpc-wallet-testnet.supra.com", "description": "RPC For Wallet" }, { "url": "https://rpc-suprascan-testnet.supra.com", "description": "RPC For Suprascan" }, { "url": "https://rpc-archive-testnet.supra.com", "description": "RPC For Suprascan" }, { "url": "https://rpc-suprascan-reprocessing-testnet.supra.com", "description": "RPC For Suprascan" }, { "url": "https://rpc-testnet1.supra.com", "description": "RPC For nodeops group1" }, { "url": "http://localhost:27000", "description": "LocalNet" } ], "paths": { "/rpc/v2/accounts/{address}/coin_transactions": { "get": { "tags": [ "Accounts" ], "summary": "Get coin transactions (v2)", "description": "List of finalized coin withdraw/deposit transactions relevant to the move account. Return max 100 transactions per request.\nIt includes both transactions sent from and received by the account.\n\n", "operationId": "coin_transactions_v2", "parameters": [ { "name": "address", "in": "path", "description": "Address of account with or without a 0x prefix", "required": true, "schema": { "type": "string" } }, { "name": "count", "in": "query", "description": "Maximum number of items to return. Default is 20.", "required": false, "schema": { "type": "integer", "minimum": 0 }, "style": "form" }, { "name": "start", "in": "query", "description": "The cursor that the search should start from. The cursor for a given transaction can be derived by adding\nits index (where indexes start from zero) in the block in which it became finalized to the timestamp of the\nblock.\n\nDuring a paginated query, the cursor returned in the previous page should be used as the starting cursor of the next page.\n\nIf provided, return \":count\" of transactions starting from this cursor in ascending order.\nIf not provided, return \":count\" of most recent transactions in descending order.", "required": false, "schema": { "type": "integer", "format": "u-int64", "minimum": 0 }, "style": "form" } ], "responses": { "200": { "description": "List of *finalized* transactions sent from and received by the move account.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AccountCoinStatementV2" } } } } } } } }, "components": { "schemas": { "AccountCoinStatementV2": { "type": "object", "required": [ "record", "cursor" ], "properties": { "record": { "type": "array", "items": { "$ref": "#/components/schemas/TransactionInfoV2" } }, "cursor": { "type": "integer", "format": "u-int64", "minimum": 0 } } }, "TransactionInfoV2": { "type": "object", "description": "Information about a Supra transaction.", "required": [ "authenticator", "hash", "header", "payload", "status" ], "properties": { "authenticator": { "type": "object", "description": "The cryptographic material that was submitted with the transaction, according to its type." }, "block_header": { "oneOf": [ { "type": "null" }, { "$ref": "#/components/schemas/BlockHeaderInfo", "description": "Metadata about the block containing the transaction, if any. This field should\nnot be set if this [TransactionInfoV2] is yet to be included in a [Block]." } ] }, "hash": { "$ref": "#/components/schemas/Hash" }, "header": { "$ref": "#/components/schemas/SmrTransactionHeader" }, "payload": { "type": "object", "description": "The deserialized payload of the transaction according to its type." }, "output": { "oneOf": [ { "$ref": "#/components/schemas/TransactionOutput" }, { "type": "null" } ] }, "status": { "$ref": "#/components/schemas/TxExecutionStatus" } } }, "BlockHeaderInfo": { "type": "object", "description": "Metadata about a Supra block.", "required": [ "author", "hash", "height", "parent", "timestamp", "view" ], "properties": { "author": { "$ref": "#/components/schemas/Identity" }, "hash": { "$ref": "#/components/schemas/Hash" }, "height": { "oneOf": [ { "type": "integer", "format": "u-int64", "minimum": 0 } ], "description": "Number of blocks before this block in the chain (including the genesis block)." }, "parent": { "$ref": "#/components/schemas/Hash" }, "timestamp": { "$ref": "#/components/schemas/SmrTimestamp" }, "view": { "$ref": "#/components/schemas/View" } } }, "Identity": { "type": "string", "description": "Hex encoded identity." }, "Hash": { "type": "string", "description": "Hex encoded hash" }, "SmrTimestamp": { "type": "object", "required": [ "timestamp" ], "properties": { "timestamp": { "type": "integer", "format": "u-int64", "description": "The timestamp as measured in the number of microseconds since the unix epoch.", "minimum": 0 } } }, "View": { "type": "object", "required": [ "epoch_id", "round" ], "properties": { "epoch_id": { "$ref": "#/components/schemas/EpochId", "description": "Identifier of the consensus epoch." }, "round": { "oneOf": [ { "type": "integer", "format": "u-int64", "minimum": 0 } ], "description": "Identifier of the consensus round." } } }, "EpochId": { "type": "object", "r" } } } } ``` -------------------------------- ### Example: Auto Wallet Top-Up Functionality (Pseudocode) Source: https://docs.supra.com/automation/smart-contract-integration Demonstrates a pseudocode example of an 'auto_top_up' function. This function checks a user's balance and triggers a transfer if the balance falls below a specified minimum. It highlights the logic for automated wallet refills based on predefined conditions. ```pseudocode //pseudocode public entry fun auto_top_up(source: &signer, user: address, min_balance: u64, top_up_amount: u64) { let current_balance = balance_of(user); if (current_balance < min_balance) { transfer(source, user, top_up_amount); } } ```