### Complete SKALE LLM TXT Client Example Source: https://docs.skale.space/cookbook/x402/buying A comprehensive TypeScript example demonstrating the setup and usage of the Faremeter SDK for accessing paywalled resources. It includes wallet creation, payment handler setup, and making the API request. ```typescript import { createLocalWallet } from "@faremeter/wallet-evm"; import { createPaymentHandler } from "@faremeter/payment-evm/exact"; import { wrap as wrapFetch } from "@faremeter/fetch"; import { createPublicClient, http, formatEther, defineChain } from "viem"; import "dotenv/config"; export const skaleChain = defineChain({ id: 324705682, name: "SKALE Base Sepolia", nativeCurrency: { decimals: 18, name: "Credits", symbol: "CREDIT" }, rpcUrls: { default: { http: ["https://base-sepolia-testnet.skalenodes.com/v1/base-testnet"] }, }, }); async function main() { const privateKey = process.env.PRIVATE_KEY; if (!privateKey) { throw new Error("PRIVATE_KEY environment variable is required"); } // Setup wallet const wallet = await createLocalWallet(skaleChain, privateKey); console.log(`Wallet address: ${wallet.account.address}`); // Setup payment-enabled fetch const assetAddress = process.env.PAYMENT_TOKEN_ADDRESS as `0x${string}`; const assetName = process.env.PAYMENT_TOKEN_NAME || "Bridged USDC (SKALE Bridge)"; const fetchWithPayment = wrapFetch(fetch, { handlers: [ createPaymentHandler(wallet, { asset: { address: assetAddress, contractName: assetName, forwarderName: assetName, forwarderVersion: "1", }, }), ], }); // Access paywalled resource - payment handled automatically! const url = "http://localhost:3000/premium/data"; try { console.log(`Accessing ${url}...`); const response = await fetchWithPayment(url, { method: "GET", headers: { "Content-Type": "application/json" }, }); if (!response.ok) { throw new Error(`Request failed: ${response.status}`); } const data = await response.json(); console.log("Premium data:", data); } catch (error) { console.error("Error:", error); } } main(); ``` -------------------------------- ### Install General Tools for SGX Server Source: https://docs.skale.space/validators/run-supernode Installs essential build and development tools required for SGXWallet setup on Ubuntu. Includes compilers, build utilities, and libraries like protobuf, flex, bison, and crypto libraries. ```shell sudo apt-get install -y build-essential make cmake gcc g++ yasm python libprotobuf10 flex bison automake libtool texinfo libgcrypt20-dev libgnutls28-dev ``` -------------------------------- ### Initialize Node.js Project and Install Hardhat Source: https://docs.skale.space/cookbook/deployment/setup-hardhat Initializes a new Node.js project and installs Hardhat along with the Hardhat Toolbox, which includes essential development tools and plugins. ```shell mkdir my-skale-project cd my-skale-project npm init -y npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox ``` -------------------------------- ### Start Development Server (Bash) Source: https://docs.skale.space/cookbook/x402/facilitator This command initiates the development server for the facilitator using pnpm. It's the primary method to get the facilitator running locally. ```bash pnpm dev ``` -------------------------------- ### Project Setup and Dependencies (Bash) Source: https://docs.skale.space/cookbook/x402/facilitator Initializes a new project directory, navigates into it, and installs necessary project dependencies using pnpm. This includes core libraries, EVM-related packages, and development tools for TypeScript and Express. ```bash mkdir skale-facilitator cd skale-facilitator pnpm init pnpm add @x402/core @x402/evm dotenv express viem pnpm add -D @types/express @types/node tsx typescript ``` -------------------------------- ### Enable SGX and install SGX driver Source: https://docs.skale.space/validators/releases/3-1-1-upgrade These commands navigate to the sgxwallet directory, enable SGX, and then install the SGX Linux driver. This is a critical step for SGX server functionality. ```bash cd sgxwallet && sudo ./sgx_enable ``` ```bash cd scripts; sudo ./sgx_linux_x64_driver_2.11.b6f5b4a.bin; cd .. ``` -------------------------------- ### Quick Start: Encrypt and Send Transaction with BITE SDK Source: https://docs.skale.space/developers/bite-protocol/typescript-sdk A quick start guide demonstrating how to initialize the BITE SDK, encrypt a transaction object (to and data fields), and send it using a web3 provider like MetaMask. It also shows how to retrieve decrypted transaction data after block finality. ```typescript import { BITE } from '@skalenetwork/bite'; const providerUrl = 'https://your-fair-rpc'; const bite = new BITE(providerUrl); // Minimal tx object: encrypts `to` and `data` and rewrites `to` to BITE magic address const tx = { to: '0x1234567890abcdef1234567890abcdef12345678', data: '0x1234abcd', }; const encryptedTx = await bite.encryptTransaction(tx); // send via your wallet / provider, e.g. window.ethereum.request({ method: 'eth_sendTransaction', params: [encryptedTx] }) // Later, fetch revealed original fields after block finality const result = await bite.getDecryptedTransactionData(''); // result => { to: '0x...', data: '0x...' } ``` -------------------------------- ### Install Project Dependencies Source: https://docs.skale.space/cookbook/deployment/setup-foundry Installs the OpenZeppelin Contracts library as a dependency for the Foundry project. This command fetches the specified contract library and adds it to the project's 'lib' directory. ```shell forge install OpenZeppelin/openzeppelin-contracts ``` -------------------------------- ### Install nftables and Docker Compose plugin Source: https://docs.skale.space/validators/releases/3-1-1-upgrade Ensures that nftables and the Docker Compose plugin are installed on the node server. These are required for network configuration and container management. ```bash sudo apt install nftables docker-compose-plugin ``` -------------------------------- ### Project Setup with npm and Vite Source: https://docs.skale.space/cookbook/privacy/sending-encrypted-transactions-with-bite Initializes a new Node.js project, installs necessary dependencies including BITE SDK, ethers, dotenv, and Vite for frontend development. It also creates a basic project structure. ```bash # Create project directory\nmkdir bite-encrypted-transfers\ncd bite-encrypted-transfers\n\n# Initialize npm project\nnpm init -y\n\n# Install dependencies\nnpm install @skalenetwork/bite ethers dotenv vite\nnpm install --save-dev vite @vitejs/plugin-react\n\n# Create basic structure\nmkdir src\ntouch src/main.js src/style.css index.html .env package.json ``` -------------------------------- ### Install Docker and Docker Compose for SGX Server Source: https://docs.skale.space/validators/run-supernode Installs Docker and the Docker Compose plugin, which are necessary for running SGXWallet in a containerized environment. Ensures container orchestration capabilities are available. ```shell sudo apt-get install -y docker sudo apt-get install -y docker.io sudo apt-get install -y docker-compose-plugin ``` -------------------------------- ### Install required packages for SGX server Source: https://docs.skale.space/validators/releases/3-1-1-upgrade Installs Docker, Docker Compose, and build essentials on the Ubuntu 22.04 server. These are necessary for running the SGX wallet services. ```bash apt-get install docker.io docker-compose build-essential ``` -------------------------------- ### Setup Foundry for SKALE Development Source: https://context7_llms A guide to setting up the Foundry development environment for building and deploying applications on the SKALE network. Foundry is a fast, portable, and extensible build system for Ethereum. ```markdown ## Setup Foundry Guide to setting up Foundry for SKALE development ``` -------------------------------- ### Create a Smart Contract Deployment Script Source: https://docs.skale.space/cookbook/deployment/setup-hardhat Provides a basic JavaScript script for deploying a smart contract using Hardhat's ethers.js integration. It demonstrates how to get the contract factory, deploy an instance, and log the contract's address. ```javascript const hre = require("hardhat"); async function main() { const MyContract = await hre.ethers.getContractFactory("MyContract"); const myContract = await MyContract.deploy(); await myContract.waitForDeployment(); console.log("Contract deployed to:", await myContract.getAddress()); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ``` -------------------------------- ### Download and Install SKALE Validator CLI Source: https://docs.skale.space/validators/run-supernode This snippet downloads the SKALE Validator CLI binary for Linux systems and places it in the user's PATH. It requires specifying the version number of the CLI. ```shell VERSION_NUM=1.3.3 && sudo -E bash -c "curl -L https://github.com/skalenetwork/validator-cli/releases/download/$VERSION_NUM/sk-val-$VERSION_NUM-`uname -s`-`uname -m` > /usr/local/bin/sk-val" ``` -------------------------------- ### Complete SKALE LLM TXT Example Source: https://docs.skale.space/cookbook/x402/buying A comprehensive example demonstrating the full workflow of accessing paywalled resources with SKALE. It includes setting up the wallet, initializing the x402 client, defining the SKALE chain, and making a request to a paywalled URL, including the payment process if required. Requires a PRIVATE_KEY environment variable. ```typescript import { x402Client, x402HTTPClient } from "@x402/core/client"; import { ExactEvmScheme } from "@x402/evm"; import { privateKeyToAccount } from "viem/accounts"; import { createPublicClient, http, formatEther } from "viem"; import { defineChain } from "viem"; import "dotenv/config"; export const skaleChain = defineChain({ id: 324705682, name: "SKALE Base Sepolia", nativeCurrency: { decimals: 18, name: "Credits", symbol: "CREDIT" }, rpcUrls: { default: { http: ["https://base-sepolia-testnet.skalenodes.com/v1/base-testnet"] }, }, }); async function main() { const privateKey = process.env.PRIVATE_KEY; if (!privateKey) { throw new Error("PRIVATE_KEY environment variable is required"); } // Setup wallet const account = privateKeyToAccount(privateKey as `0x${string}`); console.log(`Wallet address: ${account.address}`); // Setup x402 client const evmScheme = new ExactEvmScheme(account); const coreClient = new x402Client().register("eip155:*", evmScheme); const httpClient = new x402HTTPClient(coreClient); // Access paywalled resource const url = "http://localhost:3000/premium/data"; try { const response = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json" }, }); if (response.status === 402) { console.log("Payment required, processing..."); const responseBody = await response.json(); const paymentRequired = httpClient.getPaymentRequiredResponse( (name: string) => response.headers.get(name), responseBody ); const paymentPayload = await httpClient.createPaymentPayload(paymentRequired); const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload); const paidResponse = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json", ...paymentHeaders, }, }); if (!paidResponse.ok) { throw new Error(`Payment failed: ${paidResponse.status}`); } console.log("Payment successful, data received:", await paidResponse.json()); } else if (response.ok) { console.log("No payment required, data received:", await response.json()); } else { throw new Error(`Failed to access resource: ${response.status}`); } } catch (error) { console.error("Error accessing resource:", error); } } main(); ``` -------------------------------- ### Verify Foundry Installation Source: https://docs.skale.space/cookbook/deployment/setup-foundry Checks if Foundry tools (forge, cast, anvil) have been installed correctly by displaying their version numbers. This is a crucial step after installation to ensure the tools are accessible. ```shell forge --version cast --version anvil --version ``` -------------------------------- ### Installing Project Dependencies (Bash) Source: https://docs.skale.space/cookbook/agents/build-an-agent This command installs all the necessary npm packages for the project, including core x402 libraries, LangChain components, Hono for the server, and other utilities. It's essential to run this before setting up environment variables or running the application. ```bash npm install @x402/core @x402/evm @x402/hono @langchain/anthropic @langchain/core hono @hono/node-server viem dotenv ``` -------------------------------- ### Install iptables-persistent Source: https://docs.skale.space/validators/run-supernode Installs iptables-persistent with automatic saving of IPv4 and IPv6 rules. This ensures firewall rules are maintained across reboots. ```shell echo iptables-persistent iptables-persistent/autosave_v4 boolean true | sudo debconf-set-selections echo iptables-persistent iptables-persistent/autosave_v6 boolean true | sudo debconf-set-selections sudo apt install iptables-persistent -y ``` -------------------------------- ### Generate Wildcard SSL with Letsencrypt (Shell) Source: https://docs.skale.space/validators/node-cli/node-ssl-setup This snippet demonstrates how to generate a wildcard SSL certificate using Letsencrypt and Certbot. It requires Certbot to be installed and assumes you are running commands in a shell environment. The output includes commands for obtaining the certificate and copying the generated .pem files to a secure location. ```shell certbot certonly --standalone -d my.domain.com ``` ```shell cp *.pem ~/[SECURE_DIR] ``` -------------------------------- ### Install Foundry Source: https://docs.skale.space/cookbook/deployment/setup-foundry Installs the latest stable release of Foundry, which includes Forge, Cast, Anvil, and Chisel. This command is run directly in the terminal. ```shell foundryup ``` -------------------------------- ### Initialize and Start Server (Node.js) Source: https://docs.skale.space/cookbook/agents/build-an-agent This function initializes the AI agent and sets up the protected weather route. It then starts the server, making the weather API accessible via HTTP. ```typescript async function startServer() { await initializeAgent(); await setupWeatherRoute(); serve({ fetch: app.fetch, port: PORT }, () => { console.log(`[Server] Running on http://localhost:${PORT}`); console.log(`[Server] Weather endpoint: GET /api/weather (payment required)`); }); } startServer(); ``` -------------------------------- ### Facilitator Server Setup and API Endpoints (TypeScript) Source: https://docs.skale.space/cookbook/x402/facilitator This code snippet demonstrates the setup of an Express.js server for the facilitator. It includes routes for '/verify', '/settle', and '/supported', handling payment verification, settlement, and retrieving supported schemes respectively. It also shows event listeners for different settlement stages. ```typescript .onBeforeSettle(async (context) => { console.log("Before settle", context); }) .onAfterSettle(async (context) => { console.log("After settle", context); }) .onSettleFailure(async (context) => { console.log("Settle failure", context); }); registerExactEvmScheme(facilitator, { signer: evmSigner, networks: "eip155:324705682", deployERC4337WithEIP6492: true, }); const app = express(); app.use(express.json()); app.post("/verify", async (req, res) => { try { const { paymentPayload, paymentRequirements } = req.body as { paymentPayload: PaymentPayload; paymentRequirements: PaymentRequirements; }; if (!paymentPayload || !paymentRequirements) { return res.status(400).json({ error: "Missing paymentPayload or paymentRequirements", }); } const response: VerifyResponse = await facilitator.verify( paymentPayload, paymentRequirements ); res.json(response); } catch (error) { console.error("Verify error:", error); res.status(500).json({ error: error instanceof Error ? error.message : "Unknown error", }); } }); app.post("/settle", async (req, res) => { try { const { paymentPayload, paymentRequirements } = req.body; if (!paymentPayload || !paymentRequirements) { return res.status(400).json({ error: "Missing paymentPayload or paymentRequirements", }); } const response: SettleResponse = await facilitator.settle( paymentPayload as PaymentPayload, paymentRequirements as PaymentRequirements ); res.json(response); } catch (error) { console.error("Settle error:", error); if ( error instanceof Error && error.message.includes("Settlement aborted:") ) { return res.json({ success: false, errorReason: error.message.replace("Settlement aborted: ", ""), network: req.body?.paymentPayload?.network || "unknown", } as SettleResponse); } res.status(500).json({ error: error instanceof Error ? error.message : "Unknown error", }); } }); app.get("/supported", async (req, res) => { try { const response = facilitator.getSupported(); res.json(response); } catch (error) { console.error("Supported error:", error); res.status(500).json({ error: error instanceof Error ? error.message : "Unknown error", }); } }); app.listen(parseInt(PORT), () => { console.log(`Facilitator listening on port ${PORT}`); }); ``` -------------------------------- ### Start SGX Wallet Container Source: https://docs.skale.space/validators/run-supernode Starts the SGXWallet containers in detached mode using Docker Compose. This command assumes the 'docker-compose.yml' file is correctly configured in the current directory. ```shell sudo docker compose up -d ``` -------------------------------- ### Install SGX Linux Driver Source: https://docs.skale.space/validators/run-supernode Installs the Intel SGX driver for Linux (version 2.5.0) from the provided binary file. This driver is essential for the operating system to interact with the SGX hardware. ```shell cd scripts sudo ./sgx_linux_x64_driver_2.5.0_2605efa.bin cd .. ``` -------------------------------- ### Main Facilitator Application (TypeScript) Source: https://docs.skale.space/cookbook/x402/facilitator Implements the core facilitator service using the @x402/core library. It sets up an Express server, configures an EVM signer using viem, and integrates with the x402Facilitator class. It includes event handlers for verification lifecycle. ```typescript import { x402Facilitator } from "@x402/core/facilitator"; import { PaymentPayload, PaymentRequirements, SettleResponse, VerifyResponse, } from "@x402/core/types"; import { toFacilitatorEvmSigner } from "@x402/evm"; import { registerExactEvmScheme } from "@x402/evm/exact/facilitator"; import dotenv from "dotenv"; import express from "express"; import { createWalletClient, http, publicActions } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { skaleBaseSepoliaTestnet } from "viem/chains"; dotenv.config(); const PORT = process.env.PORT || "4022"; if (!process.env.FACILITATOR_SIGNER_PK) { console.error("FACILITATOR_SIGNER_PK environment variable is required"); process.exit(1); } const evmAccount = privateKeyToAccount( process.env.FACILITATOR_SIGNER_PK as `0x${string}` ); console.info(`EVM Facilitator account: ${evmAccount.address}`); const viemClient = createWalletClient({ account: evmAccount, chain: skaleBaseSepoliaTestnet, transport: http(), }).extend(publicActions); const evmSigner = toFacilitatorEvmSigner({ getCode: (args: { address: `0x${string}` }) => viemClient.getCode(args), address: evmAccount.address, readContract: (args: { address: `0x${string}`; abi: readonly unknown[]; functionName: string; args?: readonly unknown[]; }) => viemClient.readContract({ ...args, args: args.args || [], }), verifyTypedData: (args: { address: `0x${string}`; domain: Record; types: Record; primaryType: string; message: Record; signature: `0x${string}`; }) => viemClient.verifyTypedData(args as Parameters[0]), writeContract: (args: { address: `0x${string}`; abi: readonly unknown[]; functionName: string; args: readonly unknown[]; }) => viemClient.writeContract({ ...args, args: args.args || [], }), sendTransaction: (args: { to: `0x${string}`; data: `0x${string}` }) => viemClient.sendTransaction(args), waitForTransactionReceipt: (args: { hash: `0x${string}` }) => viemClient.waitForTransactionReceipt(args), }); const facilitator = new x402Facilitator() .onBeforeVerify(async (context) => { console.log("Before verify", context); }) .onAfterVerify(async (context) => { console.log("After verify", context); }) .onVerifyFailure(async (context) => { ``` -------------------------------- ### Environment Setup for x402 Payments (Bash) Source: https://docs.skale.space/cookbook/x402/buying This snippet demonstrates how to set up environment variables for making x402 payments. It requires a private key for your wallet and the contract address and name for the payment token (e.g., USDC) on the SKALE Chain. Ensure sensitive information like private keys is kept secure and not committed to version control. ```bash # Your wallet private key (never commit this!) PRIVATE_KEY=0xYourPrivateKey # USDC token contract on SKALE PAYMENT_TOKEN_ADDRESS=0x2e08028E3C4c2356572E096d8EF835cD5C6030bD PAYMENT_TOKEN_NAME="Bridged USDC (SKALE Bridge)" ``` -------------------------------- ### Install Coinbase SDK Dependencies Source: https://docs.skale.space/cookbook/x402/accepting-payments Installs the necessary npm packages for the Hono framework, Coinbase SDK, and related utilities. This includes hono, @hono/node-server, @x402/hono, @x402/evm, @x402/core, and dotenv. ```bash npm install hono @hono/node-server @x402/hono @x402/evm @x402/core dotenv ``` -------------------------------- ### Verify SGX Driver Installation Source: https://docs.skale.space/validators/run-supernode Checks for the presence of the SGX device file in the /dev directory to confirm that the Intel SGX driver has been successfully installed. It checks for both 'isgx' and 'sgx_enclave' device names. ```shell ls /dev/isgx ls /dev/sgx_enclave ``` -------------------------------- ### Install cpuid and libelf-dev for SGX Verification Source: https://docs.skale.space/validators/run-supernode Installs the 'cpuid' utility and 'libelf-dev' package, which are used to verify SGX support on the processor and handle ELF file manipulation, respectively. Essential for SGX diagnostics. ```shell sudo apt-get install -y libelf-dev cpuid ``` -------------------------------- ### Implement BasicAgent for Resource Access and Payments Source: https://docs.skale.space/cookbook/agents/build-an-agent Creates a `BasicAgent` class that handles programmatic x402 payments and resource access without AI. It utilizes `@x402/core`, `@x402/evm`, and `viem` for wallet management, payment signing, and network interaction. The agent can be initialized asynchronously and provides methods to access resources, handling 402 payment required responses. ```typescript import { x402Client, x402HTTPClient } from "@x402/core/client"; import { ExactEvmScheme } from "@x402/evm"; import { privateKeyToAccount } from "viem/accounts"; import { createPublicClient, http, formatEther } from "viem"; import { skaleChain } from "./chain"; import "dotenv/config"; type AccessResult = { success: boolean; data?: unknown; error?: string; }; class BasicAgent { private httpClient: x402HTTPClient; private walletAddress: string; private publicClient: ReturnType; private constructor( httpClient: x402HTTPClient, walletAddress: string, publicClient: ReturnType ) { this.httpClient = httpClient; this.walletAddress = walletAddress; this.publicClient = publicClient; } static async create(): Promise { const privateKey = process.env.PRIVATE_KEY; if (!privateKey) { throw new Error("PRIVATE_KEY environment variable is required"); } // Create wallet account from private key const account = privateKeyToAccount(privateKey as `0x${string}`); // Create EVM scheme for signing payments const evmScheme = new ExactEvmScheme(account); // Register scheme for all EVM networks const coreClient = new x402Client().register("eip155:*", evmScheme); const httpClient = new x402HTTPClient(coreClient); // Create public client for balance checks const publicClient = createPublicClient({ chain: skaleChain, transport: http(), }); console.log(`Agent initialized with wallet: ${account.address}`); return new BasicAgent(httpClient, account.address, publicClient); } async accessResource(url: string): Promise { console.log(`Accessing resource: ${url}`); try { const response = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json" }, }); if (response.status === 402) { return this.handlePaymentRequired(response, url); } if (!response.ok) { return { success: false, error: `Request failed: ${response.status}` }; } const data = await response.json(); return { success: true, data }; } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; return { success: false, error: message }; } } private async handlePaymentRequired( response: Response, url: string ): Promise { console.log("Payment required (402), processing payment..."); try { const responseBody = await response.json(); // Get payment requirements from response headers and body const paymentRequired = this.httpClient.getPaymentRequiredResponse( (name: string) => response.headers.get(name), responseBody ); console.log(`Payment options: ${paymentRequired.accepts.length}`); // Create signed payment payload const paymentPayload = await this.httpClient.createPaymentPayload(paymentRequired); // Encode payment headers for the retry request ``` -------------------------------- ### Register SKALE Node with Domain Name Source: https://docs.skale.space/validators/node-cli/node-ssl-setup Command to register a new SKALE node, including its IP address and a designated domain name. This command is used during the initial node setup process. ```shell skale node register --ip 1.2.3.4 -d node-0.awesome-validator.com --name node-0-AV ``` -------------------------------- ### Create and Navigate Foundry Project Source: https://docs.skale.space/cookbook/deployment/setup-foundry Initializes a new Foundry project named 'my-skale-project' and then changes the current directory into the newly created project folder. This sets up the basic file structure for a smart contract project. ```shell forge init my-skale-project cd my-skale-project ``` -------------------------------- ### Test Weather Client Flow (TypeScript) Source: https://docs.skale.space/cookbook/agents/build-an-agent Sets up and runs the Weather Client to fetch weather data. It initializes the client, requests the forecast, and then logs the received data or any errors encountered during the process. This serves as a complete example of the client's usage. ```typescript import { WeatherClient } from "./client.js"; async function main() { console.log("Initializing Weather Client... "); const client = await WeatherClient.create(); console.log("Requesting weather forecast... "); const result = await client.getWeather(); if (result.success && result.data) { console.log(`Weather Forecast for ${result.data.data.city}: `); console.log("-".repeat(50)); for (const day of result.data.data.forecast) { console.log(` ${day.dayOfWeek} (${day.date}): ${day.condition} - ${day.minTemp}C to ${day.maxTemp}C `); } console.log("-".repeat(50)); console.log(`Generated: ${result.data.timestamp} `); } else { console.error("Failed to get weather:", result.error); } } main().catch(console.error); ``` -------------------------------- ### Verify Supernode Installation and Health Source: https://docs.skale.space/validators/run-supernode Verifies the SKALE supernode installation and checks the connection status between the supernode and SGXWallet. Commands include 'skale wallet info' for wallet details and 'skale health sgx' for SGX server status. ```shell sudo skale wallet info sudo skale health sgx ``` -------------------------------- ### SKALE Supernode .env Configuration Example Source: https://docs.skale.space/validators/run-supernode Provides an example of the .env file configuration for a SKALE supernode, detailing essential variables for network connection, container versions, and logging. These variables are crucial for the Node CLI to operate correctly. ```dotenv CONTAINER_CONFIGS_STREAM=4.0.1 DOCKER_LVMPY_STREAM=1.0.2-stable.0 FILEBEAT_HOST=filebeat.mainnet.skalenodes.com:5000 MANAGER_CONTRACTS_ABI_URL= https://raw.githubusercontent.com/skalenetwork/concepts/refs/heads/master/releases/mainnet/skale-manager/1.12.0/skale-manager-1.12.0-mainnet-abi.json IMA_CONTRACT_ABI_URL=https://raw.githubusercontent.com/skalenetwork/concepts/refs/heads/master/releases/mainnet/IMA/2.2.0/mainnet/abi.json ENV_TYPE=mainnet DISK_MOUNTPOINT=[DISK_MOUNTPOINT] IMA_ENDPOINT=[IMA_ENDPOINT] ENDPOINT=[ENDPOINT] SGX_SERVER_URL=[SGX_SERVER_URL] # Do not add a trailing "/" after the port number. ``` -------------------------------- ### Setup Hardhat for SKALE Development Source: https://context7_llms This documentation provides instructions for setting up Hardhat, a popular Ethereum development environment, for use with the SKALE network. It covers configuration and essential steps for a smooth development workflow. ```markdown ## Setup Hardhat Guide to setting up Hardhat for SKALE development ``` -------------------------------- ### Install Docker, Docker Compose, and Dependencies on Linux Source: https://docs.skale.space/validators/run-sync-node Installs Docker, Docker Compose version 1.27.4, and essential system packages (iptables-persistent, btrfs-progs, lsof, lvm2, psmisc) required for the SKALE sync node setup on a Linux machine. ```shell sudo apt-get update # Install Docker and Docker-compose sudo apt-get install docker.io sudo curl -L "https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose # Install other dependencies sudo apt install iptables-persistent btrfs-progs lsof lvm2 psmisc # Setup Swapfile sudo fallocate -l 16G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile sudo cp /etc/fstab /etc/fstab.bak echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab ``` -------------------------------- ### Setup Ledger Wallet for Skale CLI Source: https://docs.skale.space/validators/validator-cli/releases/v1-2-0 Initializes the Skale CLI to work with a Ledger hardware wallet. Requires specifying the address index and key type (live or legacy). ```shell sk-val wallet setup-ledger --address-index --keys-type ``` -------------------------------- ### Upgrade system packages and reboot Source: https://docs.skale.space/validators/releases/3-1-1-upgrade Updates the package list and upgrades all installed packages on the system. A reboot is required after the upgrade. ```bash sudo apt update && sudo apt upgrade sudo reboot ``` -------------------------------- ### Check SKALE Node SSL Status Source: https://docs.skale.space/validators/node-cli/node-ssl-setup Command to verify the current SSL certificate status on a SKALE node after uploading. ```shell skale ssl status ``` -------------------------------- ### Install SGX Packages (Bash) Source: https://docs.skale.space/validators/migrate-node-with-sgxwallet Installs essential packages for SGX functionality, including Docker, Docker Compose, build tools, and SGX-related libraries. Ensures the system is up-to-date before installing new packages. ```bash sudo apt-get update && sudo apt-get upgrade -y sudo apt-get install -y docker.io docker-compose-plugin sudo apt-get install -y build-essential make cmake gcc g++ yasm python libprotobuf10 flex bison automake libtool texinfo libgcrypt20-dev libgnutls28-dev sudo apt-get install -y docker sudo apt-get install -y libelf-dev cpuid ``` -------------------------------- ### Download and Install Node-CLI (Bash) Source: https://docs.skale.space/validators/migrate-node-with-sgxwallet Downloads the SKALE node-CLI tool from a GitHub release, saves it to `/usr/local/bin/skale`, and makes it executable. Includes a verification step to check the installed version. ```bash curl -L https://github.com/skalenetwork/node-cli/releases/download/2.6.2/skale-2.6.2-Linux-x86_64 > /usr/local/bin/skale chmod +x /usr/local/bin/skale # Verify installation skale --version ``` -------------------------------- ### Compile, Test, and Verify Contracts with Hardhat Source: https://docs.skale.space/cookbook/deployment/setup-hardhat Demonstrates essential Hardhat commands for smart contract development: compiling contracts, running tests, and verifying deployed contracts on SKALE testnet using the Hardhat verify plugin. Contract verification requires the contract address and constructor arguments. ```shell npx hardhat compile npx hardhat test npx hardhat verify --network skale_testnet ``` -------------------------------- ### Set New Gas Limit for SKALE Chain Message Size Source: https://docs.skale.space/developers/skale-bridge/messaging-layer/message-proxy This snippet shows how to set a new gas limit for a SKALE Chain's message proxy after the necessary role has been assigned. It provides examples using the MultisigWallet CLI and Ethers v6. Ensure 'ethers' and 'dotenv' are installed for the Ethers v6 example. ```shell npx msig encodeData schain-name-here MessageProxyForSchain setNewGasLimit 3000000 ``` ```typescript /** * Run: * npm install ethers dotenv */ import { Contract, JsonRpcProvider, Wallet } from "ethers"; import dotenv from "dotenv"; dotenv.config(); const MSG_PROXY_SCHAIN_ADDR = "0xd2AAa00100000000000000000000000000000000"; const MSG_PROXY_SCHAIN_ABI = [ "function grantRole(bytes32 role, address account) external", "function setNewGasLimit(uint256 newGasLimit) external" ]; const provider = new JsonRpcProvider(process.env.RPC_URL); const wallet = new Wallet(process.env.PRIVATE_KEY); const contract = new Contract(MSG_PROXY_SCHAIN_ADDR, MSG_PROXY_SCHAIN_ABI, wallet); const res = await contract.setNewGasLimit(3000000); // Set to 3,0000,000 ``` -------------------------------- ### Enable SGX and Install Driver (Shell) Source: https://docs.skale.space/validators/migrate-node-with-sgxwallet Executes the 'sgx_enable' utility to enable SGX on the server and then installs the SGX Linux driver. A system reboot is required after driver installation for the changes to take effect. ```shell sudo ./sgx_enable cd scripts sudo ./sgx_linux_x64_driver_2.11.b6f5b4a.bin cd .. # System Reboot required ``` -------------------------------- ### Clone and Checkout SGXWallet Repository Source: https://docs.skale.space/validators/run-supernode Clones the SGXWallet repository from GitHub and checks out a specific stable version (1.9.1-stable.1). This ensures the correct source code is used for installation on the SGX-enabled server. ```shell git clone https://github.com/skalenetwork/sgxwallet/ cd sgxwallet git checkout tags/1.9.1-stable.1 ``` -------------------------------- ### Server-Side Integration with x402x (TypeScript) Source: https://docs.skale.space/cookbook/facilitators/using-x402x This TypeScript code demonstrates how to set up a server using Hono that integrates with the x402x facilitator. It includes initializing the facilitator client, registering payment schemes, applying payment middleware for protected routes, and serving premium content. ```typescript import { Hono } from "hono"; import { serve } from "@hono/node-server"; import { paymentMiddleware, x402ResourceServer } from "@x402/hono"; import { ExactEvmScheme } from "@x402/evm/exact/server"; import { HTTPFacilitatorClient } from "@x402/core/server"; import type { Network } from "@x402/core/types"; import "dotenv/config"; const app = new Hono(); async function main() { const facilitatorUrl = process.env.FACILITATOR_URL!; const apiKey = process.env.X402X_API_KEY!; const receivingAddress = process.env.RECEIVING_ADDRESS as `0x${string}`; const paymentTokenAddress = process.env.PAYMENT_TOKEN_ADDRESS as `0x${string}`; const paymentTokenName = process.env.PAYMENT_TOKEN_NAME || "Axios USD"; const networkChainId = process.env.NETWORK_CHAIN_ID || "324705682"; const network: Network = `eip155:${networkChainId}`; // Initialize x402x facilitator client with authentication const facilitatorClient = new HTTPFacilitatorClient({ url: facilitatorUrl, headers: { "X-API-Key": apiKey, "Authorization": `Bearer ${apiKey}`, }, }); const resourceServer = new x402ResourceServer(facilitatorClient); resourceServer.register("eip155:*", new ExactEvmScheme()); // Apply payment middleware app.use( paymentMiddleware( { "GET /api/premium": { accepts: [ { scheme: "exact", network: network, payTo: receivingAddress, price: { amount: "50000", // 0.05 tokens asset: paymentTokenAddress, extra: { name: paymentTokenName, version: "1", }, }, }, ], description: "Premium content with x402x", mimeType: "application/json", }, }, resourceServer ) ); // Protected endpoint app.get("/api/premium", (c) => { return c.json({ message: "Premium content unlocked via x402x!", features: ["analytics", "webhooks", "rate-limiting"], timestamp: new Date().toISOString(), }); }); const port = Number(process.env.PORT) || 3000; serve({ fetch: app.fetch, port }, () => { console.log(`Server running on http://localhost:${port}`); console.log(`Using x402x facilitator: ${facilitatorUrl}`); }); } main().catch(console.error); ```