### Install peaq-robotics-sdk (Bash) Source: https://docs.peaq.xyz/sdk-reference/robotics-sdk/examples/options-test Command to install or upgrade the peaq-robotics-sdk package using pip. This is a prerequisite for running the provided Python examples. ```bash pip install -U peaq-robotics-sdk ``` -------------------------------- ### Install peaq-robotics-sdk using pip Source: https://docs.peaq.xyz/sdk-reference/robotics-sdk/examples/wallet-demo Command to install or upgrade the peaq-robotics-sdk package from PyPI. ```bash pip install -U peaq-robotics-sdk ``` -------------------------------- ### Setup Python Virtual Environment for peaq SDK Source: https://docs.peaq.xyz/build/getting-started/install-peaq-sdk Sets up a virtual environment for Python projects to isolate the peaq SDK installation. Requires Python version 3.8+. ```bash python -m venv peaq source peaq/bin/activate ``` ```bash python -m venv peaq peaq\Scripts\activate ``` -------------------------------- ### Python Wallet Demo using peaq-robotics-sdk Source: https://docs.peaq.xyz/sdk-reference/robotics-sdk/examples/wallet-demo This Python script demonstrates basic wallet operations using the peaq-robotics-sdk. It shows how to initialize the SDK, retrieve account information, optionally fund the account using an environment variable mnemonic, create a DID, and perform data storage and retrieval operations. The script requires the 'peaq-robotics-sdk' package to be installed. ```python import os, time, asyncio from peaq_robot import PeaqRobot from peaq_robot.types import TxOptions, ConfirmationMode sdk = PeaqRobot() print("Address:", sdk.address) print("Balance:", sdk.balance) # Optional: fund via an env mnemonic (demo only) mnemonic = os.getenv("PEAQ_ROBOT_FUND_MNEMONIC", "") if mnemonic: from substrateinterface.keypair import Keypair kp = Keypair.create_from_mnemonic(mnemonic) _ = sdk.wallet.send_transaction( module='Balances', function='transfer_allow_death', params={'dest': sdk.address, 'value': int(1 * 10**18)}, keypair=kp, ) # Create DID (idempotent) and store a small JSON payload try: _ = sdk.id.create_identity() except Exception: pass tx = sdk.store.add_data("DEMO_DATA_001", {"robot": "demo", "status": "active"}) print("Storage tx:", tx) res = sdk.store.read_data("DEMO_DATA_001") print("Read:", res.get("data")) ``` -------------------------------- ### Install ethers and peaq SDK Source: https://docs.peaq.xyz/build/first-depin/onboard-machine Installs the ethers library for wallet generation and token transfers, and the peaq network SDK for DID document generation and storage. These are essential prerequisites for onboarding a machine. ```bash npm install ethers npm install @peaq-network/sdk ``` -------------------------------- ### Install peaq SDK for Python Source: https://docs.peaq.xyz/build/getting-started/install-peaq-sdk Installs the peaq SDK for Python projects using pip. Assumes a virtual environment is active. ```bash pip install peaq-sdk ``` -------------------------------- ### Store Data with FAST Confirmation (Python) Source: https://docs.peaq.xyz/sdk-reference/robotics-sdk/examples/options-test This snippet demonstrates how to add data to the store using the FAST confirmation mode, which returns the transaction hash immediately. It utilizes the peaq_robot library and requires the peaq-robotics-sdk to be installed. ```python import asyncio, time from peaq_robot import PeaqRobot from peaq_robot.types import TxOptions, ConfirmationMode sdk = PeaqRobot() # FAST (string tx-hash) tx1 = sdk.store.add_data(f"OPT_FAST_{int(time.time())}", {"t": int(time.time())}) print("FAST:", tx1) ``` -------------------------------- ### Initialize SmartAccount with Project and Chain Options Source: https://docs.peaq.xyz/build/advanced-operations/account-abstraction/particle-network This snippet demonstrates how to create a new instance of SmartAccount. It requires an Ethereum provider and configuration including project ID, client key, app ID, and specific AA options for supported account contracts and their versions. The example uses Peaq Agung Testnet. ```javascript import { useEthereum } from '@particle-network/auth-core-modal'; import { PeaqAgungTestnet } from '@particle-network/chains'; import { SmartAccount } from '@particle-network/aa'; const App = () => { const { provider } = useEthereum(); const smartAccount = new SmartAccount(provider, { projectId: process.env.REACT_APP_PROJECT_ID, clientKey: process.env.REACT_APP_CLIENT_KEY, appId: process.env.REACT_APP_APP_ID, aaOptions: { accountContracts: { SIMPLE: [{ chainIds: [PeaqAgungTestnet.id], version: '1.0.0' }] } } }); } ``` -------------------------------- ### Install Hardhat Toolbox Source: https://docs.peaq.xyz/build/basic-operations/smart-contracts/build-smart-contract Installs the Hardhat Toolbox, a collection of essential plugins for testing, contract interaction, and deployment within the Hardhat environment. ```bash npm install @nomicfoundation/hardhat-toolbox ``` -------------------------------- ### Install peaq SDK for Node.js Source: https://docs.peaq.xyz/build/getting-started/install-peaq-sdk Installs the peaq SDK for JavaScript projects using npm or yarn. Requires Node.js version 16.x or higher. Enables ES Modules by adding "type": "module" to package.json. ```bash npm i @peaq-network/sdk ``` ```bash yarn add @peaq-network/sdk ``` -------------------------------- ### Store Data with FINAL Confirmation and Callback (Python) Source: https://docs.peaq.xyz/sdk-reference/robotics-sdk/examples/options-test This snippet demonstrates adding data to the store using the FINAL confirmation mode. It includes an `on_status` callback function to process transaction status updates and waits for the transaction to be finalized using `asyncio.run(res.finalize)`. The `peaq_robotics-sdk` must be installed. ```python import asyncio, time from peaq_robot import PeaqRobot from peaq_robot.types import TxOptions, ConfirmationMode sdk = PeaqRobot() # FINAL (awaitable finalize) def on_status(s): try: print(s.model_dump()) except Exception: print({"status": str(s.status), "hash": s.hash}) res = sdk.store.add_data( f"OPT_FINAL_{int(time.time())}", {"t": int(time.time())}, tx_options=TxOptions(mode=ConfirmationMode.FINAL), on_status=on_status, ) final_receipt = asyncio.run(res.finalize) print("FINALIZED:", str(final_receipt)[:180]) ``` -------------------------------- ### Install Hardhat using npm Source: https://docs.peaq.xyz/build/basic-operations/smart-contracts/build-smart-contract Installs the Hardhat development environment for local Ethereum development. This command should be run in your project's terminal. ```bash npm install --save-dev hardhat ``` -------------------------------- ### Transaction Tracing with cURL Source: https://docs.peaq.xyz/build/getting-started/evm-onboarding Example of how to use cURL to send a JSON-RPC request to a tracing-enabled node to debug a specific transaction using the 'callTracer'. ```bash curl -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"debug_traceTransaction","params":["",{"tracer":"callTracer"}]}' \ https://evm.yourevmnode.xyz ``` -------------------------------- ### Machine DID Document Examples (EVM & Substrate) Source: https://docs.peaq.xyz/learn/peaqDID Demonstrates the structure of a Machine Decentralized Identifier (DID) Document, highlighting differences between EVM and Substrate implementations. Includes fields for ID, controller, verification methods, authentication, signature, and service endpoints. ```javascript { "id": "did:peaq:0x742d35Cc6634C0532925a3b844Bc454e4438f44e", "controller": "did:peaq:0x742d35Cc6634C0532925a3b844Bc454e4438f44e", "verificationMethod": [ { "id": "did:peaq:0x742d35Cc6634C0532925a3b844Bc454e4438f44e#keys-1", "type": "EcdsaSecp256k1RecoveryMethod2020", "controller": "did:peaq:0x742d35Cc6634C0532925a3b844Bc454e4438f44e", "publicKeyMultibase": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" } ], "authentication": [ "did:peaq:5Df42mkztLtkksgQuLy4YV6hmhzdjYvDknoxHv1QBkaY12Qn#keys-1" ], "signature": { "type": "EcdsaSecp256k1Signature2019", "issuer": "did:peaq:0x742d35Cc6634C0532925a3b844Bc454e4438f44e", "hash": "0x5f2b7c5e5a1d3a65b9b67b9f2a6e2a8723f5d2b4e7d82b6a5f8e7b4d2f2b6e5a" }, "service": [ { "id": "#metadata", "type": "DataStorage", "serviceEndpoint": "ipfs://QmT5NvUtoM5nXBgGR2Fz3dRhFtrD4K1PzBEXm1PGRfZgm5" }, { "id": "#owner", "type": "Owner", "data": "did:peaq:0x3F5CE5FBFe3E9af3971dD833D26BA9b5C936F0bE" } ] } ``` ```javascript { "id": "did:peaq:5Df42mkztLtkksgQuLy4YV6hmhzdjYvDknoxHv1QBkaY12Qn", "controller": "did:peaq:5Df42mkztLtkksgQuLy4YV6hmhzdjYvDknoxHv1QBkaY12Qn", "verificationMethod": [ { "id": "did:peaq:5Df42mkztLtkksgQuLy4YV6hmhzdjYvDknoxHv1QBkaY12Qn#keys-1", "type": "Ed25519VerificationKey2020", "controller": "did:peaq:5Df42mkztLtkksgQuLyYV6hmhzdjYvDknoxHv1QBkaY12Qn", "publicKeyMultibase": "z6MkngYwTj4bW2nY9qHyyTjUEZGqDNRc5cVoXwYFjzwPrXbm" }, ], "authentication": [ "did:peaq:5Df42mkztLtkksgQuLy4YV6hmhzdjYvDknoxHv1QBkaY12Qn#keys-1" ], "signature": { "type": "Ed25519VerificationKey2020", "issuer": "did:peaq:5Df42mkztLtkksgQuLy4YV6hmhzdjYvDknoxHv1QBkaY12Qn", "hash": "0x5f2b7c5e5a1d3a65b9b67b9f2a6e2a8723f5d2b4e7d82b6a5f8e7b4d2f2b6e5a" }, "service": [ { "id": "#metadata", "type": "DataStorage", "serviceEndpoint": "ipfs://QmT5NvUtoM5nXBgGR2Fz3dRhFtrD4K1PzBEXm1PGRfZgm5" }, { "id": "#owner", "type": "Owner", "data": "did:peaq:5H6JkCkybXvKePVoDNFJVBYDHBfStUESSC62QxSpgcS7FFFe" } ] } ``` -------------------------------- ### Install peaq JavaScript SDK Source: https://context7.com/context7/peaq_xyz/llms.txt Installs the peaq JavaScript SDK using either npm or yarn package managers. This SDK provides the necessary tools to interact with the peaq network from a JavaScript environment. ```bash npm install @peaq-network/sdk # or yarn add @peaq-network/sdk ``` -------------------------------- ### Install Gnosis Safe SDK Dependencies Source: https://docs.peaq.xyz/build/basic-operations/working-with-wallet-addresses/multi-sig Installs the necessary Node.js packages for interacting with Gnosis Safe contracts using ethers.js and dotenv for environment configuration. ```bash npm install ethers @gnosis.pm/safe-core-sdk @gnosis.pm/safe-ethers-lib dotenv ``` -------------------------------- ### Install OpenZeppelin Upgrades Plugin for Hardhat Source: https://docs.peaq.xyz/build/basic-operations/smart-contracts/upgradable-smart-contracts Installs the OpenZeppelin Upgrades Plugin, which provides functionality for deploying and managing upgradable smart contracts within a Hardhat project. This is a prerequisite for following the deployment steps. ```bash npm install --save-dev @openzeppelin/hardhat-upgrades ``` -------------------------------- ### SimpleStorage Smart Contract (Foundry) Source: https://docs.peaq.xyz/build/basic-operations/smart-contracts/build-smart-contract The SimpleStorage smart contract written in Solidity for Foundry projects. It provides functionality to set and get a uint256 value. This version uses a pragma compatible with Foundry's typical setup. ```Solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.25; contract SimpleStorage { uint256 private data; function set(uint256 _data) external { data = _data; } function get() external view returns (uint256) { return data; } } ``` -------------------------------- ### Enabling Debug Tracing RPCs in Node Startup Source: https://docs.peaq.xyz/build/getting-started/evm-onboarding Command to start a peaq node with specific features enabled for debugging and tracing. It includes enabling debug, trace, and txpool RPC methods and setting the state pruning to archive. ```bash ./peaq-node \ --ethapi=debug,trace,txpool \ --rpc-methods=Unsafe \ --state-pruning archive \ --wasm-runtime-overrides=parachain-peaq \ --runtime-cache-size 64 \ ``` -------------------------------- ### Initialize peaq SDK Instance for Substrate (Signed) Source: https://docs.peaq.xyz/sdk-reference/python/create-instance Initializes the peaq SDK for Substrate transactions with a mnemonic seed, enabling signed transaction execution. Requires a WSS base URL, ChainType.SUBSTRATE, and the SUBSTRATE_SEED environment variable. Dependencies include 'peaq-sdk' and 'python-dotenv'. ```python import os from dotenv import load_dotenv from peaq_sdk import Sdk from peaq_sdk.types import ChainType load_dotenv() WSS_PEAQ_URL = os.getenv("WSS_PEAQ_URL") SUBSTRATE_SEED = os.getenv("SUBSTRATE_SEED") sdk = Sdk.create_instance( base_url=WSS_PEAQ_URL, chain_type=ChainType.SUBSTRATE, seed=SUBSTRATE_SEED ) ``` -------------------------------- ### Initialize Particle AA SmartAccount with Provider Source: https://docs.peaq.xyz/build/advanced-operations/account-abstraction/particle-network Demonstrates the initialization of the SmartAccount from the `@particle-network/aa` SDK within a React component. It shows how to obtain the EIP-1193 provider using `useEthereum` from `@particle-network/auth-core-modal` and import necessary components for AA setup. ```javascript import { useEthereum, useConnect, useAuthCore } from '@particle-network/auth-core-modal'; import { PeaqAgungTestnet } from '@particle-network/chains'; import { AAWrapProvider, SmartAccount } from '@particle-network/aa'; import { ethers } from 'ethers'; const App = () => { const { provider } = useEthereum(); // EIP-1193 provider // ... rest of the component logic for SmartAccount initialization } ``` -------------------------------- ### SDK Initialization Source: https://docs.peaq.xyz/sdk-reference/python/create-instance Initializes the Peaq SDK to create an instance for interacting with the blockchain network. Supports both EVM and Substrate chain types, with the option to provide a seed for signing transactions. ```APIDOC ## create_instance(base_url, chain_type, seed) ### Description Initializes the SDK and returns an instance ready to interact with the network. ### Method `create_instance` (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | EVM | Substrate | Description | |---|---|---|---|---| | **base_url** | `string` | Required | Required | HTTPS/WSS URL used to connect to the blockchain. Reference [connecting to peaq](/build/getting-started/connecting-to-peaq) for supported URLs. Use **HTTPS** for EVM and **WSS** for Substrate (and EVM reads). | | **chain_type** | `ChainType` | Required | Required | Defines whether the instance will generate EVM or Substrate transactions. | | **seed** | `string` | Optional | Optional | Private key (EVM) or mnemonic phrase (Substrate) used to execute write transactions on behalf of the user. If not set, the peaq transaction object is returned to the user for manual submission. | ### Request Example ```python import os from dotenv import load_dotenv from peaq_sdk import Sdk from peaq_sdk.types import ChainType load_dotenv() HTTPS_PEAQ_URL = os.getenv("HTTPS_PEAQ_URL") WSS_PEAQ_URL = os.getenv("WSS_PEAQ_URL") EVM_PRIVATE_KEY = os.getenv("EVM_PRIVATE_KEY") SUBSTRATE_SEED = os.getenv("SUBSTRATE_SEED") # EVM Unsigned Tx sdk_evm_unsigned = Sdk.create_instance( base_url=HTTPS_PEAQ_URL, chain_type=ChainType.EVM ) # EVM Write Tx sdk_evm_signed = Sdk.create_instance( base_url=HTTPS_PEAQ_URL, chain_type=ChainType.EVM, seed=EVM_PRIVATE_KEY ) # Substrate Unsigned Call sdk_substrate_unsigned = Sdk.create_instance( base_url=WSS_PEAQ_URL, chain_type=ChainType.SUBSTRATE, ) # Substrate Write Call sdk_substrate_signed = Sdk.create_instance( base_url=WSS_PEAQ_URL, chain_type=ChainType.SUBSTRATE, seed=SUBSTRATE_SEED ) ``` ### Response #### Success Response (200) - **sdk instance** (`object`) - An initialized SDK object ready for network interactions. #### Response Example (The response is the SDK object itself, not a JSON payload. See the request example for usage.) ``` -------------------------------- ### Initiate Social Login with Particle Auth Source: https://docs.peaq.xyz/build/advanced-operations/account-abstraction/particle-network This example shows how to use the useConnect hook to trigger a social login. The `connect` function accepts a social type (e.g., 'google', 'twitter', or an empty string for a general interface) and the target blockchain chain. It also includes a disconnect function. ```javascript import { useConnect } from '@particle-network/auth-core-modal'; import { PeaqAgungTestnet } from '@particle-network/chains'; const App = () => { const { connect, disconnect } = useConnect(); const handleLogin = async (authType) => { // Assuming userInfo is available and checked elsewhere if (!userInfo) { await connect({ socialType: authType, // 'google', 'twitter', etc. - can also be '' chain: PeaqAgungTestnet, // or PeaqKrest }); } }; // ... JSX for login buttons triggering handleLogin disconnect(); // Typically mapped to a UI element } ``` -------------------------------- ### Initialize peaq SDK Instance for Substrate (Unsigned) Source: https://docs.peaq.xyz/sdk-reference/python/create-instance Initializes the peaq SDK for Substrate transactions without a seed, returning an unsigned transaction object. Requires a WSS base URL and ChainType.SUBSTRATE. Dependencies include 'peaq-sdk' and 'python-dotenv'. ```python import os from dotenv import load_dotenv from peaq_sdk import Sdk from peaq_sdk.types import ChainType load_dotenv() WSS_PEAQ_URL = os.getenv("WSS_PEAQ_URL") sdk = Sdk.create_instance( base_url=WSS_PEAQ_URL, chain_type=ChainType.SUBSTRATE, ) ``` -------------------------------- ### Solidity Smart Contract Basics Source: https://docs.peaq.xyz/build/basic-operations/smart-contracts/build-smart-contract This snippet illustrates fundamental Solidity syntax including file license, pragma version, contract declaration, state variables, and basic functions for setting and getting data. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract SimpleStorage { uint256 private data; function set(uint256 _data) public { data = _data; } function get() public view returns (uint256) { return data; } } ``` -------------------------------- ### Initialize and Configure Foundry Project Source: https://docs.peaq.xyz/build/basic-operations/smart-contracts/build-smart-contract Commands to initialize a new Foundry project and configure its settings. The `foundry.toml` file specifies source directories, output directories, libraries, and the EVM version to be compatible with peaq-like networks. ```bash forge init my-project cd my-project ``` ```toml [profile.default] src = "src" out = "out" libs = ["lib"] evm_version = 'london' ``` -------------------------------- ### Initialize peaq SDK Instance for EVM (Signed) Source: https://docs.peaq.xyz/sdk-reference/python/create-instance Initializes the peaq SDK for EVM transactions with a private key, enabling signed transaction execution. Requires a base URL, ChainType.EVM, and the EVM_PRIVATE_KEY environment variable. Dependencies include 'peaq-sdk' and 'python-dotenv'. ```python import os from dotenv import load_dotenv from peaq_sdk import Sdk from peaq_sdk.types import ChainType load_dotenv() HTTPS_PEAQ_URL = os.getenv("HTTPS_PEAQ_URL") EVM_PRIVATE_KEY = os.getenv("EVM_PRIVATE_KEY") sdk = Sdk.create_instance( base_url=HTTPS_PEAQ_URL, chain_type=ChainType.EVM, seed=EVM_PRIVATE_KEY ) ``` -------------------------------- ### Instantiate PeaqRobot SDK (Python) Source: https://docs.peaq.xyz/sdk-reference/robotics-sdk/create-instance Demonstrates how to create a PeaqRobot instance, allowing access to wallet, identity, and storage functionalities. Supports default testnet or custom network/mnemonic configuration. Requires the 'peaq-robot' library. ```python from peaq_robot import PeaqRobot sdk = PeaqRobot() # 2) Use keystore (recommended) or explicit mnemonic # Keystore path can be set via env PEAQ_ROBOT_KEYSTORE # 3) Choose network (testnet by default). To override: sdk = PeaqRobot(network="agung", mnemonic="your 12/24 words ...") # or "peaq" / custom wss URL print(sdk.address) print(sdk.balance) # float ``` -------------------------------- ### Install Dependencies for ethers.js Source: https://docs.peaq.xyz/build/basic-operations/gas-operations/managing-gas-limits Installs the necessary Node.js packages, ethers.js and dotenv, for managing environment variables and interacting with the blockchain. ```bash npm install ethers dotenv ``` -------------------------------- ### Complete Machine Onboarding Flow using JavaScript Source: https://context7.com/context7/peaq_xyz/llms.txt This JavaScript code demonstrates the complete flow for onboarding a machine. It includes generating a new machine wallet, transferring native tokens to it, and creating a Decentralized Identifier (DID) for the machine. Dependencies include ethers.js and the @peaq-network/sdk. It takes no explicit input but relies on environment variables for the admin's private key. ```javascript import { ethers, Wallet } from "ethers"; import { Sdk } from "@peaq-network/sdk"; class ECDSAKeyring { constructor(privateKey) { this.wallet = privateKey ? new Wallet(privateKey) : Wallet.createRandom(); } getAddress() { return this.wallet.address; } getPrivateKey() { return this.wallet.privateKey; } async signMessage(message) { return this.wallet.signMessage(message); } } async function getAdmin() { const provider = new ethers.JsonRpcProvider("https://peaq-agung.api.onfinality.io/public"); const adminPrivateKey = process.env["ADMIN_PRIVATE_KEY"]; return new Wallet(adminPrivateKey, provider); } async function transferNativeToken(machineWallet, adminWallet) { const tx = await adminWallet.sendTransaction({ to: machineWallet.getAddress(), value: ethers.parseEther("1") }); console.log("Transaction sent:", tx.hash); await tx.wait(); console.log("Transaction confirmed."); } async function generateDID(machineWallet, adminWallet) { const HTTPS_BASE_URL = "https://peaq-agung.api.onfinality.io/public"; const sdk = await Sdk.createInstance({ baseUrl: HTTPS_BASE_URL, chainType: Sdk.ChainType.EVM }); const name = "machine_001"; const customFields = { verifications: [{ type: "EcdsaSecp256k1RecoveryMethod2020" }], services: [{ id: '#admin', type: 'admin', data: `${adminWallet.address}` }] }; const tx = await sdk.did.create({ name: name, address: machineWallet.getAddress(), customDocumentFields: customFields }); const receipt = await Sdk.sendEvmTx({ tx: tx, baseUrl: HTTPS_BASE_URL, seed: machineWallet.getPrivateKey() }); console.log("Machine DID created:", receipt.hash); } async function main() { // Create machine wallet const machineWallet = new ECDSAKeyring(); console.log("Machine Address:", machineWallet.getAddress()); // Load admin wallet const adminWallet = await getAdmin(); // Transfer tokens to machine await transferNativeToken(machineWallet, adminWallet); // Create machine DID await generateDID(machineWallet, adminWallet); console.log("Machine onboarding complete!"); } main().catch(console.error); ``` -------------------------------- ### Install MongoDB and Polkadot API Packages Source: https://docs.peaq.xyz/build/advanced-operations/off-chain-storage/mongoDB Installs the necessary npm packages for interacting with MongoDB and the Polkadot API. This is a prerequisite for using peaqStorage with MongoDB. ```bash npm install mongodb @polkadot/api ``` -------------------------------- ### Install Dependencies for Web3.js Source: https://docs.peaq.xyz/build/basic-operations/listening-parsing-chain-events/eth-subscribe Installs the necessary Node.js packages: web3 for blockchain interaction, dotenv for environment variable management, and web3-providers-ws for WebSocket connectivity. ```bash npm install web3 dotenv web3-providers-ws ``` -------------------------------- ### Install ethers.js for Blockchain Interactions Source: https://docs.peaq.xyz/build/advanced-operations/sending-bulk-transactions Installs the ethers.js library, a popular JavaScript SDK for interacting with the Ethereum blockchain. This is a prerequisite for programmatically sending transactions. ```bash npm install ethers ``` -------------------------------- ### Initialize Hardhat Project Source: https://docs.peaq.xyz/build/basic-operations/smart-contracts/build-smart-contract Initializes a new Hardhat project. It prompts the user to select a configuration file, and an empty 'hardhat.config.js' is recommended for custom setups. ```bash npx hardhat init ``` -------------------------------- ### Solidity EVM Version Configuration Source: https://docs.peaq.xyz/build/getting-started/evm-onboarding Specifies the Solidity compiler version and EVM version to use in a Hardhat project. Ensures compatibility with the 'london' hardfork features. ```javascript solidity: { version: "0.8.21", settings: { evmVersion: "london" } } ``` -------------------------------- ### Initialize peaq SDK Instance for EVM (Unsigned) Source: https://docs.peaq.xyz/sdk-reference/python/create-instance Initializes the peaq SDK for EVM transactions without a seed, returning an unsigned transaction object. Requires a base URL for the EVM chain and ChainType.EVM. Dependencies include the 'peaq-sdk' and 'python-dotenv' libraries. ```python import os from dotenv import load_dotenv from peaq_sdk import Sdk from peaq_sdk.types import ChainType load_dotenv() HTTPS_PEAQ_URL = os.getenv("HTTPS_PEAQ_URL") sdk = Sdk.create_instance( base_url=HTTPS_PEAQ_URL, chain_type=ChainType.EVM ) ``` -------------------------------- ### Install Node.js Dependencies for WebSocket Subscription Source: https://docs.peaq.xyz/build/basic-operations/listening-parsing-chain-events/chain-subscribeNewHeads Installs the necessary Node.js packages, `ws` for WebSocket communication and `dotenv` for environment variable management, required for subscribing to chain events. ```bash npm install ws dotenv ``` -------------------------------- ### Start Subsquid GraphQL Server Source: https://docs.peaq.xyz/build/advanced-operations/indexers/subsquid Starts the GraphQL server for the Subsquid indexer. This server allows you to query the indexed data using GraphQL queries. It should be run in a separate terminal from the indexer. ```bash npx squid-graphql-server ``` -------------------------------- ### Complete Machine Onboarding to peaq Network (JavaScript) Source: https://docs.peaq.xyz/build/first-depin/onboard-machine This JavaScript code demonstrates the full process of onboarding a machine to the peaq network's agung testnet. It covers creating an EVM-compatible machine wallet, funding it with native tokens from an admin wallet, and registering a Decentralized Identifier (DID) document for the machine's on-chain identity. It utilizes the ethers.js library for EVM interactions and the @peaq-network/sdk for peaq-specific functionalities. ```javascript import { ethers, Wallet } from "ethers"; import { Sdk } from "@peaq-network/sdk"; // Simple keyring class for managing EVM-compatible wallets class ECDSAKeyring { constructor(privateKey) { this.wallet = privateKey ? new Wallet(privateKey) : Wallet.createRandom(); } getAddress() { return this.wallet.address; } getPrivateKey() { return this.wallet.privateKey; } async signMessage(message) { return this.wallet.signMessage(message); } } // Load an admin wallet with tokens to fund new machine wallets async function getAdmin() { const provider = new ethers.JsonRpcProvider("https://peaq-agung.api.onfinality.io/public"); // Agung testnet const adminPrivateKey = "0xADMIN_PRIVATE_KEY"; // Replace securely return new Wallet(adminPrivateKey, provider); } // Transfer native tokens (gas) to the machine's wallet async function transferNativeToken(machineWallet, adminWallet) { const tx = await adminWallet.sendTransaction({ to: machineWallet.getAddress(), value: ethers.parseEther("1") // Transfer 1 native token }); console.log("Transaction sent:", tx.hash); await tx.wait(); console.log("Transaction confirmed."); } // Register a DID Document on the peaq network for the machine async function generateDID(machineWallet, adminWallet) { const HTTPS_BASE_URL = "https://peaq-agung.api.onfinality.io/public"; const sdk = await Sdk.createInstance({ baseUrl: HTTPS_BASE_URL, chainType: Sdk.ChainType.EVM }); const name = "project_name"; // Customize per project const customFields = { verifications: [{ type: "EcdsaSecp256k1RecoveryMethod2020" }], services: [{ id: '#admin', type: 'admin', data: `${adminWallet.address}` }] }; const tx = await sdk.did.create({ name: name, address: machineWallet.getAddress(), customDocumentFields: customFields }); const receipt = await Sdk.sendEvmTx({ tx: tx, baseUrl: HTTPS_BASE_URL, seed: machineWallet.getPrivateKey() }); console.log("peaq DID EVM receipt:\n", receipt); } // Main execution flow async function main() { // 1. Create machine wallet const machineWallet = new ECDSAKeyring(); // Optional: store these values securely // console.log("Machine Address:", machineWallet.getAddress()); // console.log("Private Key:", machineWallet.getPrivateKey()); // 2. Load admin wallet const adminWallet = await getAdmin(); // 3. Transfer tokens to the machine await transferNativeToken(machineWallet, adminWallet); // 4. Create machine DID Document await generateDID(machineWallet, adminWallet); } main(); ``` -------------------------------- ### Start Subsquid Indexer Source: https://docs.peaq.xyz/build/advanced-operations/indexers/subsquid Starts the compiled Subsquid indexer using Node.js. The '-r dotenv/config' flag ensures that environment variables from the .env file are loaded before the main script is executed. ```bash node -r dotenv/config lib/main.js ``` -------------------------------- ### SDK Initialization Source: https://docs.peaq.xyz/sdk-reference/python Initializes the Peaq SDK instance for interacting with the blockchain. It supports both EVM and Substrate chain types and can optionally take a seed for signing transactions. ```APIDOC ## POST / Sdk.create_instance ### Description Initializes the SDK and returns an instance ready to interact with the network. This function is crucial for setting up your connection to the peaq blockchain. ### Method POST ### Endpoint /Sdk.create_instance ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **base_url** (string) - Required - HTTPS/WSS URL used to connect to the blockchain. Reference connecting to peaq for supported URLs. Use **HTTPS** for EVM and **WSS** for Substrate (and EVM reads). - **chain_type** (ChainType) - Required - Defines whether the instance will generate EVM or Substrate transactions. - **seed** (string) - Optional - Private key (EVM) or mnemonic phrase (Substrate) used to execute write transactions on behalf of the user. If not set, the peaq transaction object is returned to the user for manual submission. ### Request Example ```json { "base_url": "https://your-peaq-node.com", "chain_type": "EVM", "seed": "0xyour_private_key_or_mnemonic_phrase" } ``` ### Response #### Success Response (200) - **sdk_instance** (object) - An initialized SDK instance ready for use. #### Response Example ```json { "sdk_instance": "" } ``` ``` -------------------------------- ### Install dotenv for Environment Variables Source: https://docs.peaq.xyz/build/basic-operations/smart-contracts/build-smart-contract Installs the 'dotenv' package, which allows Node.js applications to load environment variables from a .env file. This is crucial for managing sensitive data like RPC URLs and private keys. ```bash npm install dotenv ``` -------------------------------- ### Initialize peaqRobot SDK and Access Data Source: https://docs.peaq.xyz/sdk-reference/robot-sdk/home This snippet demonstrates how to initialize the PeaqRobot SDK, access the robot's address and balance, and create an identity document. It requires the 'peaq_robot' library. ```python from peaq_robot import PeaqRobot sdk = PeaqRobot() print(sdk.address) print(sdk.balance) # Create DID and store data sdk.id.create_identity() sdk.store.add_data("DEMO", {"ok": True}) ``` -------------------------------- ### Start PostgreSQL Database Container Source: https://docs.peaq.xyz/build/advanced-operations/indexers/subsquid Starts the PostgreSQL database service defined in the docker-compose.yaml file in detached mode. This command makes the database accessible on the host machine via the specified port. ```bash docker compose up -d ``` -------------------------------- ### Fetch Roles Code Examples for EVM and Substrate Source: https://docs.peaq.xyz/sdk-reference/javascript/rbac-operations/role Demonstrates fetching all roles associated with an owner address using the `fetchRoles` method for both EVM and Substrate chains. The EVM version requires a WSS base URL, while the Substrate version uses the WSS URL provided during SDK instance creation. ```javascript import { Sdk } from "@peaq-network/sdk"; const HTTPS_BASE_URL = "https://quicknode.peaq.xyz"; const WSS_BASE_URL = "wss://quicknode.peaq.xyz"; const EVM_ADDRESS = process.env["EVM_ADDRESS"]; const sdk = await Sdk.createInstance({ baseUrl: HTTPS_BASE_URL, chainType: Sdk.ChainType.EVM }); const response = await sdk.rbac.fetchRoles({ owner: EVM_ADDRESS, wssBaseUrl: WSS_BASE_URL }); ``` ```javascript // sdk.rbac.fetchRoles({}) response object [ { id: 'e09fe342-f8ee-46d1-82e2-a60a5b6e', name: 'role-name-123', enabled: true }, ... { id: 'b68a5589-1284-49e9-8276-0359a429', name: 'peaq-role-1', enabled: true } ] ``` ```javascript import { Sdk } from "@peaq-network/sdk"; const WSS_BASE_URL = "wss://quicknode.peaq.xyz"; const SUBSTRATE_ADDRESS = process.env["SUBSTRATE_ADDRESS"]; const sdk = await Sdk.createInstance({ baseUrl: WSS_BASE_URL, chainType: Sdk.ChainType.SUBSTRATE }); const response = await sdk.rbac.fetchRoles({ owner: SUBSTRATE_ADDRESS }); // disconnect when finished await sdk.disconnect(); ``` ```javascript // sdk.rbac.fetchRoles({}) response object [ { id: 'bb3d5a05-3a4a-452b-a96d-372832ff', name: 'role-name-123', enabled: true }, ... { id: 'bc3f20d5-c519-4048-8db1-4bbf48dc', name: 'peaq-role-1', enabled: true } ] ``` -------------------------------- ### Deployment Script for Upgradable SimpleStorage Contract Source: https://docs.peaq.xyz/build/basic-operations/smart-contracts/upgradable-smart-contracts A JavaScript script using Hardhat and OpenZeppelin's upgrades plugin to deploy the SimpleStorage contract as an upgradable proxy. It initializes the contract with a starting value and logs the deployed address. ```javascript // scripts/upgrade_storage.js const { ethers, upgrades } = require('hardhat'); async function main () { const SimpleStorage = await ethers.getContractFactory('SimpleStorage'); console.log('Deploying SimpleStorage...'); const simple_storage = await upgrades.deployProxy(SimpleStorage, [10], { initializer: 'store' }); await simple_storage.waitForDeployment(); console.log('SimpleStorage deployed to:', await simple_storage.getAddress()); } main(); ``` -------------------------------- ### Initialize Peaq SDK Instance (Python) Source: https://docs.peaq.xyz/sdk-reference/python Initializes the Peaq SDK with the provided base URL and chain type. This function requires the base URL and chain type. An optional seed can be provided for signing transactions. If no seed is provided, unsigned transactions are returned. ```python import os from dotenv import load_dotenv from peaq_sdk import Sdk from peaq_sdk.types import ChainType load_dotenv() HTTPS_PEAQ_URL = os.getenv("HTTPS_PEAQ_URL") # For EVM transactions sdk_evm = Sdk.create_instance( base_url=HTTPS_PEAQ_URL, chain_type=ChainType.EVM ) # For Substrate transactions (example with WSS URL) WSS_PEAQ_URL = os.getenv("WSS_PEAQ_URL") sdk_substrate = Sdk.create_instance( base_url=WSS_PEAQ_URL, chain_type=ChainType.SUBSTRATE ) ``` -------------------------------- ### Fetching Latest and Finalized Blocks in JavaScript Source: https://docs.peaq.xyz/build/getting-started/evm-onboarding Demonstrates how to fetch both the latest (optimistic) block and a finalized block using the Ethereum provider. 'latest' is good for UI, 'finalized' for irreversible operations. ```javascript // Latest for optimistic UI const latest = await provider.getBlock("latest"); // Finalized for deterministic reads const finalized = await provider.send( "eth_getBlockByNumber", ["finalized", false] ); ```