Pharos 백서

Pharos

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 18쪽 중 17쪽

r any issues, refer to the Troubleshooting section or consult the Rust documentation. Happy building! 🚀 # Interoperability This guide is suitable for developers who want to realize interoperability between EVM and WASM. If you are a new user of Ethereum, please consider researching the [Ethereum documentation](https://ethereum.org/en/developers/docs/) before continuing. # Call EVM From WASM This guide will walk you through the process of calling EVM contracts from the WASM code e.g., Rust. ### Prerequisites Before you begin, ensure you have the following: * Git: Used for code management and obtain examples. * Rust: Install it from [rust-lang.org](https://www.rust-lang.org/tools/install). * Pharos Devnet/Testnet Access: Access to a Pharos node (local or remote) for interacting with the blockchain. ### Setup 1: Install WASM Toolchains With Cargo Install the pharos wasm toolchain plugin using the Cargo tool: ```shell cargo install --git https://github.com/PharosNetwork/pharos-cargo-stylus ``` Add the `wasm32-unknown-unknown` build target to your Rust compiler: ```shell rustup target add wasm32-unknown-unknown ``` You should now have it available as a Cargo subcommand: ```shell cargo stylus --help Cargo subcommand for developing Pharos Stylus projects ``` > Note: Pharos built the chain excution client from scratch using C++, and we design, developed and open-sourced the [Dora](https://github.com/dp-labs/dora) VM, which combines EVM and WASM in a deeply compiled VM arch with native interoperability. The Rust toolchain and Rust SDK are forked from Stylus toolchain and SDK to facilitate easier adoption, the change here is the removal of Arbitrum ink billing and the simplification of the activation and compilation process on Pharos. ### Setup 2: Set Up the Project Clone the example repo: ```shell git clone https://github.com/PharosNetwork/examples cd examples/interoperability/call-evm-from-wasm ``` ### Setup 3: Write the Interoperability Contract * Create a new file for your interoperability contract: ```shell touch src/lib.rs ``` Write the interoperability Contract: * Open `src/lib.rs` in your favorite text editor and add the following code: ```rust #![cfg_attr(not(feature = "export-abi"), no_main)] extern crate alloc; use stylus_sdk::{ abi::Bytes, alloy_primitives::{Address, U256}, prelude::*, stylus_core::calls::context::Call, }; use alloy_sol_types::{sol, SolCall}; sol! { interface IErc20 { function mint(uint256 value) external; } } #[storage] #[entrypoint] pub struct Interoperability; #[public] impl Interoperability { /// Here we can call an EVM contract with the given target address and calldata. pub fn execute(&self, target: Address, data: Bytes) -> Bytes { let result = self.vm().call(&Call::default(), target, &data); result.unwrap().into() } /// Here we can transfer ETH to the given target address. pub fn transfer_eth(&self, to: Address, amount: U256) -> Result<(), Vec<u8>> { self.vm().transfer_eth(to, amount) } /// Here we call an ERC20 token contract written in Solidity. pub fn mint_erc20(&self, erc20: Address, value: U256) -> Bytes { self.execute(erc20, Bytes(IErc20::mintCall { value, }.abi_encode())) } } ``` Compile the Smart Contract: * Use cargo to compile the contract: ```shell cargo stylus check --endpoint=<PHAROS_RPC_URL> ``` ### Step 4: Deploy the Interoperability Contract ```shell cargo stylus deploy --private-key=<YOUR_PRIVATE_KEY> --endpoint=<PHAROS_RPC_URL> ``` ### Troubleshooting * **Contract Deployment Fails**: Ensure you have enough testnet tokens to cover the deployment cost. * **Interaction Issues**: Verify that the contract address and ABI are correct. * **Insufficient Balance**: Ensure your wallet has enough tokens to transfer. # x402 A developer guide on how to get started with x402 on Pharos Mainnet ## Overview x402 is an open, internet-native payment protocol. The HTTP 402 status code was defined in the early HTTP/1.1 specification as “Payment Required.” However, for a long time, it served only as a reserved status code with few practical applications. With the maturation of blockchain and crypto-payment infrastructure, this status code has been reactivated, evolving into a lightweight, trustless mechanism for content payment. In this model, when a client requests protected resources (such as articles, API responses, or data streams), the server does not return the content directly. Instead, it returns an HTTP 402 response accompanied by payment instructions (e.g., recipient address, amount, supported payment networks, etc.). The client initiates a micro-payment—either on-chain or off-chain—via a wallet. Once the server verifies the validity of the transaction, it unlocks and delivers the requested content. In decentralized networks like Pharos, this process is typically implemented as follows: the user sends a micro-token transfer to a specified address → the network node or server-side listens for and verifies the transaction → the original requested resource is automatically returned upon successful verification. The entire process requires no registration, login, or traditional payment gateways, truly achieving “pay-as-you-go, instant access.” This mechanism provides native, programmable payment capabilities for AI agents, automated services, or IoT devices, serving as one of the key infrastructures for building an Autonomous Economy. ## Working <figure><img src="https://3298017099-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNmFp0ycownpuaUNf2xeE%2Fuploads%2Fgit-blob-a1bf544d2e47c4a8180faa23a896ded777be26f9%2Fx402-1.png?alt=media" alt="x402 Flowchart"><figcaption><p>x402 Flowchart</p></figcaption></figure> ### Initial Request and Payment Requirements * **Resource Request Initiation:** The client initiates an HTTP request (e.g., `GET /api`) to the resource server for a specific protected resource. * **Payment Trigger Response:** The server returns an `HTTP 402 Payment Required` status code. A Base64-encoded `PaymentRequired` object is carried in the response body via the `PAYMENT-REQUIRED` header. This object defines the payment scheme, target network, and specific payment parameters required for the current transaction. ### Payment Credential Construction and Signing * **Scheme Selection and Payment Payload Generation:** The client parses the payment requirements returned by the server and selects a specific payment scheme based on its own supported payment capabilities. Subsequently, the client constructs a `PaymentPayload` containing the necessary metadata according to the protocol specifications of that scheme. * **Secondary Request Submission:** The client re-initiates the resource request and attaches the signed `PaymentPayload` in the `PAYMENT-SIGNATURE` HTTP header. ### Verification * **Verification Routing:** Upon receiving the signed request, the resource server executes validation logic. The server can choose to perform local verification or forward the `PaymentPayload` and the original `PaymentRequirements` to the Facilitator's `/verify` interface for remote verification. **Compliance Check:** The Facilitator verifies the payload according to the specified payment scheme and blockchain network rules, then returns a `Verification Response` to the resource server. * **Access Control Decisions:** * **Verification Failed:** If the verification does not pass, the resource server returns a 402 status code and error details again. * **Verification Succeeded:** If the verification passes, the resource server confirms the payment credential is valid and immediately initiates business logic processing (Do Work), preparing for on-chain settlement. ### On-chain Settlement and Confirmation * **Transaction Broadcasting:** The resource server is responsible for initiating fund settlement. This can be completed by interacting directly with a blockchain node or by delegating it to a Facilitator. If delegated, the server sends the payment credential to the Facilitator's `/settle` interface. * **Block Inclusion:** The Facilitator submits the transaction to the blockchain network (Submit tx). ### Delivery and Receipt * **Settlement Feedback:** Once the on-chain transaction is confirmed, the Facilitator returns a settlement execution response (Settlement Response) containing the transaction hash (`tx_hash`) to the resource server. * **Resource Delivery:** The resource server sends an `HTTP 200 OK` response to the client, placing the requested resource content in the response body. Simultaneously, to provide proof of payment, the server attaches Base64-encoded settlement response information in the `PAYMENT-RESPONSE` response header, marking the completion of the entire "pay-before-receive" closed loop. **Pharos Support:** The x402 protocol itself is chain-agnostic. On Pharos, it supports all ERC-20 tokens. Pharos’s high-performance features (30,000 TPS, sub-second finality) make it particularly suitable for x402 micro-payment scenarios. ## Use Cases x402 enables micro-payment and pay-per-use scenarios that were previously impossible due to economic unfeasibility. Below are some possible application scenarios: ### Agent Commerce * **AI Agents subscribing to content services with auto-renewal:** AI agents can represent users in subscribing to content services such as industry updates, financial newsletters, or in-depth analysis reports, automatically completing periodic fee payments and renewal operations through integrated digital wallets. * **Pay-per-use AI capability calls:** Users or systems pay based on the actual number of uses when calling Large Language Model (LLM) inference, image generation, or other AI APIs. * **Payments between agents:** Supports peer-to-peer payments between multiple autonomous agents for data sharing, task collaboration, or service provision without human intervention. * **Automated financial trading agents:** Based on real-time market data and external information sources (e.g., paid data streams), these agents autonomously execute high-frequency trading strategies and dynamically procure necessary data resources to optimize decision-making. ### Medical and Health Tech * **AI-assisted diagnostic reports:** After users upload medical images, they pay to unlock structured diagnostic suggestions. * **Personalized health advice APIs:** Wearable devices call health analysis models and pay-per-call to obtain deep insights. * **Access to electronic medical record fragments:** Third-party applications request specific medical visit records, and patients authorize and pay a small fee to share data. ### Education and Knowledge Services * **AI Tutor single-question answering:** Basic prompts are free, while in-depth analysis requires payment to unlock. * **Professional course fragment unlocking:** After a trial preview, users pay by the minute or chapter to continue learning. * **Single academic paper access:** No subscription required; pay per paper for instant PDF access. ### E-commerce and Consumer Services * **Personalized recommendation engine calls:** E-commerce platforms pay AI service providers based on successful conversions. * **AR try-on/make-up experience:** Payment is required to unlock real-time rendering before high-precision virtual trials. * **Supply chain risk assessment queries:** Enterprises pay-per-query for supplier risks, which can be used for procurement decision-making. ### Other Scenarios * **Computing power rental:** Billing by the second for using GPU/CPU resources for training or inference. * **IoT micro-transactions:** Sensor networks pay automatically based on data points or events (e.g., environmental monitoring, smart meters). * **Sustainability and carbon credits:** Companies or individuals purchase carbon offsets on demand, with the API returning a 402 to trigger instant settlement. **Key Advantage:** x402 transaction costs on Pharos are extremely low, making true micro-payments possible. Combined with instant finality, this enables real-time access control. ## x402 SDK for Pharos ### Server-side: Using Express + x402 Middleware For Express applications, you can use the middleware pattern: ```ts // Load .env environment variables import { config } from "dotenv"; config(); // Import required modules import express from "express"; import { paymentMiddleware, x402ResourceServer } from "@x402/express"; import { ExactEvmScheme } from "@x402/evm/exact/server"; import { HTTPFacilitatorClient } from "@x402/core/server"; // === Environment Configuration === const payToAddress = process.env.PAY_TO_ADDRESS as `0x${string}`; if (!payToAddress) { console.error("❌ Please set the PAY_TO_ADDRESS environment variable"); console.error('Example: export PAY_TO_ADDRESS=0xYourAddressHere'); process.exit(1); } const facilitatorUrl = process.env.FACILITATOR_URL; // Facilitator service URL const port = parseInt(process.env.PORT || "4021", 10); // Listening port // USDC Configuration const usdcAddress = process.env.USDC_ADDRESS; // USDC contract address on Pharos const usdcName = process.env.USDC_NAME || "USDC"; // === Initialize Client and Resource Server === const facilitatorClient = new HTTPFacilitatorClient({ url: facilitatorUrl }); const resourceServer = new x402ResourceServer(facilitatorClient); // === Create EVM Payment Scheme and Register Custom Amount Parser === const evmScheme = new ExactEvmScheme(); // Convert USD amount to USDC (6 decimals precision) evmScheme.registerMoneyParser(async (amount: number, network: string) => { if (network === "eip155:1672") { return { amount: Math.round(amount * 1e6).toString(), // Convert to integer string (e.g., 0.01 → "10000") asset: usdcAddress, // USDC contract address extra: { token: usdcName, name: usdcName, version: "2", }, }; } return null; }); // Register Pharos Pacific Mainnet (Chain ID: 1672) resourceServer.register("eip155:1672", evmScheme); // === Create Express App === const app = express(); // Use payment middleware to protect routes app.use( paymentMiddleware( { // Premium endpoint: $0.01 "GET /data": { accepts: { scheme: "exact", price: "0.01", network: "eip155:1672", payTo: payToAddress, }, description: "Paid data endpoint", mimeType: "application/json", }, // Low-cost endpoint: $0.005 "GET /api/info": { accepts: { scheme: "exact", price: "0.005", network: "eip155:1672", payTo: payToAddress, }, description: "Low-cost info endpoint", mimeType: "application/json", }, }, resourceServer ) ); // === Protected Business Endpoints === app.get("/data", (req, res) => { res.json({ message: "Hello, paid user!", timestamp: Date.now() }); }); app.get("/api/info", (req, res) => { res.json({ name: "Pharos x402 Server", network: "Pharos Pacific Mainnet", chainId: 1672, timestamp: Date.now(), }); }); // === Health Check (No Payment Required) === app.get("/health", (req, res) => { res.json({ status: "ok" }); }); // === Start Server === app.listen(port, () => { console.log(`✅ Server started, listening on http://localhost:${port}`); console.log(`📡 Network: Pharos Pacific Mainnet (Chain ID: 1672)`); console.log(`💰 Payment receiver address: ${payToAddress}`); console.log(`🪙 USDC contract: ${usdcAddress}`); }); ``` ### Client-side: Using Fetch + x402 SDK ```ts // Load environment variables import { config } from "dotenv"; config(); // Import required modules import { wrapFetchWithPayment, x402Client, decodePaymentResponseHeader } from "@x402/fetch"; import { ExactEvmScheme } from "@x402/evm/exact/client"; import { privateKeyToAccount } from "viem/accounts"; import fs from "fs"; // === Get EVM private key (prefer environment variable, fall back to .private_key file) === const privateKey = process.env.EVM_PRIVATE_KEY || (fs.existsSync(".private_key") ? fs.readFileSync(".private_key", "utf-8").trim() : null); if (!privateKey) { console.error("❌ Please set the EVM_PRIVATE_KEY environment variable, or create a .private_key file"); process.exit(1); } // === Initialize EVM account and x402 client === const signer = privateKeyToAccount(privateKey as `0x${string}`); const client = new x402Client(); // Register payment scheme for Pharos Pacific Mainnet (Chain ID: 1672) client.register("eip155:1672", new ExactEvmScheme(signer)); // Wrap fetch to enable automatic payments const fetchWithPayment = wrapFetchWithPayment(fetch, client); // === Get target URL (from command-line argument, defaulting to local /data endpoint) === const url = process.argv[2] || "http://localhost:4021/data"; console.log(`📡 Request URL: ${url}`); console.log(`💳 Payer account: ${signer.address}`); // === Make a request with automatic payment === try { const response = await fetchWithPayment(url); const data = await response.json(); console.log("✅ Request succeeded!"); console.log("📦 Response data:", JSON.stringify(data, null, 2)); // If the response includes payment info, decode and print transaction details const paymentResponseHeader = response.headers.get("PAYMENT-RESPONSE"); if (paymentResponseHeader) { const paymentResponse = decodePaymentResponseHeader(paymentResponseHeader); console.log("💰 Transaction hash:", paymentResponse.transaction); console.log("🌐 Network:", paymentResponse.network); console.log("📤 Payer address:", paymentResponse.payer); } } catch (error) { console.error("❌ Request failed:", error); process.exit(1); } ``` ### Facilitator Implementation ```ts import dotenv from "dotenv"; import express from "express"; import { privateKeyToAccount } from "viem/accounts"; import { createWalletClient, http, publicActions, defineChain } from "viem"; import { x402Facilitator } from "@x402/core/facilitator"; import { toFacilitatorEvmSigner } from "@x402/evm"; import { ExactEvmScheme } from "@x402/evm/exact/facilitator"; dotenv.config(); // Check for EVM private key if (!process.env.EVM_PRIVATE_KEY) { console.error("❌ Please set EVM_PRIVATE_KEY"); process.exit(1); } // Define Pharos mainnet (ID: 1672) const pharos = defineChain({ id: 1672, name: "Pharos", nativeCurrency: { name: "PROS", symbol: "PROS", decimals: 18 }, rpcUrls: { default: { http: ["https://rpc.pharos.xyz"] } }, // Pharos RPC endpoint testnet: false, }); // Create wallet client const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`); const client = createWalletClient({ account, chain: pharos, transport: http(undefined, { timeout: 30_000 }), }).extend(publicActions); // Create EVM signer required by the Facilitator const signer = toFacilitatorEvmSigner({ address: account.address, getCode: (args) => client.getCode(args), readContract: (args) => client.readContract({ ...args, args: args.args || [] }), verifyTypedData: (args) => client.verifyTypedData(args as any), writeContract: (args) => client.writeContract({ ...args, args: args.args || [] }), sendTransaction: (args) => client.sendTransaction(args), waitForTransactionReceipt: (args) => client.waitForTransactionReceipt(args), }); // Initialize Facilitator and register Pharos chain const facilitator = new x402Facilitator(); facilitator.register("eip155:1672", new ExactEvmScheme(signer, { deployERC4337WithEIP6492: true })); // Create Express app const app = express(); app.use(express.json()); // Verify payment app.post("/verify", async (req, res) => { try { const { paymentPayload, paymentRequirements } = req.body; const result = await facilitator.verify(paymentPayload, paymentRequirements); res.json(result); } catch (e) { res.status(500).json({ error: (e as Error).message }); } }); // Settle payment on-chain app.post("/settle", async (req, res) => { try { const { paymentPayload, paymentRequirements } = req.body; const result = await facilitator.settle(paymentPayload, paymentRequirements); res.json(result); } catch (e) { res.status(500).json({ error: (e as Error).message }); } }); // Return supported payment schemes app.get("/supported", (req, res) => { res.json(facilitato
프로젝트로 돌아가기