### Start Local Network with Example Data Setup Source: https://docs.sui.io/build/sui-local-network Initiate a local Sui network with genesis regeneration, faucet, indexer, and GraphQL enabled. This is a prerequisite for generating example data. ```bash sui start --force-regenesis --with-faucet --with-indexer --with-graphql ``` -------------------------------- ### Install Dependencies and Start Local Server Source: https://docs.sui.io/references/contribute/contribution-process Install project dependencies using pnpm and start the local development server to preview documentation changes. ```bash pnpm install pnpm start ``` -------------------------------- ### Prerequisite Snippet Example Source: https://docs.sui.io/references/contribute/mdx-components Shows how to format prerequisite requirements for guides using a reusable snippet. It includes installation, setup, and token acquisition steps. ```jsx ## Prerequisites - [x] [Install the latest version of Sui](/getting-started/onboarding/sui-install). - [x] Set up your Sui account and CLI environment. **Create Sui account and setup CLI environment** ```sh $ sui client ``` If this is the first time running the `sui client` CLI tool, it asks you to provide a Sui full node server URL and a meaningful environment alias. It also generates an address for you. If this is not your first time running `sui client`, then you already have a `client.yaml` file in your local environment. If you'd like to create a new address for this tutorial, use the command: ```sh $ sui client new-address ed25519 ``` - [x] Obtain test tokens. **How to obtain tokens** If you are connected to Devnet or Testnet networks, use the [Faucet UI](https://faucet.sui.io/) to request tokens. If you are connected to a local full node, [learn how to get local network tokens](/getting-started/onboarding/local-network). ``` -------------------------------- ### Clone the Only Fins Example App Repository Source: https://docs.sui.io/sui-stack/walrus/only-fins Clone the example application's repository and navigate into the frontend directory to begin the setup process. ```bash git clone https://github.com/MystenLabs/onlyfins-example-app.git cd onlyfins-example-app/frontend ``` -------------------------------- ### Configure Backend Environment Variables Source: https://docs.sui.io/getting-started/examples/event-indexer Navigate to the backend directory, install dependencies, and copy the example environment file. Update the .env file with the Package ID, Module Name, Private Key, and Users Counter Object ID obtained from the publish step. ```bash $ cd ../backend $ npm install $ cp env.example .env ``` ```dotenv PACKAGE_ID=PACKAGE_ID_FROM_STEP_2 MODULE_NAME=indexer PRIVATE_KEY=YOUR_BASE64_PRIVATE_KEY USERS_COUNTER_OBJECT_ID=COUNTER_OBJECT_ID_FROM_STEP_2 ``` -------------------------------- ### Complete Balance Manager Setup Workflow Source: https://docs.sui.io/onchain-finance/deepbookv3-sdk/balance-manager This asynchronous function guides through the complete setup process for a balance manager, including creation, sharing, minting capabilities, and transferring them to the owner. ```typescript // Example: Complete balance manager setup workflow completeSetup = async (tx: Transaction) => { const ownerAddress = '0x123...'; // Step 1: Create manager with custom owner const manager = tx.add(this.balanceManager.createBalanceManagerWithOwner(ownerAddress)); // Step 2: Share the manager tx.add(this.balanceManager.shareBalanceManager(manager)); // Step 3: Mint capabilities const tradeCap = tx.add(this.balanceManager.mintTradeCap('MANAGER_1')); const depositCap = tx.add(this.balanceManager.mintDepositCap('MANAGER_1')); const withdrawCap = tx.add(this.balanceManager.mintWithdrawalCap('MANAGER_1')); // Step 4: Transfer capabilities to owner tx.transferObjects([depositCap, withdrawCap, tradeCap], ownerAddress); }; ``` -------------------------------- ### Install Dependencies and Generate Key Pair Source: https://docs.sui.io/getting-started/examples/merchant-ctf Installs project dependencies and generates a new key pair for transaction signing. This is the initial setup step before running the merchant script. ```bash $ pnpm install $ pnpm init-keypair ``` -------------------------------- ### Clone Hello World Project Source: https://docs.sui.io/getting-started/onboarding/hello-world Clone the "Hello, World!" example project from GitHub to start building your first Sui application. Navigate into the project's hello-world directory. ```bash git clone https://github.com/MystenLabs/sui-stack-hello-world.git cd sui-stack-hello-world/move/hello-world ``` -------------------------------- ### Solitaire Frontend Configuration Source: https://docs.sui.io/sui-stack/enoki/solitaire Install frontend dependencies, copy the environment example, and update the .env file with your specific configuration values. ```bash cd ../../app pnpm install cp .env.example .env ``` -------------------------------- ### Deepbook Margin SDK Setup and Trading Example Source: https://docs.sui.io/onchain-finance/deepbook-margin-sdk Demonstrates initializing the DeepBookMarginTrader, performing margin manager operations like deposit and borrow, placing leveraged orders, and interacting with margin pools. Requires a private key and optionally pre-configured margin managers. ```tsx (async () => { const privateKey = ''; // Can encapsulate this in a .env file // Initialize with margin managers if created const marginManagers = { MARGIN_MANAGER_1: { address: '', poolKey: 'SUI_DBUSDC', }, }; const traderClient = new DeepBookMarginTrader(privateKey, 'testnet', marginManagers); const tx = new Transaction(); // Margin manager contract calls traderClient.client.deepbook.marginManager.deposit('MARGIN_MANAGER_1', 'DBUSDC', 10000)(tx); traderClient.client.deepbook.marginManager.borrowBase('MARGIN_MANAGER_1', 'SUI_DBUSDC', 100)(tx); // Place leveraged orders traderClient.client.deepbook.poolProxy.placeLimitOrder({ poolKey: 'SUI_DBUSDC', marginManagerKey: 'MARGIN_MANAGER_1', clientOrderId: '12345', price: 2.5, quantity: 100, isBid: true, payWithDeep: true, })(tx); // Margin pool operations const supplierCap = tx.add(traderClient.client.deepbook.marginPool.mintSupplierCap()); traderClient.client.deepbook.marginPool.supplyToMarginPool('DBUSDC', supplierCap, 5000)(tx); let res = await traderClient.signAndExecute(tx); console.dir(res, { depth: null }); })(); ``` -------------------------------- ### Clone Asset Tokenization Repository Source: https://docs.sui.io/onchain-finance/tokenized-assets/deploy-tokenized-asset Clone the repository and navigate to the setup directory. Then copy the environment template and install dependencies. ```sh git clone https://github.com/MystenLabs/asset-tokenization.git cd asset-tokenization cp setup/.env.template setup/.env cd setup && npm install ``` -------------------------------- ### Configure Frontend Environment Variables Source: https://docs.sui.io/getting-started/examples/nft-app Navigate to the frontend application directory, install dependencies, copy the example environment file, and update it with the published Package ID and HeroRegistry Object ID. ```bash $ cd ../../app/my-first-sui-dapp $ pnpm install $ cp .env.example .env ``` -------------------------------- ### Configure .env Variables Source: https://docs.sui.io/getting-started/examples/plinko Install dependencies and copy the example .env file. Edit the .env file with the specific values obtained from the Move package publish step, including network name, package address, wallet address, private key, and object IDs. ```bash cd ../app pnpm install cd ../setup pnpm install cp .env.example .env ``` -------------------------------- ### Install libpq-dev on Linux Source: https://docs.sui.io/getting-started/onboarding/install-source Installs the development package for libpq, the PostgreSQL C client library. This is required if using the `--with-indexer` and `--with-graphql` options with `sui start`. ```sh $ sudo apt-get install libpq-dev ``` -------------------------------- ### Sui Start Command Options Source: https://docs.sui.io/build/sui-local-network Use these options with `sui start` to customize your local network. Run `sui start --help` for a full list. ```bash --network.config Config directory that will be used to store network config, node db, keystore. sui genesis -f --with-faucet generates a genesis config that can be used to start this process. Use with caution as the `-f` flag will overwrite the existing config directory. We can use any config dir that is generated by the `sui genesis` --force-regenesis A new genesis is created each time this flag is set, and state is not persisted between runs. Only use this flag when you want to start the network from scratch every time you run this command. To run with persisted state, do not pass this flag and use the `sui genesis` command to generate a genesis that can be used to start the network with. --with-faucet[=] Start a faucet with default host and port: 0.0.0.0:9123. This flag accepts also a port, a host, or both (e.g., 0.0.0.0:9123). When providing a specific value, please use the = sign between the flag and value: `--with-faucet=6124` or `--with-faucet=0.0.0.0`, or `--with-faucet=0.0.0.0:9123` --with-indexer[=] Start an indexer with a PostgreSQL database. Three modes of operation: - Not specified: No indexer is started (unless --with-graphql is set) - `--with-indexer`: Create/use a temporary database in the network's configuration directory - `--with-indexer=`: Use the provided PostgreSQL database URL When providing a database URL, use the = sign: `--with-indexer=postgres://user:pass@host:5432/db` --with-consistent-store[=] Start a Consistent Store with default host and port: 0.0.0.0:9124. This flag accepts also a port, a host, or both (e.g., 0.0.0.0:9124). When providing a specific value, please use the = sign between the flag and value: `--with-consistent-store=9124` or `--with-consistent-store=0.0.0.0`, or `--with-consistent-store=0.0.0.0:9124` The Consistent Store will be automatically enabled when `--with-graphql` is set. --with-graphql[=] Start a GraphQL server with default host and port: 0.0.0.0:9125. This flag accepts also a port, a host, or both (e.g., 0.0.0.0:9125). When providing a specific value, please use the = sign between the flag and value: `--with-graphql=9125` or `--with-graphql=0.0.0.0`, or `--with-graphql=0.0.0.0:9125` Note that GraphQL requires a running indexer and consistent store, which will be enabled by default even if those flags are not set. --fullnode-rpc-port Port to start the Fullnode RPC server on. Default port is 9000 [default: 9000] --epoch-duration-ms Set the epoch duration. Can only be used when `--force-regenesis` flag is passed or if there's no genesis config and one will be auto-generated. When this flag is not set but `--force-regenesis` is set, the epoch duration will be set to 60 seconds --data-ingestion-dir Make the fullnode dump executed checkpoints as files to this directory. This is incompatible with --no-full-node. If --with-indexer is set, this defaults to a temporary directory. --no-full-node Start the network without a fullnode --committee-size Set the number of validators in the network. If a genesis was already generated with a specific number of validators, this will not override it; the user should recreate the genesis with the desired number of validators ``` -------------------------------- ### Configure Chat App Frontend Source: https://docs.sui.io/sui-stack/seal/sui-chat-app Install dependencies and configure the frontend environment for the chat application. Copy the example environment file and edit it with your specific network and service configurations. ```bash cd ../chat-app pnpm install cp .env.example .env ``` -------------------------------- ### Install site-builder CLI Source: https://docs.sui.io/sui-stack/walrus/sui-stack-walrus-sites Installs the `site-builder` CLI using `suiup`. Ensure `$HOME/.local/bin` is in your PATH. ```bash curl -sSfL https://raw.githubusercontent.com/Mystenlabs/suiup/main/install.sh | sh $ suiup install site-builder@mainnet ``` -------------------------------- ### Clone and Deploy Walrus Example Site to Testnet Source: https://docs.sui.io/sui-stack/walrus/sui-stack-walrus-sites Clone the example repository and deploy the 'snake' example to the Testnet environment. The `--epochs` flag determines the site's availability duration. ```bash git clone https://github.com/MystenLabs/walrus-sites.git && cd walrus-sites site-builder --context=testnet deploy examples/snake --epochs 1 ``` -------------------------------- ### Unprunable Pipeline Indexer Setup Source: https://docs.sui.io/operators/data-management/indexer-stack-setup Set up the indexer for an unprunable pipeline, starting from genesis through a specified GCS bucket. ```sh $ sui-indexer-alt indexer \ --config unpruned.toml \ --database-url postgres://username:password@localhost:5432/database \ --remote-store-gcs mysten-mainnet-checkpoints-use4 ``` -------------------------------- ### Go: Install Dependencies for gRPC Client Source: https://docs.sui.io/develop/accessing-data/grpc/using-grpc Install the necessary Go tools for protobuf and gRPC code generation. Ensure 'go' and 'protoc' are installed. ```shell go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest ``` -------------------------------- ### Install Dependencies for zkLogin Demo Source: https://docs.sui.io/sui-stack/zklogin-integration/zklogin-demo Install the necessary project dependencies using pnpm. ```bash pnpm install pnpm install @mysten/utils ``` -------------------------------- ### Install site-builder CLI Source: https://docs.sui.io/sui-stack/walrus/sui-stack-walrus-sites Install the site-builder CLI tool for managing Walrus Sites. ```bash suiup install site-builder@mainnet ``` -------------------------------- ### Install Sui using suiup Source: https://docs.sui.io/guides/developer/getting-started/sui-install Installs the Sui CLI for the testnet using `suiup`. ```bash $ suiup install sui@testnet ``` -------------------------------- ### Verify site-builder Installation Source: https://docs.sui.io/sui-stack/walrus/sui-stack-walrus-sites Confirms the successful installation of the `site-builder` CLI. ```bash site-builder --help ``` -------------------------------- ### Initialize Diesel Project Source: https://docs.sui.io/develop/accessing-data/custom-indexer/build Run `diesel setup` to create the necessary directory structure for Diesel migrations, providing the database URL. ```bash $ diesel setup --database-url $PSQL_URL ``` -------------------------------- ### Install Sui and Sui-Bridge-CLI from Git Source: https://docs.sui.io/operators/bridge-node-configuration Install the Sui and sui-bridge-cli tools from the main branch of the Sui repository. Ensure you have Rust and Cargo installed. ```sh cargo install --locked --git "https://github.com/MystenLabs/sui.git" sui sui-bridge-cli ``` -------------------------------- ### TypeScript: Get Transaction Events and Effects Source: https://docs.sui.io/develop/accessing-data/grpc/using-grpc Use this TypeScript snippet to create a gRPC client and fetch 'events' and 'effects' for a given transaction digest. Ensure proto-loader and gRPC are installed. The example assumes SSL is enabled on port 443. ```typescript const PROTO_PATH = path.join(__dirname, 'protos/sui/rpc/v2/ledger_service.proto'); // Load proto definitions const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true, includeDirs: [path.join(__dirname, 'protos')], }); const suiProto = grpc.loadPackageDefinition(packageDefinition) as any; const LedgerService = suiProto.sui.rpc.v2.LedgerService; // Create gRPC client const client = new LedgerService( ':443', grpc.credentials.createSsl() ); // Sample transaction digest in Base58 format const base58Digest = '3ByWphQ5sAVojiTrTrGXGM5FmCVzpzYmhsjbhYESJtxp'; // Construct the request const request = { digest: base58Digest, read_mask: { paths: ['events', 'effects'], }, }; // Make gRPC call client.GetTransaction(request, (err: any, response: any) => { if (err) { console.error('Error:', err); } else { console.log('Response:', JSON.stringify(response, null, 2)); } }); ``` -------------------------------- ### Install Build Prerequisites on Linux Source: https://docs.sui.io/operators/full-node/sui-full-node Installs necessary packages for building Sui components on a Linux system. Ensure Docker and Docker Compose are installed prior to running. ```bash $ apt update \ && apt install -y --no-install-recommends \ tzdata \ ca-certificates \ build-essential \ pkg-config \ cmake ``` -------------------------------- ### Start the Frontend Development Server Source: https://docs.sui.io/sui-stack/walrus/only-fins Navigate to the frontend directory and start the development server to run the application locally. ```bash cd frontend pnpm dev ``` -------------------------------- ### Get Vesting Start Time Source: https://docs.sui.io/onchain-finance/fungible-tokens/token-vesting-strategies Returns the start time for the front-loaded portion of the vesting schedule. ```move public fun start(self: &Wallet): u64 { self.start_front } ``` -------------------------------- ### Start the Frontend Application Source: https://docs.sui.io/sui-stack/seal/sui-chat-app Navigate to the chat app directory and start the development server for the frontend using npm. ```bash cd sui-stack-messaging/chat-app npm run dev ``` -------------------------------- ### Get Native Epoch Start Timestamp Source: https://docs.sui.io/references/framework/sui_sui/tx_context A native function to retrieve the epoch start time in milliseconds. ```move fun native_epoch_timestamp_ms(): u64 ``` -------------------------------- ### Get Epoch Start Timestamp Source: https://docs.sui.io/references/framework/sui_sui/tx_context Returns the epoch start time as a Unix timestamp in milliseconds. This function takes a reference to the TxContext. ```move public fun epoch_timestamp_ms(_self: &sui::tx_context::TxContext): u64 ``` -------------------------------- ### Go: Run the Sample Client Source: https://docs.sui.io/develop/accessing-data/grpc/using-grpc Execute the Go gRPC client after setting up go.mod and generating proto files. Ensure correct import paths for generated code. ```shell go run main.go ``` -------------------------------- ### Get Historical Volume for All Pools Example Response Source: https://docs.sui.io/onchain-finance/deepbookv3/deepbookv3-indexer Example response for the /all_historical_volume endpoint, listing the trading volume for various pools within the specified time frame. ```json { "DEEP_SUI": 22557460000000, "WUSDT_USDC": 10265000000, "NS_USDC": 4399650900000, "NS_SUI": 6975475200000, "SUI_USDC": 19430171000000000, "WUSDC_USDC": 23349574900000, "DEEP_USDC": 130000590000000 } ``` -------------------------------- ### Get Current Epoch Timestamp in Sui Source: https://docs.sui.io/sui-stack/on-chain-primitives/access-time Use this function to get the millisecond-granularity Unix timestamp for the start of the current epoch. This value updates approximately every 24 hours. ```move public fun epoch_timestamp_ms(_self: &TxContext): u64 { native_epoch_timestamp_ms() } ``` -------------------------------- ### Clone the Capability Pattern Example Repo Source: https://docs.sui.io/getting-started/examples/capability-pattern Clone the repository and navigate to the capability pattern directory to set up the example locally. ```bash git clone -b solution https://github.com/MystenLabs/sui-move-bootcamp.git cd sui-move-bootcamp/C1/capability ``` -------------------------------- ### Configure and Start Relayer Source: https://docs.sui.io/sui-stack/seal/sui-chat-app Set up the relayer by copying the environment file and filling in necessary variables like SUI_RPC_URL and GROUPS_PACKAGE_ID. Then, run the relayer using cargo. ```bash cd relayer cp .env.example .env # fill in SUI_RPC_URL (https://fullnode.testnet.sui.io:443 for testnet) and GROUPS_PACKAGE_ID (Deployed Groups SDK package ID) ``` ```bash cargo run ``` -------------------------------- ### Get Historical Volume for Specific Pools Example Source: https://docs.sui.io/onchain-finance/deepbookv3/deepbookv3-indexer Example request to the /historical_volume endpoint, demonstrating how to query volume for 'DEEP_SUI' and 'SUI_USDC' pools in the base asset for a specific time range. ```http /historical_volume/DEEP_SUI,SUI_USDC?start_time=1731260703&end_time=1731692703&volume_in_base=true ``` -------------------------------- ### Get Pool Information Response Source: https://docs.sui.io/onchain-finance/deepbookv3/deepbookv3-indexer Example response structure for the /get_pools endpoint, detailing the properties of each trading pool. ```json [ { "pool_id": "0xb663828d6217467c8a1838a03793da896cbe745b150ebd57d82f814ca579fc22", "pool_name": "DEEP_SUI", "base_asset_id": "0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP", "base_asset_decimals": 6, "base_asset_symbol": "DEEP", "base_asset_name": "DeepBook Token", "quote_asset_id": "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI", "quote_asset_decimals": 9, "quote_asset_symbol": "SUI", "quote_asset_name": "Sui", "min_size": 100000000, "lot_size": 10000000, "tick_size": 10000000 }, { "pool_id": "0xf948981b806057580f91622417534f491da5f61aeaf33d0ed8e69fd5691c95ce", "pool_name": "DEEP_USDC", "base_asset_id": "0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP", "base_asset_decimals": 6, "base_asset_symbol": "DEEP", "base_asset_name": "DeepBook Token", "quote_asset_id": "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC", "quote_asset_decimals": 6, "quote_asset_symbol": "USDC", "quote_asset_name": "USDC", "min_size": 100000000, "lot_size": 10000000, "tick_size": 10000 } ] ``` -------------------------------- ### Configure TypeScript Tests Source: https://docs.sui.io/getting-started/examples/derived-objects Commands to navigate to the TypeScript directory, install dependencies, and copy the environment example file. ```bash cd ../../ts bun install cp .env.example .env ``` -------------------------------- ### Start the Indexer Source: https://docs.sui.io/getting-started/examples/event-indexer Run the npm start command in the backend directory to launch the indexer. This will subscribe to the gRPC checkpoint stream and log decoded events. ```bash $ npm start ``` -------------------------------- ### Root Object Access Examples Source: https://docs.sui.io/references/object-display-syntax Chains can start from the root object, referred to explicitly as '$self' or implicitly by omitting the root. ```text {name} — equivalent to {$self.name} ``` ```text {$self} — the root object itself ``` ```text {$self.id} — explicit access from the root object ``` -------------------------------- ### Example: Steady-State from Fullnode Source: https://docs.sui.io/operators/data-management/archival-stack-setup Example command for steady-state indexing from a fullnode's RPC and streaming URLs. ```sh sui-kvstore-alt \ --chain mainnet \ my-bigtable-instance \ --rpc-api-url http://my-fullnode:9000 \ --streaming-url http://my-fullnode:9000 ``` -------------------------------- ### Install Frontend Dependencies Source: https://docs.sui.io/getting-started/onboarding/app-frontends Navigate to the UI directory and run this command to install the necessary frontend dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Get Kiosk Extension Storage (Immutable) Source: https://docs.sui.io/references/framework/sui_sui/kiosk_extension Retrieves immutable access to an extension's storage within the Kiosk. This can only be called by the extension itself while it is installed. ```rust public fun storage(_ext: Ext, self: &sui::kiosk::Kiosk): &sui::bag::Bag ``` -------------------------------- ### Example GraphQL RPC Server Run Command Source: https://docs.sui.io/operators/data-management/indexer-stack-setup An example command demonstrating how to run the GraphQL RPC server with specific configuration files and service endpoints for a production environment. ```sh sui-indexer-alt-graphql rpc \ --config graphql.toml \ --indexer-config events.toml \ --indexer-config obj_versions.toml \ --indexer-config tx_affected_addresses.toml \ --indexer-config tx_affected_objects.toml \ --indexer-config tx_calls.toml \ --indexer-config tx_kinds.toml \ --indexer-config unpruned.toml \ --ledger-grpc-url https://archive.mainnet.sui.io:443 \ --consistent-store-url https://localhost:7001 \ --database-url postgres://username:password@localhost:5432/database \ --fullnode-rpc-url https://localhost:9000 ``` -------------------------------- ### Get Checkpoints Source: https://docs.sui.io/sui-api-ref Retrieves a paginated list of checkpoints in descending order. You can specify a cursor to start from and a limit for the number of results per page. ```json { "jsonrpc": "2.0", "id": 1, "method": "sui_getCheckpoints", "params": [ "1004", 4, false ] } ``` ```json { "jsonrpc": "2.0", "result": { "data": [ { "epoch": "5000", "sequenceNumber": "1005", "digest": "9zA7Q9Ka1ykvYjSQGhQCdCf32FZkcWNWx7L22JczXGsk", "networkTotalTransactions": "792385", "previousDigest": "8BLFxLTjWZ2KqaGc3FjR1o9aL6kbyYrmhuNfJLU1ehYt", "epochRollingGasCostSummary": { "computationCost": "0", "storageCost": "0", "storageRebate": "0", "nonRefundableStorageFee": "0" }, "timestampMs": "1676911928", "transactions": [ "7RudGLkQDBNJyqrptkrNU66Zd3pvq8MHVAHYz9WpBm59" ], "checkpointCommitments": [], "validatorSignature": "wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" }, { "epoch": "5000", "sequenceNumber": "1006", "digest": "FAUWHyWacmb4Vg4QGi9a6gqeVb7ixAZiL73FaGd6WpoV", "networkTotalTransactions": "792385", "previousDigest": "6Pn25cieaE62AT6BwCeBoca13AGZuneucaaTGqt3gNCo", "epochRollingGasCostSummary": { "computationCost": "0", "storageCost": "0", "storageRebate": "0", "nonRefundableStorageFee": "0" }, "timestampMs": "1676911928", "transactions": [ "7r7tmP5hzgrusiN6cucFwfTveqDb7K75tMJ7oNCyoDmy" ], "checkpointCommitments": [], "validatorSignature": "wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" }, { "epoch": "5000", "sequenceNumber": "1007", "digest": "B3mzC6gy87SomUQwPsmVY7mtwkZLxfm5WwNi3kKyEb3x", "networkTotalTransactions": "792385", "previousDigest": "CnHTfdUJr1UUqwXkYUhbQjXeM16xR33UR62jE72toCis", "epochRollingGasCostSummary": { "computationCost": "0", "storageCost": "0", "storageRebate": "0", "nonRefundableStorageFee": "0" }, "timestampMs": "1676911928", "transactions": [ "Gb1UDqhmKMzMJ5FL37kBqCcuy4TtBL2ay3qec8tEUBLj" ], "checkpointCommitments": [], "validatorSignature": "wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" }, { "epoch": "5000", "sequenceNumber": "1008", "digest": "HunuJWKu7azBfS47rJTq9FHTMvUDNVo2SK4hQeh5brXp", "networkTotalTransactions": "792385", "previousDigest": "38fLUfuigyzLPEDrsmRhcQmhKtbEUohuFBP9NDcWBmFz", "epochRollingGasCostSummary": { "computationCost": "0", "storageCost": "0", "storageRebate": "0", "nonRefundableStorageFee": "0" }, "timestampMs": "1676911928", "transactions": [ "GWTS9QR7mjNz9fBWGkk4JZU3mrzMXrmj74uS59Cd5und" ], "checkpointCommitments": [], "validatorSignature": "wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" } ], "nextCursor": "1008", "hasNextPage": true }, "id": 1 } ``` -------------------------------- ### Example .env Configuration Source: https://docs.sui.io/getting-started/examples/plinko An example of the .env file content, showing the required variables and their expected format. This includes network settings, addresses, keys, and game parameters. ```dotenv NEXT_PUBLIC_SUI_NETWORK_NAME=testnet NEXT_PUBLIC_PACKAGE_ADDRESS=PACKAGE_ID_FROM_STEP_2 HOUSE_ADDRESS=YOUR_WALLET_ADDRESS HOUSE_PRIVATE_KEY=YOUR_BASE64_PRIVATE_KEY NEXT_PUBLIC_HOUSE_DATA_ID=HOUSE_CAP_OBJECT_ID_FROM_STEP_2 NEXT_PUBLIC_MIN_BET_AMOUNT=100000000 (0.1 SUI in MIST) NEXT_PUBLIC_MAX_BET_AMOUNT=10000000000 (10 SUI in MIST) ENOKI_SECRET_KEY=ENOKI_KEY ``` -------------------------------- ### Get Historical Volume for Specific Pools Response Source: https://docs.sui.io/onchain-finance/deepbookv3/deepbookv3-indexer Example response structure for the /historical_volume endpoint, showing the total volume for each requested pool. ```json { "DEEP_SUI": 22557460000000, "SUI_USDC": 19430171000000000 } ``` -------------------------------- ### Indexer Setup for Prunable Pipelines Source: https://docs.sui.io/operators/data-management/indexer-stack-setup Configure the indexer for prunable pipelines, specifying a remote GCS bucket and a starting checkpoint based on retention requirements. ```sh $ sui-indexer-alt indexer \ --config \ --database-url \ --remote-store-gcs \ --first-checkpoint ``` -------------------------------- ### Start the Development Server Source: https://docs.sui.io/getting-started/examples/dapp-kit-frontend Start the local development server to run the dApp. Access the dApp at http://localhost:5173. ```bash $ pnpm dev ``` -------------------------------- ### Unique Prerequisite Tabs Example Source: https://docs.sui.io/references/contribute/mdx-components Illustrates using the `Tabs` component with `className="tabsHeadingCentered--small"` for guides with unique prerequisites. ```jsx ## Prerequisites - [x] Unique prerequisite. ``` -------------------------------- ### Run sui-kv-rpc with basic arguments Source: https://docs.sui.io/operators/data-management/archival-stack-setup Start the sui-kv-rpc service using instance ID and address. Replace placeholders with your specific values. ```sh sui-kv-rpc \ \
``` -------------------------------- ### Module Definition for Hot Potato Example Source: https://docs.sui.io/concepts/transactions/prog-txn-blocks Defines a struct for hot potatoes and functions for handling them and spending coins. This serves as a setup for demonstrating PTB restrictions. ```move module ex::m; public struct HotPotato() public fun hot(x: &mut Coin): HotPotato { ... } entry fun spend(x: &mut Coin) { ... } public fun cool(h: HotPotato) { ... } ``` -------------------------------- ### Get Historical Volume by Balance Manager Response Source: https://docs.sui.io/onchain-finance/deepbookv3/deepbookv3-indexer Example response structure for the /historical_volume_by_balance_manager_id endpoint, showing maker and taker volumes for each pool associated with the balance manager. ```json { "pool_name_1": [maker_volume, taker_volume], "pool_name_2": … } ``` -------------------------------- ### Clone Sui Move Bootcamp Repository Source: https://docs.sui.io/getting-started/examples/scenario-testing Clone the specified branch of the Sui Move bootcamp repository and navigate into the scenario directory. This is the initial setup step for the examples. ```bash git clone -b solution https://github.com/MystenLabs/sui-move-bootcamp.git cd sui-move-bootcamp/G1/scenario ``` -------------------------------- ### Initialize and Use Game Components Source: https://docs.sui.io/references/contribute/mdx-components Demonstrates initializing a new game, creating swords, and heroes, and handling unequip operations. Includes a test for an expected failure when unequipping a non-existent item. ```move let _admin = new_game(ts.ctx()); ts.next_tx(player); let mut game: Game = ts.take_shared(); let coin = coin::mint_for_testing(MIN_SWORD_COST, ts.ctx()); let sword = game.new_sword(coin, ts.ctx()); let mut hero = sword.new_hero(ts.ctx()); let _s0 = hero.unequip(); let _s1 = hero.unequip(); // Doesn't exist abort 1337 } ``` ```move #[test] #[expected_failure(abort_code = EAlreadyEquipped)] fun test_equip_already_equipped() { let admin = @0xAD; let player = @0xA; let mut ts = ts::begin(admin); let _admin = new_game(ts.ctx()); ts.next_tx(player); let mut game: Game = ts.take_shared(); let c0 = coin::mint_for_testing(MIN_SWORD_COST, ts.ctx()); let s0 = game.new_sword(c0, ts.ctx()); let c1 = coin::mint_for_testing(MIN_SWORD_COST, ts.ctx()); let s1 = game.new_sword(c1, ts.ctx()); let mut hero = s0.new_hero(ts.ctx()); hero.equip(s1); abort 1337 } ``` -------------------------------- ### Configure Backend Environment Variables Source: https://docs.sui.io/sui-stack/walrus/only-fins Copy the example environment file and edit it to include your author private keys and the published Move package ID. ```bash cd ../../../backend/ cp .env.example .env ``` -------------------------------- ### Get Available Wallets Source: https://docs.sui.io/standards/wallet-standard Query for installed wallets in the user's browser using `getWallets().get()`. The returned array contains `Wallet` types that can be used to display wallet details. ```typescript import { getWallets } from '@mysten/wallet-standard'; const availableWallets = getWallets().get(); ``` -------------------------------- ### Obtain Active Address and Convert to Keytool Source: https://docs.sui.io/sui-stack/enoki/ticketing-poc Use these commands to get your active Sui address and convert it for use with the keytool. Ensure you copy the private key starting with 'suiprivkey1...'. ```bash $ sui client active-address $ sui keytool convert
``` -------------------------------- ### Clone Sui Move Bootcamp Repository Source: https://docs.sui.io/getting-started/examples/dapp-kit-frontend Clone the repository and navigate to the dApp example directory. This sets up the project locally. ```bash $ git clone -b solution https://github.com/MystenLabs/sui-move-bootcamp.git $ cd sui-move-bootcamp/E2/my-first-sui-dapp ``` -------------------------------- ### Initialize Node.js Project and Install Sui SDK Source: https://docs.sui.io/develop/publish-upgrade-packages/custom-policies Set up a Node.js project for using the Sui TypeScript SDK. This involves initializing the project and installing the necessary SDK package. ```json { "type": "module" } ``` ```sh $ npm install @mysten/sui ``` -------------------------------- ### Get Trade Count Endpoint Source: https://docs.sui.io/onchain-finance/deepbookv3/deepbookv3-indexer Fetches the total number of trades across all pools within a specified time range. Requires start and end times in Unix timestamp format. ```http /trade_count?start_time=&end_time= ``` -------------------------------- ### Verify Partitioning Setup Source: https://docs.sui.io/develop/accessing-data/custom-indexer/indexer-runtime-perf These queries help confirm that the partitioned table and its associated cron job are correctly configured. ```sql SELECT parent_table, partition_type, control, interval_val FROM part_config ORDER BY parent_table; -- Check maintenance job is scheduled SELECT jobid, schedule, command, nodename, database, username FROM cron.job WHERE command = 'SELECT run_maintenance()'; ``` -------------------------------- ### Connect to Sui Networks and Get API Versions Source: https://docs.sui.io/references/rust-sdk Use SuiClientBuilder to connect to Sui testnet, devnet, and mainnet, then print their RPC API versions. This example requires the tokio runtime. ```rust use sui_sdk::SuiClientBuilder; #[tokio::main] async fn main() -> Result<(), anyhow::Error> { // Sui testnet -- https://fullnode.testnet.sui.io:443 let sui_testnet = SuiClientBuilder::default().build_testnet().await?; println!("Sui testnet version: {}", sui_testnet.api_version()); // Sui devnet -- https://fullnode.devnet.sui.io:443 let sui_devnet = SuiClientBuilder::default().build_devnet().await?; println!("Sui devnet version: {}", sui_devnet.api_version()); // Sui mainnet -- https://fullnode.mainnet.sui.io:443 let sui_mainnet = SuiClientBuilder::default().build_mainnet().await?; println!("Sui mainnet version: {}", sui_mainnet.api_version()); Ok(()) } ``` -------------------------------- ### Get Owned Objects by Address Source: https://docs.sui.io/develop/objects/transfers/transfer-to-object Example RPC call to retrieve objects owned by a specific address. This method can also be used with object IDs to retrieve objects owned by that object. ```json { "jsonrpc": "2.0", "id": 1, "method": "suix_getOwnedObjects", "params": [ "0xADD" ] } ``` -------------------------------- ### Setup fastcrypto CLI Source: https://docs.sui.io/develop/cryptography/signing Clone the fastcrypto repository and build the sigs-cli binary. This is for testing and debugging purposes only. ```sh git clone git@github.com:MystenLabs/fastcrypto.git cd fastcrypto/ cargo build --bin sigs-cli ``` -------------------------------- ### Response Structure for Get All Pools Source: https://docs.sui.io/onchain-finance/deepbookv3/deepbookv3-indexer Example JSON response structure for the /get_pools endpoint. Each object details a trading pool with its assets, decimals, symbols, and trading parameters like min_size, lot_size, and tick_size. ```json [ { "pool_id": "string", "pool_name": "string", "base_asset_id": "string", "base_asset_decimals": integer, "base_asset_symbol": "string", "base_asset_name": "string", "quote_asset_id": "string", "quote_asset_decimals": integer, "quote_asset_symbol": "string", "quote_asset_name": "string", "min_size": integer, "lot_size": integer, "tick_size": integer }, ... ] ``` -------------------------------- ### Install Frontend Dependencies Source: https://docs.sui.io/sui-stack/enoki/ticketing-poc Change to the app directory and install the necessary Node.js dependencies using pnpm. ```bash cd app pnpm install ``` -------------------------------- ### Install and Launch Tokio Console Source: https://docs.sui.io/develop/accessing-data/custom-indexer/indexer-runtime-perf Install the tokio-console CLI tool and launch it to connect to your running indexer and visualize task execution. ```bash # Install tokio-console if not already installed cargo install tokio-console # Connect to your running indexer (default: localhost:6669) tokio-console ``` -------------------------------- ### Get Owned Objects by Object ID Source: https://docs.sui.io/develop/objects/transfers/transfer-to-object Example RPC call to retrieve objects owned by an object ID. This demonstrates the flexibility of the `suix_getOwnedObjects` method, which treats object IDs similarly to addresses for ownership queries. ```json { "jsonrpc": "2.0", "id": 1, "method": "suix_getOwnedObjects", "params": [ "0x0B" ] } ``` -------------------------------- ### Full Seal Encrypt and Decrypt Workflow Example Source: https://docs.sui.io/sui-stack/seal/sui-stack-seal This Node.js script demonstrates the end-to-end Seal workflow, including client setup, encryption, session key generation, PTB construction, and owner-only access decryption. ```typescript import { SealClient, SealConfig } from "@mysten/seal-client"; import { randomBytes } from "crypto"; import { SuiClient, getFullnodeUrl } from "@mysten/sui.js/client"; import { Ed25519Keypair, RawSigner, TransactionBlock } from "@mysten/sui.js/transactions"; // --- Configuration --- const SEAL_PACKAGE_ID = "0x1234"; // Replace with your deployed Seal package ID const SUI_NETWORK = "devnet"; // or "testnet", "mainnet", or a custom RPC URL const RPC_URL = getFullnodeUrl(SUI_NETWORK); // --- Helper Functions --- // Function to generate a random encryption ID function generateEncryptionId(): string { return randomBytes(16).toString("hex"); } // Function to simulate creating a PTB for decryption access async function createDecryptionPTB( sealClient: SealClient, encryptionId: string, ownerSigner: RawSigner ): Promise { const ptb = new TransactionBlock(); // Add Seal's seal_approve_access function call ptb.moveCall({ target: `${SEAL_PACKAGE_ID}::seal::seal_approve_access`, arguments: [ ptb.pure(encryptionId), // Add other necessary arguments based on your Seal implementation ], }); return ptb; } // --- Main Workflow --- async function runSealDemo() { // 1. Setup Sui Client and Signer const suiClient = new SuiClient({ url: RPC_URL }); const keypair = Ed25519Keypair.generate(); const signer = new RawSigner(keypair, suiClient); const ownerAddress = signer.getAccountAddress(); console.log(`Sui Account: ${ownerAddress}`); // 2. Initialize Seal Client const sealConfig: SealConfig = { packageId: SEAL_PACKAGE_ID, // Add other necessary Seal configurations (e.g., RPC endpoints for key servers) }; const sealClient = new SealClient(sealConfig); // 3. Encryption const encryptionId = generateEncryptionId(); const plaintext = new TextEncoder().encode("This is a secret message!"); console.log(`Encrypting data with ID: ${encryptionId}`); const { encryptedObject, key: backupKey } = await sealClient.encrypt(encryptionId, plaintext); console.log("Encryption successful."); console.log("Encrypted Object (first 50 chars):", JSON.stringify(encryptedObject).substring(0, 50) + "..."); console.log("Backup Key (first 10 chars):", JSON.stringify(backupKey).substring(0, 10) + "..."); // In a real app, you would upload `encryptedObject` to storage (e.g., Walrus) // and store `encryptionId` alongside it. // 4. Decryption (Owner-Only Access Simulation) console.log("Simulating decryption..."); // a. Create a Transaction Block to request decryption access const decryptionPTB = await createDecryptionPTB(sealClient, encryptionId, signer); console.log("Created PTB for decryption access."); // b. Simulate receiving decryption key shares and reconstructing the key // This part is complex and depends on your Seal key server setup. // For this demo, we'll use the backupKey directly. const decryptionKey = backupKey; // In a real scenario, this would be derived from key shares // c. Decrypt the data using the reconstructed key try { const decryptedData = await sealClient.decrypt(encryptionId, encryptedObject, decryptionKey); const decryptedMessage = new TextDecoder().decode(decryptedData); console.log("Decryption successful!"); console.log("Decrypted Message:", decryptedMessage); } catch (error) { console.error("Decryption failed:", error); } } runSealDemo().catch(console.error); ``` -------------------------------- ### Call Entry Function with Clock Argument Source: https://docs.sui.io/sui-stack/on-chain-primitives/access-time Example CLI command to call the `access` entry function, passing `0x6` as the address for the `Clock` parameter. Note that the `--gas-budget` option is no longer required for CLI commands starting with Sui v1.24.1. ```sh $ sui client call --package --module 'clock' --function 'access' --args '0x6' --gas-budget ``` -------------------------------- ### Run Weather Example Prompts Source: https://docs.sui.io/sui-stack/nautilus/using-nautilus Follow the prompts to run the weather example. This includes providing an EC2 instance name, choosing to use a secret for the API key, and entering the secret name and value. ```bash Enter EC2 instance base name: weather # anything you like Do you want to use a secret? (y/n): y Do you want to create a new secret or use an existing secret ARN? (new/existing): new Enter secret name: weather-api-key # anything you like Enter secret value: 045a27812dbe456392913223221306 # this is an example api key, you can get your own at weatherapi.com ``` -------------------------------- ### New Keypair and Configuration Source: https://docs.sui.io/getting-started/onboarding/configure-sui-client Output shown after successfully creating a new keypair and `client.yaml` file. It includes the recovery phrase and sets the active environment. ```bash Generated new keypair ... secret recovery phrase : [recovery phrase words are here] Created "~/.sui/sui_config/client.yaml" Set active environment to testnet ``` -------------------------------- ### Per-user Profiles Example Source: https://docs.sui.io/getting-started/examples/derived-objects Use create_address with the player's wallet address as the key for per-user profiles. Each user gets one derived profile object per game, looked up by computing deriveObjectID(gameId, "address", userAddress). ```typescript const gameId = "0x123..."; const userAddress = "0x456..."; const profileId = deriveObjectID(gameId, "address", userAddress); ```