### Configure Hardhat for HashKey Chain Testnet Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Developer-QuickStart This snippet demonstrates how to modify the `hardhat.config.ts` file to add the HashKey Chain Testnet network configuration, including its RPC URL, chain ID, and account setup using an environment variable for the private key. ```TypeScript const config: HardhatUserConfig = { networks: { hashkeyTestnet: { url: "https://testnet.hsk.xyz" || "", accounts: process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [], chainId: 133 } } }; ``` -------------------------------- ### Install viem Library Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/KYC Installs the `viem` library, a lightweight Ethereum JavaScript library, required for interacting with the HashKey Chain. This command should be run in a Node.js environment. ```JavaScript npm install viem ``` -------------------------------- ### Set up ethers.js Provider for HashKey Chain Testnet Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Developer-QuickStart This code demonstrates how to initialize an `ethers.js` `JsonRpcProvider` to establish a connection with the HashKey Chain Testnet, using its designated RPC URL for interacting with the blockchain. ```JavaScript import { ethers } from "ethers" const provider = new ethers.providers.JsonRpcProvider("https://testnet.hsk.xyz") ``` -------------------------------- ### Deploy with Foundry to HashKey Chain Testnet Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Developer-QuickStart This command illustrates how to use Foundry's `forge create` command to deploy a smart contract to the HashKey Chain Testnet, specifying the RPC URL and chain ID directly in the command line arguments. ```Shell forge create ... --rpc-url=https://testnet.hsk.xyz --chain-id 133 ``` -------------------------------- ### Configure Truffle for HashKey Chain Testnet Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Developer-QuickStart This snippet shows how to configure the `truffle.js` file to connect to the HashKey Chain Testnet. It uses `HDWalletProvider` to manage the private key and specifies the network ID and RPC URL for deployment. ```JavaScript const HDWalletProvider = require("@truffle/hdwallet-provider") module.exports = { networks: { hashkeyTestnet: { provider: () => new HDWalletProvider(process.env.PRIVATE_KEY, "https://testnet.hsk.xyz"), network_id: 133 } } } ``` -------------------------------- ### Install Graph Protocol Dependencies Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Subgraph Install the necessary Node.js packages for Graph Protocol development, including Graph CLI for command-line operations and Graph TypeScript for type definitions. ```Shell npm install -g @graphprotocol/graph-cli npm install @graphprotocol/graph-ts ``` -------------------------------- ### Oracle Provider Selection Guide Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Oracle A comparative guide to different oracle providers (SUPRA, APRO, Ethereum Global, Chainlink), detailing their update mechanisms, best use cases, and unique features. This table assists developers in selecting the most suitable oracle for their specific application requirements on HashKey Chain. ```APIDOC Oracle Selection Guide: - Provider: SUPRA Update Mechanism: Pull-based Best For: Applications requiring on-demand data Unique Features: High throughput consensus algorithm (DORA) - Provider: APRO Update Mechanism: Push-based Best For: DeFi protocols needing real-time updates Unique Features: Threshold-based updates reducing gas costs - Provider: Ethereum Global Update Mechanism: Verify Proxy Best For: Cross-chain applications Unique Features: Multi-chain compatibility - Provider: Chainlink Update Mechanism: Streams Best For: Mission-critical applications Unique Features: Industry-standard security and reliability ``` -------------------------------- ### HashKey Chain Testnet and Ethereum Sepolia Network Configuration Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Developer-QuickStart This section provides essential network configuration details for both HashKey Chain Testnet and Ethereum Sepolia, including RPC URLs, Chain IDs, Currency Symbols, and Block Explorer URLs, necessary for setting up development tools. ```APIDOC Network Configuration: HashKey Chain Testnet: Network Name: HashKey Chain Testnet RPC URL: https://testnet.hsk.xyz Chain ID: 133 Currency Symbol: HSK Block Explorer URL: https://testnet-explorer.hsk.xyz Ethereum Sepolia: Network Name: Ethereum Sepolia RPC URL: https://rpc2.sepolia.org Chain ID: 11155111 Currency Symbol: ETH Block Explorer URL: https://sepolia.etherscan.io ``` -------------------------------- ### Constructing Block Explorer Links for dApps Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Explorer This example demonstrates how to programmatically construct URLs to specific transactions on BlockScout and contract addresses on OKLink. Developers can use these links to improve user experience and transparency by providing direct access to on-chain data from their dApp UIs. ```javascript // Example: Constructing a link to a transaction on BlockScout const txHash = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"; const blockscoutUrl = `https://explorer.hsk.xyz/tx/${txHash}`; // Example: Constructing a link to a contract on OKLink const contractAddress = "0xabcdef1234567890abcdef1234567890abcdef1234"; const oklinkUrl = `https://www.oklink.com/zh-hans/hashkey/address/${contractAddress}`; ``` -------------------------------- ### Clone HashKey Chain Fullnode Sync Repository Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/RPC-Node-Provider This command clones the `fullnode-sync` repository from GitHub, which contains the necessary files for setting up a HashKey Chain full node. After cloning, it changes the current directory into the newly created `fullnode-sync` directory to prepare for further setup steps. ```Shell git clone https://github.com/HashKeyChain/fullnode-sync cd fullnode-sync ``` -------------------------------- ### Deposit ETH to WETH Contract on Sepolia using Ethers.js Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Faucet This JavaScript example demonstrates how to interact with a Wrapped ETH (WETH) contract on the Sepolia testnet using the Ethers.js library. It shows the process of initializing a contract instance and executing the `deposit()` function to convert native ETH into WETH. The snippet includes error handling and logging for successful transactions. ```JavaScript // Example: Depositing ETH into WETH contract on Sepolia const wethContract = new ethers.Contract( "0x7b79995e5f793a07bc00c21412e50ecae098e7f9", wethAbi, signer ); // Convert 0.1 ETH to WETH const tx = await wethContract.deposit({ value: ethers.utils.parseEther("0.1") }); await tx.wait(); console.log("Successfully wrapped 0.1 ETH to WETH on Sepolia"); ``` -------------------------------- ### Start HashKey Chain Node using Docker Compose Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/RPC-Node-Provider This command initiates the HashKey Chain node services defined in the `docker-compose.yml` file in detached mode (`-d`). It orchestrates the execution and consensus layers, bringing up all necessary containers for the node to run in the background. ```Shell docker compose up -d ``` -------------------------------- ### Retrieve Safe Information using Safe SDK Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Safe This example demonstrates how to connect to the HashKey Chain Mainnet Safe and retrieve Safe details using the Safe SDK. It initializes `SafeApiKit` with the transaction service URL and an `ethAdapter`, then calls `getSafeInfo` to fetch information about a specific Safe address. ```TypeScript // Example: Retrieving Safe information using Safe SDK import { SafeApiKit, SafeFactory } from '@safe-global/api-kit' // Connect to HashKey Chain Mainnet Safe const safeService = new SafeApiKit({ txServiceUrl: 'https://safe-transaction-hashkey.safe.global', ethAdapter: ethAdapter }) // Retrieve Safe details const safeInfo = await safeService.getSafeInfo(safeAddress) ``` -------------------------------- ### Solidity KycDemo Contract Implementation Example Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/KYC Provides a demonstration contract `KycDemo` that interacts with the `IKycSBT` interface. It showcases how to delegate calls to the `IKycSBT` instance for functions like checking a user's human status, retrieving their KYC information, and verifying ENS name approval. ```Solidity contract KycDemo { IKycSBT public kycSBT; constructor(address _kycSBT) { kycSBT = IKycSBT(_kycSBT); } function checkHuman(address account) external view returns (bool isHuman, uint8 level) { return kycSBT.isHuman(account); } function getUserKycInfo(address account) external view returns ( string memory ensName, IKycSBT.KycLevel level, IKycSBT.KycStatus status, uint256 createTime ) { return kycSBT.getKycInfo(account); } function checkEnsNameApproval(address user, string calldata ensName) external view returns (bool) { return kycSBT.isEnsNameApproved(user, ensName); } } ``` -------------------------------- ### Solidity Example for SUPRA Pull Oracle Integration Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Oracle This Solidity smart contract demonstrates how to integrate with the SUPRA Pull Oracle on HashKey Chain. It defines a `SupraConsumer` contract that can query the BTC/USD price and its timestamp from the oracle by calling the `getIndexedPrice` function. ```Solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "./ISupraPullOracle.sol"; contract SupraConsumer { ISupraPullOracle public oracle; constructor(address _oracleAddress) { oracle = ISupraPullOracle(_oracleAddress); } function getBTCPrice() public view returns (uint256, uint256) { // pair_id for BTC/USD = 0 (uint256 price, uint256 timestamp) = oracle.getIndexedPrice(0); return (price, timestamp); } } ``` -------------------------------- ### Query Subgraph Data with GraphQL Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Subgraph Example GraphQL query to retrieve indexed data from the deployed subgraph, filtering and ordering results. ```GraphQL { entities(first: 5, orderBy: timestamp, orderDirection: desc) { id count timestamp } } ``` -------------------------------- ### JavaScript: Get Address Transactions via Explorer API Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Explorer-Wallet Demonstrates how to programmatically retrieve transaction data for a specific blockchain address using the HashKey Chain Explorer's REST API. This asynchronous function sends a GET request to the API endpoint and returns the JSON response containing transaction details. ```JavaScript async function getAddressTransactions(address) { const response = await fetch( `https://explorer.hsk.xyz/api/v2/addresses/${address}/transactions` ); return await response.json(); } ``` -------------------------------- ### NFT Application Categories and Standards Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Ethereum-Applications Details various Non-Fungible Token application categories, their examples, underlying technical standards, and integration points within the blockchain ecosystem. ```APIDOC Category: Digital Art Examples: Unique artworks, collectibles Technical Standards: ERC-721, ERC-1155 Integration Points: IPFS, Layer 2 Solutions ``` ```APIDOC Category: Gaming Assets Examples: In-game items, characters Technical Standards: ERC-1155 multi-token standard Integration Points: Gaming engines, EVM ``` ```APIDOC Category: Virtual Real Estate Examples: Land in metaverse platforms Technical Standards: Custom standards, ERC-721 Integration Points: 3D rendering, spatial interfaces ``` ```APIDOC Category: Tokenized RWAs Examples: Real-world asset representation Technical Standards: ERC-721 with metadata Integration Points: Oracles, legal frameworks ``` -------------------------------- ### Solidity Staking Contract Interaction Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Knowledge/pos Illustrates a simplified conceptual Solidity interface for a staking contract, showing functions for depositing, unstaking, withdrawing, and checking validator stakes. It also includes comments on how a user might interact with such a contract, including ERC20 approval and calling the deposit function. ```Solidity // Very simplified concept - Real staking is much more complex! interface StakingContract { // Function to deposit and stake HSK tokens function depositAndStake(uint256 amount) external payable; // Function to signal intent to withdraw stake (often involves unbonding period) function unstake(uint256 amount) external; // Function for validators to withdraw unlocked stake function withdrawStake() external; // Function to check a validator's stake function getValidatorStake(address validator) external view returns (uint256); } // A user (potential validator) interacts with the staking contract: // Assume 'hskToken' is the ERC20 contract for HSK // Assume 'stakingContractAddress' is the address of the PoS staking contract // 1. Approve the staking contract to spend HSK: // hskToken.approve(stakingContractAddress, stakeAmount); // 2. Call the staking contract to deposit: // StakingContract(stakingContractAddress).depositAndStake{value: msg.value}(stakeAmount); // msg.value if native token staking ``` -------------------------------- ### Web3.js Transaction Gas Estimation Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Gas-Fee-Calculation This JavaScript example demonstrates how to use the `web3.eth.estimateGas` RPC method to predict the gas required for a transaction. It also shows how to add a safety buffer to the estimated gas limit. ```JavaScript const gasEstimate = await web3.eth.estimateGas({ from: myAddress, to: contractAddress, data: contractFunction.encodeABI() }); // Add buffer for safety (e.g., 20%) const gasLimitWithBuffer = Math.floor(gasEstimate * 1.2); ``` -------------------------------- ### Resolve ENS Names and Addresses with ethers.js Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Knowledge/ens This JavaScript example demonstrates how to use the `ethers.js` library to perform both forward ENS resolution (mapping a human-readable name like 'example.eth' to an Ethereum address) and reverse lookup (mapping an Ethereum address back to its associated ENS name). It utilizes the `Web3Provider` for interaction with the Ethereum network. ```JavaScript // ethers.js example const provider = new ethers.providers.Web3Provider(window.ethereum); const address = await provider.resolveName('example.eth'); const name = await provider.lookupAddress('0x123...'); // Reverse lookup ``` -------------------------------- ### Get Total Fee for KYC SBT Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/KYC Asynchronously retrieves the total fee required for KYC verification from the `KycSBT` smart contract. This function uses the `publicClient` to call the `getTotalFee` read-only method. ```TypeScript async function getTotalFee() { const fee = await publicClient.readContract({ address: KYC_SBT_ADDRESS, abi: KycSBTAbi, functionName: 'getTotalFee', }) return fee as bigint } ``` -------------------------------- ### Integrate Chainlink Price Feed in Solidity Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Oracle This Solidity contract shows how to interact with Chainlink's AggregatorV3Interface to fetch the latest price. It takes the verifier proxy address during construction and exposes a public view function to get the current price from the oracle. ```Solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; contract ChainlinkConsumer { AggregatorV3Interface internal priceFeed; constructor(address _verifierProxy) { priceFeed = AggregatorV3Interface(_verifierProxy); } function getLatestPrice() public view returns (int) { ( /* uint80 roundID */, int answer, /* uint startedAt */, /* uint timeStamp */, /* uint80 answeredInRound */ ) = priceFeed.latestRoundData(); return answer; } } ``` -------------------------------- ### Comparison of Ethereum Consensus Mechanisms Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Ethereum-Technology A table comparing different blockchain consensus mechanisms, highlighting their energy usage, throughput, finality, security model, and examples, including Proof of Work (PoW), Proof of Stake (PoS), Delegated PoS (DPoS), and Proof of Authority (PoA). ```APIDOC Mechanism: Proof of Work (PoW) Energy Usage: Very High Throughput: Low (10-15 TPS) Finality: Probabilistic Security Model: Based on computational power Examples: Bitcoin, Ethereum (pre-Merge), Litecoin Mechanism: Proof of Stake (PoS) Energy Usage: Low Throughput: Medium (25-100 TPS) Finality: Faster, deterministic Security Model: Based on economic stake Examples: Ethereum (post-Merge), Cardano, Avalanche Mechanism: Delegated PoS (DPoS) Energy Usage: Low Throughput: High (1000+ TPS) Finality: Near-instant Security Model: Relies on elected block producers Examples: EOS, Tron, BNB Chain Mechanism: Proof of Authority (PoA) Energy Usage: Very Low Throughput: Very High Finality: Instant Security Model: Based on identity of validators Examples: Most testnets, sidechains ``` -------------------------------- ### Solidity Slashing Mechanism Event Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Knowledge/pos Demonstrates a conceptual Solidity contract for a slashing mechanism. It defines an event `ValidatorSlashed` and a `reportMisbehavior` function, which includes logic for verifying evidence, calculating penalties, decreasing validator stake, and emitting the slashing event. ```Solidity // Solidity event that might be emitted by a slashing mechanism contract contract SlashingMechanism { event ValidatorSlashed(address indexed validator, uint256 amountSlashed, bytes reason); function reportMisbehavior(address validator, bytes memory evidence) public { // ... Complex logic to verify evidence ... if (isMalicious(evidence)) { uint256 stakedAmount = getValidatorStake(validator); uint256 penalty = calculatePenalty(stakedAmount, evidence); // ... Logic to burn or redistribute slashed funds ... decreaseValidatorStake(validator, penalty); emit ValidatorSlashed(validator, penalty, evidence); } } // ... other functions ... } ``` -------------------------------- ### Ethereum EVM Operation Gas Costs Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Gas-Fee-Calculation This table lists the gas costs for various common operations within the Ethereum Virtual Machine (EVM), providing examples like arithmetic, storage, and contract calls. These costs are fundamental for understanding transaction execution expenses. ```APIDOC | Operation | Gas Cost | Description | | --- | --- | --- | | `ADD`, `SUB` | 3 | Simple arithmetic | | `MUL`, `DIV` | 5 | More complex arithmetic | | `SSTORE` (0→1) | 20,000 | Storing a new value in state | | `SSTORE` (modify) | 5,000 | Modifying an existing state value | | `CALL` | 700+ | Calling another contract | | `CREATE` | 32,000+ | Creating a new contract | ``` -------------------------------- ### Import viem and Contract Dependencies Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/KYC Imports necessary modules from `viem` for client creation and account management, along with the HashKey Chain testnet configuration and the `KycSBTAbi` for contract interactions. This sets up the basic environment for frontend integration. ```TypeScript import { createPublicClient, createWalletClient, http, type Address, type WalletClient } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { hashkeyTestnet } from 'viem/chains' import { KYC_SBT_ADDRESS } from '@/config/contracts' import KycSBTAbi from '@/abis/KycSBT.json' ``` -------------------------------- ### Deploy Subgraph to Hosted Service Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Subgraph Deploy the prepared subgraph project to the Graph hosted service, making it available for indexing and querying. ```Shell graph deploy --product hosted-service / ``` -------------------------------- ### Initialize New Subgraph Project for HashKey Chain Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Subgraph Initialize a new subgraph project using the Graph CLI, configured for the HashKey Chain network and set up to index events from a specified contract. ```Shell graph init --product hosted-service \ --from-example \ --protocol ethereum \ --network hashkeychain \ --contract-name YourContract \ --index-events ``` -------------------------------- ### HashKey Chain Mainnet Node Configuration (.env) Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/RPC-Node-Provider This configuration template defines the environment variables required for running a HashKey Chain Mainnet node. It specifies Docker images for Geth and Op-Node, the L1 RPC URL and kind, static P2P bootnodes, the rollup configuration URL, and the sequencer HTTP endpoint. Users must replace placeholders like `` with their actual Ethereum mainnet endpoints. ```Shell # geth image GETH_IMAGE=us-docker.pkg.dev/oplabs-tools-artifacts/images/op-geth:v1.101503.3 # l1 rpc url # node image NODE_IMAGE=us-docker.pkg.dev/oplabs-tools-artifacts/images/op-node:v1.13.1 L1_RPC= # l1 rpc kind(standard/basic/quicknode/alchemy/erigon) # https://docs.optimism.io/builders/node-operators/tutorials/node-from-docker L1_RPC_KIND=standard # node libp2p bootnodes P2P_STATIC="/dns/hashkey-mainnet-bootnodes.altlayer.network/tcp/31112/p2p/16Uiu2HAm1UX8Lx4XKnHXncKCw5Q4r6jsajKDEukHk9S9NXuroVKY,/dns/hashkey-mainnet-bootnodes.altlayer.network/tcp/31114/p2p/16Uiu2HAm2PzcWR3pgBkCSUC8Co6WsKHhyyxJysQqzeZpHoX2RaAf,/dns/hashkey-mainnet-bootnodes.altlayer.network/tcp/31116/p2p/16Uiu2HAm6s2pY65dcXi8zM4EfD7oCP4o64C6a8XbxwgLU1q6WAUe,/dns/hashkey-mainnet-bootnodes.altlayer.network/tcp/31118/p2p/16Uiu2HAmQEAZhJTPSdrJpH2NqZ5X368XPXGq68XxL1r8wQamdbwQ" # rollup config file url link ROLLUP_CONFIG_URL="https://operator-public.s3.us-west-2.amazonaws.com/hashkeychain/mainnet/rollup.json" # tx forward endpoint SEQUENCER_HTTP=https://mainnet.hsk.xyz ``` -------------------------------- ### Configure HashKey Chain Network in Wallet Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Explorer-Wallet Instructions and network parameters for adding the HashKey Chain mainnet to a compatible cryptocurrency wallet like MetaMask, enabling interaction with the network. ```Configuration Network Name: HashKey Chain RPC URL: https://hsk-mainnet.hashkey.com Chain ID: 1719 Currency Symbol: HSK Block Explorer URL: https://explorer.hsk.xyz ``` -------------------------------- ### Blockchain Explorer API Access Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Explorer-Wallet Comparison of API access methods provided by HashKey Chain Explorer and OKLink Explorer, detailing the types of APIs available for each platform. ```APIDOC HashKey Chain Explorer: API Access: REST, GraphQL, RPC ``` ```APIDOC OKLink Explorer: API Access: REST API ``` -------------------------------- ### HashKey Chain Explorer API Overview Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Explorer-Wallet Overview of the various API types offered by HashKey Chain Explorer for programmatic access to blockchain data, including REST, GraphQL, and RPC APIs. ```APIDOC HashKey Chain Explorer APIs: - REST API: Description: Basic data retrieval Example Endpoint: GET /api/v2/addresses/{address}/transactions - GraphQL: Description: Complex queries - RPC API: Description: Node-like interaction ``` -------------------------------- ### Configure HashKey Chain Testnet Geth Node Environment Variables Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/RPC-Node-Provider Provides environment variables for setting up a Geth node on the HashKey Chain Testnet. This includes Geth and Node image versions, L1 RPC details, P2P bootnodes, rollup config, sequencer endpoint, Geth bootnodes, genesis file, sync/GC modes, and API endpoints. ```shell # geth image GETH_IMAGE=us-docker.pkg.dev/oplabs-tools-artifacts/images/op-geth:v1.101503.4 # l1 rpc url # node image NODE_IMAGE=us-docker.pkg.dev/oplabs-tools-artifacts/images/op-node:v1.13.2 L1_RPC=https://ethereum-sepolia-rpc.publicnode.com # l1 rpc kind(standard/basic/quicknode/alchemy/erigon) # https://docs.optimism.io/builders/node-operators/tutorials/node-from-docker L1_RPC_KIND=standard # node libp2p bootnodes P2P_STATIC='/dns/testnet-bootnodes.hsk.xyz/tcp/31301/p2p/16Uiu2HAm2tAbwcFYMnXNvVmhacKbE1gz1oMbdrxpUNEUrTBp1fvZ,/dns/testnet-bootnodes.hsk.xyz/tcp/32343/p2p/16Uiu2HAmDKkBkmQNBRe1yXZPtRkJUWmafLgmj6Y84w2AUa3Qgp6N' # rollup config file url link ROLLUP_CONFIG_URL="https://hashkeychain.s3.ap-southeast-1.amazonaws.com/testnet/rollup.json" # tx forward endpoint SEQUENCER_HTTP=https://testnet.hsk.xyz # op-l2 geth bootnodes GETH_STATICNODES='[ "enode://f26759caecdec0ae9d04f523a4ae6a7c562e47f89289f9a520c56f97da9c64cf386441df7f2e992b153a66e8988dcbd3280064db700002e9c14140913004cc52@testnet-bootnodes.hsk.xyz:31289", "enode://72c77ff6d8dac333d283ac2a2522452045bc292d156e4cb4c14d3ef804db77d0c11f7a0bacd507d7eaaa371a7b32cb47369c799620d245630ee137a58d19e893@testnet-bootnodes.hsk.xyz:30109" ]' # genesis file url link GENESIS_URL="https://hashkeychain.s3.ap-southeast-1.amazonaws.com/testnet/genesis.json" # sync mode(full or snap) SYNC_MODE=full # gc mode(archive or full) GC_MODE=archive # geth http api HTTP_API="web3,eth,net,engine" # geth ws api WS_API="web3,eth,net,engine" # plasma enabled(true or false) PLASMA_ENABLED=false # plasma da server url PLASMA_DA_SERVER= # beacon url L1_BEACON="" ``` -------------------------------- ### Configure HashKey Chain Mainnet Geth Node Environment Variables Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/RPC-Node-Provider Defines essential environment variables for setting up a Geth node on the HashKey Chain Mainnet. This includes bootnode lists, genesis file URL, synchronization and garbage collection modes, and HTTP/WS API endpoints. ```shell GETH_STATICNODES='[ "enode://e3d83751cba1f5fd806a73e9701baaa93eb729474eb6c246050e76f9cde32915d4904e1fa12be4196ad7296aba61d4ffebfb7a9c5eeff2b9578e0d7a55cc5ed5@hashkey-mainnet-bootnodes.altlayer.network:31111", "enode://b3714bf5e75760fcbb4de393b75bbcf046be7aa6fb47bd928c4ad6405717a5e67cb01a31dc820ce6b51cfb6c8268ec6c1166fdb2a66f9c92ea67f2fdfdf130fc@hashkey-mainnet-bootnodes.altlayer.network:31113", "enode://6ad0903b679bed251393813042f2452f55ec4e6f120347d412c203072e58bb2e3c1d68247eba25a89b920995bed3b043819d49577a8c1fe4f1c0d762d7d6763a@hashkey-mainnet-bootnodes.altlayer.network:31115", "enode://17162151981152707b855e1e67ab9027dcad7af7a2dbcfa40352c6940f1a977f490b2522986736a8c20327abd5f50afd39f23031b3b103d99c0c03c4449bd172@hashkey-mainnet-bootnodes.altlayer.network:31117", ]' GENESIS_URL="https://operator-public.s3.us-west-2.amazonaws.com/hashkeychain/mainnet/genesis.json" SYNC_MODE=full GC_MODE=archive HTTP_API="web3,eth,net,engine" WS_API="web3,eth,net,engine" ALTDA_ENABLED= ALTDA_DA_SERVER= L1_BEACON= ``` -------------------------------- ### Core DeFi Primitives on Ethereum Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Ethereum-Applications Overview of fundamental Decentralized Finance applications on Ethereum, detailing their purpose, key technologies, and technical implementation, including integration with HashKey Chain. ```APIDOC Application: Decentralized Exchanges (DEXs) Description: Platforms enabling peer-to-peer trading without intermediaries Key Technology: Smart Contracts, Automated Market Makers Technical Implementation: ERC-20 tokens, EVM ``` ```APIDOC Application: Lending Protocols Description: Platforms for borrowing and lending crypto assets Key Technology: Collateralization mechanisms, Interest rate models Technical Implementation: Smart Contracts, Oracles ``` ```APIDOC Application: Yield Aggregators Description: Services optimizing returns across multiple protocols Key Technology: Smart contract composability Technical Implementation: Ethereum Dev Tech ``` ```APIDOC Application: Stablecoins Description: Cryptocurrencies with stable value pegged to fiat Key Technology: Collateralization or algorithmic stability Technical Implementation: ERC-20, DeFi ``` -------------------------------- ### Ethereum Virtual Machine (EVM) Overview Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Ethereum-Technology An explanation of the Ethereum Virtual Machine (EVM), which serves as the runtime environment for smart contracts on the Ethereum blockchain, providing a sandboxed execution context. ```APIDOC The EVM is the runtime environment for smart contracts in Ethereum, providing a sandboxed execution context. ``` -------------------------------- ### Authenticate Graph CLI with Hosted Service Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Subgraph Authenticate your Graph CLI with the hosted service using your access token, enabling deployment of subgraphs. ```Shell graph auth --product hosted-service ``` -------------------------------- ### Initialize Public and Wallet Clients Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/KYC Initializes `publicClient` for read-only operations and `walletClient` for write operations on the HashKey Chain testnet. Both clients are configured with the `hashkeyTestnet` chain and an HTTP transport. ```TypeScript // Public client for read operations const publicClient = createPublicClient({ chain: hashkeyTestnet, transport: http('https://hk-testnet.rpc.alt.technology') }) // Wallet client for write operations const walletClient = createWalletClient({ account, chain: hashkeyTestnet, transport: http('https://hk-testnet.rpc.alt.technology') }) ``` -------------------------------- ### Integrate APRO Price Feed in Solidity Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Oracle This Solidity contract demonstrates how to consume price data from the APROPriceFeed. It initializes with the price feed's address during construction and provides a public view function to retrieve the latest price and its corresponding timestamp. ```Solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@apro/contracts/APROPriceFeed.sol"; contract APROConsumer { APROPriceFeed public priceFeed; constructor(address _priceFeedAddress) { priceFeed = APROPriceFeed(_priceFeedAddress); } function getLatestPrice() public view returns (int256, uint256) { ( /*uint80 roundID*/, int256 price, /*uint startedAt*/, uint256 timestamp, /*uint80 answeredInRound*/ ) = priceFeed.latestRoundData(); return (price, timestamp); } } ``` -------------------------------- ### Configure Subgraph Manifest (subgraph.yaml) Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Subgraph Configure the subgraph manifest file, defining data sources, contract ABIs, event handlers, and the mapping file for processing blockchain events. ```YAML specVersion: 0.0.4 schema: file: ./schema.graphql dataSources: - kind: ethereum name: YourContract network: hashkeychain source: address: "0x..." abi: YourContract startBlock: 1 mapping: kind: ethereum/events apiVersion: 0.0.6 language: wasm/assemblyscript entities: - Entity abis: - name: YourContract file: ./abis/YourContract.json eventHandlers: - event: YourEvent(indexed address,uint256) handler: handleYourEvent file: ./src/mapping.ts ``` -------------------------------- ### Interacting with an L1 Bridge Contract for Asset Deposits Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Knowledge/layer-2 This snippet provides a simplified Solidity interface for an L1 bridge contract, detailing the 'depositERC20' function used to send tokens from L1 to L2 and the 'DepositInitiated' event. It also includes conceptual JavaScript code demonstrating how to approve tokens and call the 'depositERC20' function on the L1 bridge using a library like ethers.js, illustrating the client-side interaction for initiating an L2 deposit. ```Solidity // Highly simplified L1 bridge contract interface (e.g., for depositing to an L2) interface L1Bridge { // User calls this on L1 to send tokens to their address on L2 // The contract locks the L1 tokens and emits an event L2 can listen for function depositERC20( address l1Token, // Address of the token contract on L1 address l2Token, // Address of the corresponding token contract on L2 address recipient, // Who gets the tokens on L2 uint256 amount, bytes calldata data // Optional extra data for L2 message ) external payable; // Payable if depositing native ETH // Event signaling a deposit has occurred for L2 bridge to process event DepositInitiated( address indexed l1Token, address indexed l2Token, address indexed from, address to, uint256 amount, bytes data ); // Withdrawals are usually initiated on L2 and finalized on L1 after a delay/proof // function finalizeWithdrawal(...) external; // Complex process involving L2 state roots/proofs } ``` ```JavaScript // Example Interaction (Conceptual JS using ethers.js or similar) // const l1BridgeContract = new ethers.Contract(L1_BRIDGE_ADDRESS, L1BridgeABI, signer); // const l1TokenContract = new ethers.Contract(L1_TOKEN_ADDRESS, ERC20ABI, signer); // // 1. Approve the bridge to spend L1 tokens // await l1TokenContract.approve(L1_BRIDGE_ADDRESS, depositAmount); // // 2. Call the deposit function on the L1 bridge // await l1BridgeContract.depositERC20( // L1_TOKEN_ADDRESS, // L2_TOKEN_ADDRESS, // The representation of the token on the L2 // USER_ADDRESS, // User's address (often the same on L1/L2) // depositAmount, // '0x' // Empty extra data // ); // The L2 network's bridge component will then detect the DepositInitiated event // and credit the user's account on the L2 side. ``` -------------------------------- ### HashKey Chain Mainnet Connection Details Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/network-info Provides essential network parameters for connecting to the HashKey Chain Mainnet, including Network Name, RPC Endpoint, ChainID, Native Token, and Explorer URL. ```APIDOC Network Name: HashKey Chain RPC Endpiont: https://mainnet.hsk.xyz ChainID: 177 Native Token: HSK Explorer: https://explorer.hsk.xyz ``` -------------------------------- ### Basic ERC-20 Token Implementation in Solidity Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Knowledge/erc20 Provides a foundational Solidity contract demonstrating the implementation of a basic ERC-20 token, including state variables, constructor, and the `balanceOf` and `transfer` functions. ```Solidity contract ERC20Token { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _initialSupply) { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _initialSupply; _balances[msg.sender] = _initialSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { require(_balances[msg.sender] >= amount, "Insufficient balance"); _balances[msg.sender] -= amount; _balances[recipient] += amount; emit Transfer(msg.sender, recipient, amount); return true; } // Additional functions for approve, transferFrom, allowance, etc. } ``` -------------------------------- ### Ethereum Smart Contract Languages Overview Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Ethereum-Technology A table detailing various smart contract languages used on Ethereum, including their features, learning curve, maturity, and best use cases. Languages covered are Solidity, Vyper, Fe, and Yul. ```APIDOC Language: Solidity Features: Static typing, inheritance, libraries Learning Curve: Moderate Maturity: High Best For: Most applications Language: Vyper Features: Python-like, no recursion, bounded loops Learning Curve: Moderate Maturity: Medium Best For: Security-critical contracts Language: Fe Features: Rust-inspired, type safety Learning Curve: Steep Maturity: Low (emerging) Best For: Experimental projects Language: Yul Features: Low-level intermediate language Learning Curve: Very steep Maturity: Medium Best For: Gas optimization ``` -------------------------------- ### HashKey Chain Testnet Connection Details Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/network-info Provides essential network parameters for connecting to the HashKey Chain Testnet, including Network Name, RPC Endpoint, ChainID, Native Token, and Explorer URL. ```APIDOC Network Name: HashKey Chain Testnet RPC Endpiont: https://testnet.hsk.xyz ChainID: 133 Native Token: HSK Explorer: https://testnet-explorer.hsk.xyz ``` -------------------------------- ### APRO Oracle Price Feed Details Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Oracle This section details the APRO price feeds available on HashKey Testnet and Mainnet, including currency pairs, configurable deviation thresholds, heartbeat intervals, and their respective contract addresses for real-time data delivery. ```APIDOC HashKey Testnet Price Feeds: | Pair | Deviation | Heartbeat | Contract Address | |----------|-----------|-----------|------------------------------------------| | BTC/USD | 0.5% | 4h | `0x64697A6Abb508079687465FA9EF99D2Da955D791` | | USDT/USD | 0.5% | 4h | `0xC45D520D18A465Ec23eE99A58Dc4cB96b357E744` | | USDC/USD | 0.1% | 24h | `0xCdB10dC9dB30B6ef2a63aB4460263655808fAE27` | HashKey Mainnet Price Feeds: | Pair | Deviation | Heartbeat | Contract Address | |----------|-----------|-----------|------------------------------------------| | BTC/USD | 0.5% | 1h | `0x204ED500ab56A2E19B051561258E3A45c850360F` | | HSK/USD | 0.5% | 1h | `0x86CE42c1b714149Dc3A7b169EF67b5F78A224b` | | USDT/USD | 0.1% | 24h | `0x823d7f90f7A3498DB6595886b6B5dC95E6B0B7f3` | | USDC/USD | 0.1% | 24h | `0x244Ce344df8837c9d938867E2Ffbf0E4B0169B56` | ``` -------------------------------- ### Ethereum Smart Contract Development Frameworks Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Ethereum-Technology A list of popular development frameworks for Ethereum smart contracts, outlining their key features and benefits. This includes Hardhat, Foundry, and Truffle, which aid in testing, deployment, and task automation. ```APIDOC Framework: Hardhat Description: JavaScript-based development environment Features: Built-in testing, deployment, and task automation; Extensive plugin ecosystem Framework: Foundry Description: Rust-based, fast testing framework Features: Built-in fuzzing capabilities; Direct use of Solidity for tests Framework: Truffle Description: Pioneering development suite Features: Integrated testing, asset pipeline; Mature ecosystem and documentation ``` -------------------------------- ### Monitor HashKey Chain Node Logs Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/RPC-Node-Provider This command displays the real-time logs from the Docker Compose services, allowing you to monitor the node's activity, synchronization progress, and any potential errors. The `-f` flag ensures that the logs are streamed continuously to the console. ```Shell docker compose logs -f ``` -------------------------------- ### HashKey Chain Network Parameters for Wallet Configuration Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/Wallet Details required to manually add HashKey Chain to EVM-compatible wallets like OKX Wallet, MetaMask, TokenPocket, and ImToken. These parameters define how the wallet connects to the HashKey Chain network. ```APIDOC Network Parameters: Network Name: HashKey Chain RPC URL: https://mainnet.hsk.xyz Chain ID: 177 Currency Symbol: HSK Block Explorer URL: https://explorer.hsk.xyz ``` -------------------------------- ### KYC System Emitted Events Reference Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Build-on-HashKey-Chain/Tools/KYC Lists the various events emitted by the HashKey Chain KYC system. These events provide crucial insights into state changes and actions within the smart contracts, enabling off-chain monitoring, indexing, and building responsive applications. ```APIDOC Events: KycRequested: When a user requests KYC verification KycLevelUpdated: When a user's KYC level is updated KycStatusUpdated: When a user's KYC status changes KycRevoked: When a user's KYC is revoked KycRestored: When a revoked KYC is restored AddressApproved: When an address is approved for a specific KYC level EnsNameApproved: When an ENS name is approved for a user ``` -------------------------------- ### Simulating Blockchain Proof-of-Work Mining in Python Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Knowledge/pow This Python code snippet demonstrates a simplified proof-of-work mining process. It defines a BlockHeader class to encapsulate block metadata and hash calculation. The main loop iteratively increments a nonce, recalculates the block's hash, and checks if the hash meets a predefined difficulty target, simulating the core mechanism of finding a valid block in a blockchain. ```Python import hashlib import time class BlockHeader: def __init__(self, previous_hash, merkle_root, timestamp, difficulty_target): self.previous_hash = previous_hash self.merkle_root = merkle_root self.timestamp = timestamp self.difficulty_target = difficulty_target # A numerical representation of the target self.nonce = 0 def calculate_hash(self): header_string = str(self.previous_hash) + \ str(self.merkle_root) + \ str(self.timestamp) + \ str(self.difficulty_target) + \ str(self.nonce) # In real blockchains, often double-hashed or using specific serialization return hashlib.sha256(header_string.encode()).hexdigest() # --- Simplified Mining Loop --- # Assume previous_hash, merkle_root are available # Target represented conceptually as needing 'n' leading zeros target_prefix = "0000" # Example: target needs 4 leading zeros difficulty_target_value = int(target_prefix + "F" * (64 - len(target_prefix)), 16) # Conceptual numeric target block_header = BlockHeader("prev_hash_abc", "merkle_xyz", int(time.time()), difficulty_target_value) start_time = time.time() while True: current_hash = block_header.calculate_hash() # Convert hex hash to integer for comparison hash_value_int = int(current_hash, 16) if hash_value_int < difficulty_target_value: # Check if hash meets the target print(f"Found valid hash! Nonce: {block_header.nonce}") print(f"Hash: {current_hash}") print(f"Time taken: {time.time() - start_time:.2f} seconds") # Broadcast the block with this nonce break else: block_header.nonce += 1 # Increment nonce and try again if block_header.nonce % 100000 == 0: # Print progress periodically print(f"Trying nonce {block_header.nonce}...") ``` -------------------------------- ### Legacy Ethereum Transaction Structure and Fee Calculation Source: https://docs.hsk.xyz/docs/About-HashKey-Chain/Learn/Ethereum-More/Gas-Fee-Calculation A simplified representation of the legacy Ethereum transaction structure, showing fields like `nonce`, `gasPrice`, `gasLimit`, `to`, `value`, and `data`. It also includes the basic fee calculation based on `gasUsed` and `gasPrice`. ```Solidity // Legacy transaction structure (simplified) struct LegacyTransaction { uint nonce; uint gasPrice; // User-specified gas price in wei uint gasLimit; // Maximum gas user is willing to pay address to; uint value; bytes data; // v, r, s signature values } // Fee calculation uint transactionFee = gasUsed * gasPrice; ```