### One-Click RPC Node Setup Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/node-providers Use this script to quickly set up an RPC node with Flashblocks enabled. Ensure Docker and Docker Compose are installed and you have access to a Flashblocks WebSocket endpoint. ```shell mkdir -p /data/xlayer-mainnet && cd /data/xlayer-mainnet curl -fsSL https://raw.githubusercontent.com/okx/xlayer-toolkit/main/rpc-setup/one-click-setup.sh -o one-click-setup.sh chmod +x one-click-setup.sh ./one-click-setup.sh --rpc_type=reth ``` -------------------------------- ### Install Go SDK for SHA3 Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/build-on-xlayer/address-format Install the Go SDK for SHA3 hashing. This is a prerequisite for address formatting. ```bash go get golang.org/x/crypto/sha3 ``` -------------------------------- ### Install and Connect to WSS Server Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/websockets-endpoints/websocket-endpoints Install the 'ws' tool and connect to the XLayer WSS server. This is useful for establishing real-time communication with the network. ```shell # install wss tools go install github.com/hashrocket/ws@latest # connect to the wss server ws wss://xlayertestws.okx.com ``` -------------------------------- ### Install Foundry Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-foundry Installs Foundry using a curl command. Ensure Node.js and Git are installed beforehand. ```shell curl -L https://foundry.paradigm.xyz | bash ``` -------------------------------- ### Install Hardhat Explorer Verify Plugin Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/verify-a-smart-contract/verify-with-hardhat Install the recommended Hardhat plugin for contract verification on OKLink. ```bash npm install @okxweb3/hardhat-explorer-verify ``` -------------------------------- ### Install Truffle Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-truffle Install the Truffle development framework globally using npm. This command is typically run once to set up the tool for your system. ```shell npm install -g truffle ``` -------------------------------- ### Fully Automatic X Layer RPC Node Setup Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/setup-rpc/setup-rpc Deploys a mainnet reth node with snapshot sync and default ports automatically. No user input is required after execution. ```bash curl -sSf https://raw.githubusercontent.com/okx/xlayer-toolkit/main/rpc-setup/one-click-setup.sh | bash ``` -------------------------------- ### Counter Smart Contract Example Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-foundry A basic Solidity smart contract named 'Counter' with functions to set and increment a number. ```solidity // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; contract Counter { uint256 public number; function setNumber(uint256 newNumber) public { number = newNumber; } function increment() public { number++; } } ``` -------------------------------- ### Python SDK: Address Conversion and Error Handling Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/build-on-xlayer/address-format Shows how to convert between XKO and standard EVM addresses using the Python SDK. Includes examples of successful conversions and error handling for invalid inputs. ```python from multi_address import to_evm_address, from_evm_address # XKO to EVM evm_addr = to_evm_address('XKO70586beeb7b7aa2e7966df9c8493c6cbfd75c625') print(evm_addr) # Output: 0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 # EVM to XKO xko_addr = from_evm_address('0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625') print(xko_addr) # Output: XKO70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 ``` ```python # Error handling try: to_evm_address('invalid') except ValueError as e: print(e) # Output: Invalid address length: expected 40 hex chars, got 7 ``` -------------------------------- ### Address Equivalence Examples Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/build-on-xlayer/address-format Demonstrates the equivalence between standard EVM and XKO addresses, including valid and invalid formats. Case-insensitivity of the XKO prefix is also shown. ```plaintext Standard EVM: 0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 XKO address: XKO70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 xko70586beeb7b7aa2e7966df9c8493c6cbfd75c625 ✓ Valid Xko70586beeb7b7aa2e7966df9c8493c6cbfd75c625 ✓ Valid ``` ```plaintext XKO0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 ✗ Cannot have both XKO and 0x ``` -------------------------------- ### Truffle Contract Deployment Output Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-truffle This is an example of the output you will see after successfully deploying a contract. Note that your specific details like transaction hash and contract address will differ. ```shell 1_initial_migration.js ====================== Deploying 'Migrations' ---------------------- > transaction hash: 0xaf4502198400bde2148eb4274b08d727a17080b685cd2dcd4aee13d8eb954adc > Blocks: 3 Seconds: 9 > contract address: 0x81eCD10b61978D9160428943a0c0Fb31a5460466 > block number: 3223948 > block timestamp: 1604049862 > account: 0x623ac9f6E62A8134bBD5Dc96D9B8b29b4B60e45F > balance: 6.24574114 > gas used: 191943 (0x2edc7) > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.00383886 ETH Pausing for 5 confirmations... ------------------------------ > confirmation number: 2 (block: 3223952) > confirmation number: 3 (block: 3223953) > confirmation number: 4 (block: 3223954) > confirmation number: 6 (block: 3223956) > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00383886 ETH Summary ======= > Total deployments: 1 > Final cost: 0.00383886 ETH ``` -------------------------------- ### Get Contract Bytecode with Pending State Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview Fetch the contract bytecode deployed at a specific address, querying the pending state with the 'pending' tag. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getCode","params":["0x...","pending"],"id":1}' ``` -------------------------------- ### Check Smart Contract Verification Status with Foundry Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/verify-a-smart-contract/verify-with-foundry After verification, use this command to check the status. It requires the chain ID, the OKLink verifier URL, and the verification GUID. The `--watch` flag can be used with `verify-contract` for real-time polling. ```bash forge verify-check --chain 11155111 --verifier oklink --verifier-url https://www.oklink.com/api/v5/explorer/contract/verify-source-code-plugin/{chainShortName} ``` -------------------------------- ### Create and Initialize Truffle Project Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-truffle Create a new directory for your project and then initialize a new Truffle project within that directory. This sets up the standard project structure. ```shell mkdir MegaCoin cd MegaCoin truffle init ``` -------------------------------- ### Initialize Foundry Project Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-foundry Initializes a new Foundry project named 'hello_contract' and navigates into the project directory. ```shell forge init hello_contract cd hello_contract ``` -------------------------------- ### Get Raw Transaction by Hash Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview Fetches the raw, RLP-encoded transaction data for a given transaction hash. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getRawTransactionByHash","params":["0x..."],"id":1}' ``` -------------------------------- ### Get Block Transaction Count by Hash Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview Returns the number of transactions within a block identified by its hash. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getBlockTransactionCountByHash","params":["0x..."],"id":1}' ``` -------------------------------- ### Get Block Receipts Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview Retrieves transaction receipts for a specified block. Use 'pending' for pending blocks. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getBlockReceipts","params":["pending"],"id":1}' ``` -------------------------------- ### Initialize Hardhat Project Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-hardhat Run this command in your project folder to create a new Hardhat project. It prompts you to choose between JavaScript or TypeScript projects, or an empty configuration file. ```shell npx hardhat ``` -------------------------------- ### Get Transaction by Block Hash and Index Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview Retrieves transaction details using the block hash and the transaction's index within that block. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getTransactionByBlockHashAndIndex","params":["0x...","0x0"],"id":1}' ``` -------------------------------- ### Configure Hardhat with Explorer Verify Plugin Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/verify-a-smart-contract/verify-with-hardhat Configure your `hardhat.config.js` or `hardhat.config.ts` to use the `@okxweb3/hardhat-explorer-verify` plugin. Ensure network details and API keys are correctly set. ```typescript import { HardhatUserConfig, } from "hardhat/config"; import "@nomicfoundation/hardhat-toolbox"; import '@okxweb3/hardhat-explorer-verify'; // Import the plugin const config: HardhatUserConfig = { solidity: "0.8.20", sourcify: { enabled: true, }, networks: { xlayer: { url: "https://xlayerrpc.example.com", accounts: [""], }, }, etherscan: { apiKey: '...' }, okxweb3explorer: { apiKey: "", } }; export default config; ``` -------------------------------- ### Get Block Transaction Count by Number Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview Returns the total number of transactions for a given block number. Use 'pending' for pending blocks. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getBlockTransactionCountByNumber","params":["pending"],"id":1}' ``` -------------------------------- ### Go: Convert XKO to EVM and EVM to XKO Addresses Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/build-on-xlayer/address-format Use the Go SDK to convert between XKO and EVM address formats. Ensure correct module path for 'your-module/multi_address'. ```go package main import ( "fmt" "log" address "your-module/multi_address" ) func main() { // XKO to EVM evmAddr, err := address.ToEvmAddress("XKO70586beeb7b7aa2e7966df9c8493c6cbfd75c625") if err != nil { log.Fatal(err) } fmt.Println(evmAddr) // Output: 0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 // EVM to XKO xkoAddr, err := address.FromEvmAddress("0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625") if err != nil { log.Fatal(err) } fmt.Println(xkoAddr) // Output: XKO70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 } ``` -------------------------------- ### Get Block by Hash with Flashblocks Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview Retrieve a block using its hash. Note that flashblocks and canonical blocks share the same number but may have different hashes. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getBlockByHash","params":["0x...",true],"id":1}' ``` -------------------------------- ### Download Mainnet Geth Snapshot Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/setup-rpc/snapshots Use this command to download the latest mainnet snapshot for the Geth client. Ensure you have sufficient disk space and a stable internet connection. ```bash wget https://static.okx.com/cdn/chain/xlayer/snapshot/$(curl -s https://static.okx.com/cdn/chain/xlayer/snapshot/geth-mainnet-latest) ``` -------------------------------- ### Flashblocks Diff Response Example Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/node-providers This JSON structure represents an incremental Flashblocks message, containing only transaction diffs. It is used when the index is greater than 0. ```json { "diff": { "blob_gas_used": "0x0", "block_hash": "0x...", "gas_used": "0xbe6b", "logs_bloom": "0x...", "receipts_root": "0x...", "state_root": "0x...", "transactions": [], "withdrawals": [], "withdrawals_root": "0x..." }, "index": 1, "metadata": { "block_number": 8595627, "new_account_balances": { "0x0000f90827f1c53a10cb7a02335b175320002935": "0x0" }, "receipts": { "0x30130a020af408787a9388dcf0272635fff7bc15ae118edb76d207391bb57b51": { "Legacy": {} } } }, "payload_id": "0x03307607ad2ba79d" } ``` -------------------------------- ### Create Viem Wallet Client with Data Suffix Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/builder-codes/integration Create a Viem wallet client and configure it with the `dataSuffix` option using your Builder Code. This ensures all transactions sent from this client are automatically attributed. ```typescript // client.ts import { createWalletClient, custom } from "viem"; import { Attribution } from "ox/erc8021"; import { xlayer } from "./chain"; const DATA_SUFFIX = Attribution.toDataSuffix({ codes: ["YOUR-BUILDER-CODE"], }); if (!window.ethereum) { throw new Error("No injected wallet found"); } export const walletClient = createWalletClient({ chain: xlayer, transport: custom(window.ethereum), dataSuffix: DATA_SUFFIX, }); ``` -------------------------------- ### Verify Contract using Hardhat Explorer Plugin Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/verify-a-smart-contract/verify-with-hardhat Run this command after deploying your contracts to verify them on the OKX Chain explorer using the Hardhat plugin. ```bash npx hardhat okverify --network xlayer ``` -------------------------------- ### Live Test: eth_getBalance via Flashblocks RPC Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/node-providers Perform a live test by querying the `eth_getBalance` method on the public X Layer Flashblocks RPC endpoint. Replace the address placeholder with a valid address. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x...","pending"],"id":1}' ``` -------------------------------- ### Get Storage Value at Position with Pending State Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview Retrieve the storage value at a specific position for a given address, querying the pending state using the 'pending' tag. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getStorageAt","params":["0x...","0x0","pending"],"id":1}' ``` -------------------------------- ### Send Transaction with Viem on X Layer Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview This snippet demonstrates how to send a transaction using Viem on the X Layer network. It includes setting up the chain configuration, wallet client, and public client, then sending and confirming a transaction. ```javascript import { createWalletClient, createPublicClient, http, defineChain } from 'viem'; import { privateKeyToAccount } from 'viem/accounts'; import dotenv from 'dotenv'; dotenv.config(); // TODO: create PR to viem const xlayerPreconf = defineChain({ id: 195, name: 'X Layer Preconf', nativeCurrency: { name: 'OKB', symbol: 'OKB', decimals: 18 }, rpcUrls: { default: { http: ['https://rpc.xlayer.tech/flashblocks'] }, }, blockExplorers: { default: { name: 'Explorer', url: 'https://www.oklink.com/xlayer-test' }, }, testnet: true, }); const account = privateKeyToAccount(process.env.PRIVATE_KEY); const walletClient = createWalletClient({ account, chain: xlayerPreconf, transport: http('https://rpc.xlayer.tech/flashblocks'), }); const publicClient = createPublicClient({ chain: xlayerPreconf, transport: http('https://rpc.xlayer.tech/flashblocks'), }); async function sendTransaction() { try { const submissionTime = new Date(); const hash = await walletClient.sendTransaction({ to: '0x0000000000000000000000000000000000000001', value: BigInt('100000000000000'), }); console.log(`Transaction submitted time: ${submissionTime.toISOString()}`); console.log(`Transaction hash: ${hash}`); let receipt = null; while (!receipt) { try { receipt = await publicClient.getTransactionReceipt({ hash }); } catch (e) { await new Promise(resolve => setTimeout(resolve, 10)); } } const confirmationTime = new Date(); console.log(`Transaction confirmed time: ${confirmationTime.toISOString()}`); console.log(`Time difference: ${confirmationTime.getTime() - submissionTime.getTime()}ms`); } catch (error) { console.error('Error sending transaction:', error); } } sendTransaction(); // node src/ViemExample.js ``` -------------------------------- ### Configure Hardhat for Manual Verification (X Layer Testnet) Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/verify-a-smart-contract/verify-with-hardhat Modify `hardhat.config.js` to include network settings and Etherscan API configurations for X Layer testnet. Replace placeholders with your actual private key and OKLink API key. ```javascript module.exports = { solidity: "0.8.9", networks: { xlayer: { url: "https://testrpc.xlayer.tech/terigon", //or https://rpc.xlayer.tech for mainnet accounts: [process.env.PRIVKEY] } }, etherscan: { apiKey: process.env.ETHERSCAN_KEY, customChains: [ { network: "xlayer", chainId: 195, //196 for mainnet urls: { apiURL: "https://www.oklink.com/api/v5/explorer/contract/verify-source-code-plugin/XLAYER_TESTNET", //or https://www.oklink.com/api/v5/explorer/contract/verify-source-code-plugin/XLAYER for mainnet browserURL: "https://www.oklink.com/xlayer-test" //or https://www.oklink.com/xlayer for mainnet } } ] } }; ``` -------------------------------- ### Get Transaction by Block Number and Index Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview Retrieves transaction details using the block number and the transaction's index within that block. Use 'pending' for pending blocks. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getTransactionByBlockNumberAndIndex","params":["pending","0x0"],"id":1}' ``` -------------------------------- ### Flashblocks Base + Diff Response Example Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/node-providers This JSON structure represents a full Flashblocks message, including base block properties and transaction diffs. It is used when the index is 0. ```json { "base": { "base_fee_per_gas": "0x5f5e0ff", "block_number": "0x8328ab", "extra_data": "0x...", "fee_recipient": "0x...", "gas_limit": "0xbebc200", "parent_beacon_block_root": "0x...", "parent_hash": "0x...", "prev_randao": "0x...", "timestamp": "0x695dd9b6" }, "diff": { "blob_gas_used": "0x0", "block_hash": "0x...", "gas_used": "0x6c63", "logs_bloom": "0x...", "receipts_root": "0x...", "state_root": "0x...", "transactions": [], "withdrawals": [], "withdrawals_root": "0x..." }, "index": 0, "metadata": { "block_number": 8595627, "new_account_balances": { "0x0000f90827f1c53a10cb7a02335b175320002935": "0x0" }, "receipts": { "0x56d542ee662d9a7e1696880346a3f2fb1ed091c15b7c6b607f64ae95e431b097": { "Deposit": {} } } }, "payload_id": "0x03307607ad2ba79d" } ``` -------------------------------- ### Deploy Smart Contract with Forge Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-foundry Deploys the Counter contract from src/Counter.sol. Replace HTTP_URL and PRIVATE_KEY with your actual RPC endpoint and private key. ```bash forge create --rpc-url HTTP_URL \ --private-key PRIVATE_KEY \ src/Counter.sol:Counter ``` -------------------------------- ### Get Block Number (Testnet) Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/rpc-endpoints/rpc-endpoints Use this curl command to retrieve the latest block number from the X Layer testnet RPC endpoint. Ensure you are using the correct testnet URL. ```shell curl -X POST --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' -H "Content-Type: application/json" https://testrpc.xlayer.tech/terigon ``` -------------------------------- ### Compile Smart Contracts with Hardhat Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-hardhat Use this command to compile your Solidity smart contracts. Hardhat will process the contract files and generate the necessary artifacts. ```shell npx hardhat compile ``` -------------------------------- ### Get Block Number (Mainnet) Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/rpc-endpoints/rpc-endpoints Use this curl command to retrieve the latest block number from the X Layer mainnet RPC endpoint. Ensure you are using the correct mainnet URL. ```shell curl -X POST --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' -H "Content-Type: application/json" https://rpc.xlayer.tech ``` -------------------------------- ### Live Test: eth_getTransactionReceipt via Flashblocks RPC Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/node-providers Perform a live test by querying the `eth_getTransactionReceipt` method on the public X Layer Flashblocks RPC endpoint. Replace the transaction hash placeholder with a valid hash. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getTransactionReceipt","params":["0x..."],"id":1}' ``` -------------------------------- ### Get Current Flashblocks Pending Block Height Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/overview Use this command to query the current pending block height from Flashblocks-enabled RPC endpoints. Ensure you are using the 'pending' tag for the query. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":["pending"],"id":1}' ``` -------------------------------- ### Compile Smart Contracts with Truffle Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-truffle Compile your Solidity smart contracts using the Truffle framework. Ensure you are in the root directory of your Truffle project before running this command. ```shell truffle compile ``` -------------------------------- ### Java: Address Conversion and Validation Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/build-on-xlayer/address-format Demonstrates converting between XKO and EVM addresses, checking for Xlayer addresses, and handling invalid address formats using the Java SDK. ```java import com.okcoin.MultiAddress; public class Example { public static void main(String[] args) { // XKO to EVM String evmAddr = MultiAddress.toEvmAddress("XKO70586beeb7b7aa2e7966df9c8493c6cbfd75c625"); System.out.println(evmAddr); // Output: 0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 // EVM to XKO String xkoAddr = MultiAddress.fromEvmAddress("0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625"); System.out.println(xkoAddr); // Output: XKO70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 // Check if XKO address boolean isXko = MultiAddress.isXlayerAddress("XKO70586beeb7b7aa2e7966df9c8493c6cbfd75c625"); System.out.println(isXko); // true boolean isNotXko = MultiAddress.isXlayerAddress("0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625"); System.out.println(isNotXko); // false // Error handling try { MultiAddress.toEvmAddress("invalid"); } catch (IllegalArgumentException e) { System.err.println(e.getMessage()); // Output: Invalid address length: expected 40 hex chars, got 7 } } } ``` -------------------------------- ### Run Deployment Script on X Layer Network Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-hardhat Execute the deployment script using `npx hardhat run` and specify the `--network XLayer` flag to deploy the contract to the X Layer network. ```shell $ npx hardhat run scripts/deploy.js --network XLayer ``` -------------------------------- ### Configure Hardhat for X Layer Network Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-hardhat Set up your `hardhat.config.js` file to include the X Layer network details. This involves specifying the network URL and accounts for deployment. ```javascript module.exports = { defaultNetwork: "hardhat", networks: { hardhat: { }, xlayer: { url: "https://testrpc.xlayer.tech/terigon", accounts: [privateKey1, privateKey2, ...] } } } ``` -------------------------------- ### Verify TransparentUpgradeableProxy Contract Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/verify-a-smart-contract/verify-with-hardhat Use this command to verify TransparentUpgradeableProxy contracts. Specify the contract details and the proxy address. ```bash npx hardhat okxverify --network xlayer --contract : --proxy
``` -------------------------------- ### Live Test: eth_getTransactionCount via Flashblocks RPC Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/node-providers Perform a live test by querying the `eth_getTransactionCount` method on the public X Layer Flashblocks RPC endpoint. Replace the address placeholder with a valid address. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getTransactionCount","params":["0x...","pending"],"id":1}' ``` -------------------------------- ### eth_estimateGas RPC Method Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/node-providers This snippet demonstrates how to estimate gas for a transaction using the eth_estimateGas method via the Flashbots RPC. Provide the correct 'to' and 'data' for accurate estimation. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_estimateGas","params":[{"to":"0x...","data":"0x..."},"pending"],"id":1}' ``` -------------------------------- ### Deploy Contract with Truffle Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-truffle Run this command in the root of your project directory to deploy your contract to the X Layer Chapel Testnet. ```shell $ truffle migrate --network testnet ``` -------------------------------- ### Define X Layer Chains with Viem Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/builder-codes/integration Define the X Layer mainnet and testnet configurations using Viem's `defineChain` function. This allows you to reuse these configurations across your project. ```typescript import { defineChain } from "viem"; // Mainnet export const xlayer = defineChain({ id: 196, name: "X Layer", nativeCurrency: { name: "OKB", symbol: "OKB", decimals: 18 }, rpcUrls: { default: { http: ["https://rpc.xlayer.tech"] }, }, blockExplorers: { default: { name: "OKLink", url: "https://www.oklink.com/xlayer" }, }, }); // Testnet export const xlayerTestnet = defineChain({ id: 1952, name: "X Layer Testnet", nativeCurrency: { name: "OKB", symbol: "OKB", decimals: 18 }, rpcUrls: { default: { http: ["https://testrpc.xlayer.tech"] }, }, blockExplorers: { default: { name: "OKLink", url: "https://www.oklink.com/x-layer-testnet" }, }, }); ``` -------------------------------- ### Live Test: eth_getTransactionByHash via Flashblocks RPC Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/node-providers Perform a live test by querying the `eth_getTransactionByHash` method on the public X Layer Flashblocks RPC endpoint. Replace the transaction hash placeholder with a valid hash. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getTransactionByHash","params":["0x..."],"id":1}' ``` -------------------------------- ### Sample Lock.sol Contract Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/deploy-a-smart-contract/deploy-with-hardhat A basic Solidity contract demonstrating state variables, events, a constructor, and a withdraw function. It includes checks for unlock time and owner. ```solidity // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; // Uncomment this line to use console.log // import "hardhat/console.sol"; contract Lock { uint public unlockTime; address payable public owner; event Withdrawal(uint amount, uint when); constructor(uint _unlockTime) payable { require( block.timestamp < _unlockTime, "Unlock time should be in the future" ); unlockTime = _unlockTime; owner = payable(msg.sender); } function withdraw() public { // Uncomment this line, and the import of "hardhat/console.sol", to print a log in your terminal // console.log("Unlock time is %o and block timestamp is %o", unlockTime, block.timestamp); require(block.timestamp >= unlockTime, "You can't withdraw yet"); require(msg.sender == owner, "You aren't the owner"); emit Withdrawal(address(this).balance, block.timestamp); owner.transfer(address(this).balance); } } ``` -------------------------------- ### Live Test: eth_getBlockByNumber via Flashblocks RPC Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/flashblocks/node-providers Perform a live test by querying the `eth_getBlockByNumber` method on the public X Layer Flashblocks RPC endpoint. Replace placeholders with your actual parameters. ```shell curl https://rpc.xlayer.tech/flashblocks -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["pending",true],"id":1}' ``` -------------------------------- ### Rust: Convert XKO to EVM and EVM to XKO Addresses Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/build-on-xlayer/address-format Use the Rust SDK to convert between XKO and EVM address formats. Handles potential errors during conversion. ```rust use multi_address::{to_evm_address, from_evm_address}; fn main() { // XKO to EVM match to_evm_address("XKO70586beeb7b7aa2e7966df9c8493c6cbfd75c625") { Ok(evm_addr) => println!("{}", evm_addr), // Output: 0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 Err(e) => eprintln!("Error: {}", e), } // EVM to XKO match from_evm_address("0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625") { Ok(xko_addr) => println!("{}", xko_addr), // Output: XKO70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625 Err(e) => eprintln!("Error: {}", e), } } ``` -------------------------------- ### TypeScript SDK: Type-Safe Address Conversion Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/build-on-xlayer/address-format Demonstrates type-safe address conversion between XKO and standard EVM formats using the TypeScript SDK. Shows how TypeScript enforces correct input types. ```typescript import { toEvmAddress, fromEvmAddress } from './multiAddress'; // Type-safe address conversion const evmAddr: string = toEvmAddress('XKO70586beeb7b7aa2e7966df9c8493c6cbfd75c625'); const xkoAddr: string = fromEvmAddress('0x70586BeEB7b7Aa2e7966DF9c8493C6CbFd75C625'); // Type checking toEvmAddress(123); // TypeScript compile error ``` -------------------------------- ### Verify Smart Contract with Foundry and OKLink Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/verify-a-smart-contract/verify-with-foundry Use this command to verify your deployed smart contract. Provide the contract address, contract name or path, and the OKLink verification URL. The `--verifier oklink` flag specifies the verifier service. ```javascript forge verify-contract src/MyToken.sol:MyToken --verifier oklink --verifier-url oklinkverifyUrl ``` -------------------------------- ### Deploy Contract using Hardhat Source: https://web3.okx.com/zh-hans/xlayer/docs/developer/verify-a-smart-contract/verify-with-hardhat Compile and deploy your Hardhat contract to the specified network. This command is used before the verification step. ```javascript hh run scripts/deploy.js --network xlayer ```