├── .DS_Store
├── README.md
├── academy
├── getting-started
│ ├── erc-20-tokens.mdx
│ └── start-learning.mdx
├── learn-solidity
│ ├── contract-size-limit.mdx
│ ├── gas-fees.mdx
│ ├── img
│ │ └── gas-fee-structure.jpg
│ ├── introduction-to-solidity.mdx
│ ├── permanence.mdx
│ ├── stack-limit.mdx
│ └── update-frequency.mdx
└── try-remix
│ ├── features.mdx
│ ├── img
│ ├── artifact-generation.png
│ ├── compiler-guide.png
│ ├── contract-deployed.png
│ ├── deploy-and-run.png
│ ├── editor-pane.png
│ ├── faucet-example.png
│ ├── terminal-output.png
│ └── web3-wallet-transaction.png
│ ├── remix-overview.mdx
│ └── tutorial-guide.mdx
├── developer
├── bridge
│ ├── asset-transfer.mdx
│ ├── bridging-usdc-workflow.mdx
│ ├── flow-of-assets.mdx
│ ├── img
│ │ ├── bridge-asset-l1-l2.jpg
│ │ ├── bridgetoken-transaction-mainnet.png
│ │ ├── bridgetoken-transaction-testnet.png
│ │ ├── l2-interactions-with-zk-circuit.png
│ │ ├── sending-message-across-l1-l2.png
│ │ ├── smart-contract-interactions.png
│ │ └── usdc-workflow.png
│ ├── overview.mdx
│ └── usdc-on-x-layer.mdx
├── build-on-xlayer
│ ├── bridge-to-xlayer.mdx
│ ├── gas-station.mdx
│ ├── quickstart.mdx
│ ├── rpc-endpoints.mdx
│ ├── safe-contracts.mdx
│ ├── websocket-endpoints.mdx
│ └── zkevm-contracts.mdx
├── learn-more
│ ├── img
│ │ ├── consensus-contract-flow.png
│ │ ├── xlayer-architecture.jpg
│ │ ├── zknode-architecture.png
│ │ ├── zkprover-control-flow.png
│ │ └── zkvalidium-vs-zkrollup.jpg
│ ├── xlayer-architecture.mdx
│ └── xlayer-protocol
│ │ ├── batch-aggregation.mdx
│ │ ├── batch-sequencing.mdx
│ │ ├── img
│ │ ├── batch-data-flow.png
│ │ ├── batch-hashes.png
│ │ ├── consolidated-state-on-l1.png
│ │ ├── fees-and-rewards.jpg
│ │ ├── l2-state-stages.png
│ │ ├── off-chain-execution-of-batches.png
│ │ ├── sequence-of-batches.png
│ │ └── transactions-and-data-flow.png
│ │ ├── incentive-model.mdx
│ │ ├── state-management.mdx
│ │ ├── transaction-validation.mdx
│ │ ├── transactions-batching.mdx
│ │ ├── transactions-n-data-flow.mdx
│ │ └── transactions.mdx
├── oracle
│ ├── best-practices.mdx
│ ├── direct-funding-method.mdx
│ ├── feed-registry.mdx
│ ├── offchain-aggregator.mdx
│ ├── price-feed-interface.mdx
│ ├── price-feed.mdx
│ ├── security-considerations.mdx
│ ├── subscription-method.mdx
│ └── vrf.mdx
├── setup-zknode
│ ├── setup-local-zknode.mdx
│ └── setup-production-zknode.mdx
└── smart-contract
│ ├── .DS_Store
│ ├── deploy-with-foundry.mdx
│ ├── deploy-with-hardhat.mdx
│ ├── deploy-with-truffle.mdx
│ ├── deploying-contract.mdx
│ ├── img
│ ├── complete-verification.png
│ ├── enable-optimization.png
│ ├── manually-verify-hardhat-2.png
│ ├── manually-verify-hardhat.png
│ ├── select-singlefile.png
│ ├── verified-hardhat-2.png
│ ├── verify-the-contract.png
│ ├── verify-with-hardhat-1.png
│ └── verify-with-okxplugin.png
│ ├── manual-verification.mdx
│ ├── verify-with-foundry.mdx
│ ├── verify-with-hardhat.mdx
│ └── verifying-contract.mdx
├── getting-started
├── .DS_Store
├── user-guide
│ ├── .DS_Store
│ ├── bridge-mainnet.mdx
│ ├── bridge-testnet-okb-from-goerli-to-xlayer.mdx
│ ├── bridge.mdx
│ ├── faucet.mdx
│ ├── get-testnet-okb-from-faucet.mdx
│ ├── img
│ │ ├── .DS_Store
│ │ ├── add-network.png
│ │ ├── approve-xlayer-testnet.png
│ │ ├── bridge-mainnet-guide-1.png
│ │ ├── bridge-mainnet-guide-10.png
│ │ ├── bridge-mainnet-guide-11.png
│ │ ├── bridge-mainnet-guide-12.png
│ │ ├── bridge-mainnet-guide-13.png
│ │ ├── bridge-mainnet-guide-14.png
│ │ ├── bridge-mainnet-guide-15.png
│ │ ├── bridge-mainnet-guide-16.png
│ │ ├── bridge-mainnet-guide-17.png
│ │ ├── bridge-mainnet-guide-2.png
│ │ ├── bridge-mainnet-guide-3.png
│ │ ├── bridge-mainnet-guide-4.png
│ │ ├── bridge-mainnet-guide-5.png
│ │ ├── bridge-mainnet-guide-6.png
│ │ ├── bridge-mainnet-guide-7.png
│ │ ├── bridge-mainnet-guide-8.png
│ │ ├── bridge-mainnet-guide-9.png
│ │ ├── chainlist-add-to-metamask.png
│ │ ├── choose-networks.png
│ │ ├── claim-okb.png
│ │ ├── claim-sepolia-eth.png
│ │ ├── clear-activity.png
│ │ ├── complete-slider-verification.png
│ │ ├── connect-wallet-xlayer-bridge-to-sepolia.png
│ │ ├── connect-wallet-xlayer-bridge.png
│ │ ├── erc20-mainnet-guide-1.png
│ │ ├── erc20-mainnet-guide-2.png
│ │ ├── erc20-mainnet-guide-3.png
│ │ ├── erc20-mainnet-guide-4.png
│ │ ├── erc20-mainnet-guide-5.png
│ │ ├── erc20-mainnet-guide-6.png
│ │ ├── erc20-mainnet-guide-7.png
│ │ ├── get-okb-in-sepolia.png
│ │ ├── get-okb-on-xlayer.png
│ │ ├── input-network-info.png
│ │ ├── metamask-settings.png
│ │ ├── metamask-wallet.png
│ │ ├── mint-succeed.png
│ │ ├── mint-test-token.png
│ │ ├── network-list.png
│ │ ├── okb-transferred.png
│ │ ├── okx-wallet-reset.png
│ │ ├── okx-wallet-setting.png
│ │ ├── okxwallet-all-network.png
│ │ ├── okxwallet-xlayer-testnet.png
│ │ ├── particle-wallet-network.png
│ │ ├── particle-wallet-xlayer.png
│ │ ├── setting.png
│ │ ├── transaction-confirm-popup-to-sepolia.png
│ │ ├── transaction-confirm-popup.png
│ │ ├── xlayer-bridge-claim-to-sepolia.png
│ │ ├── xlayer-bridge-confirm-transaction-to-sepolia.png
│ │ ├── xlayer-bridge-confirm-transaction.png
│ │ ├── xlayer-bridge-input-amount-to-sepolia.png
│ │ ├── xlayer-bridge-input-amount.png
│ │ ├── xlayer-bridge-pending-transaction-to-sepolia.png
│ │ ├── xlayer-bridge-pending-transaction.png
│ │ ├── xlayer-bridge-to-sepolia.png
│ │ └── xlayer-bridge.png
│ ├── network-information.mdx
│ ├── set-up-wallets.mdx
│ └── x1-docs.code-workspace
└── welcome
│ ├── introduction.mdx
│ └── welcome-to-xlayer.mdx
├── media-kit
├── .DS_Store
└── XLayer-logo-kit.zip
├── tools
├── .DS_Store
├── account-abstraction.md
├── block-explorers.mdx
├── cross-chain.mdx
├── data-indexers.mdx
├── dev-tooling.mdx
├── node-providers.mdx
├── oracles.mdx
└── user-onboarding.mdx
└── xlayer-docs.js
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/.DS_Store
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Welcome to X Layer
2 | X Layer is a ZK layer 2 network powered by the OKB token and built using Polygon CDK, that offers 100% EVM compatibility, exceptional performance, low fees, and robust security — achieved with seamless integration.
3 |
4 | X Layer aims to connect the OKX and Ethereum communities to allow anyone to take part in a truly global onchian ecosystem.
5 |
6 | In this documentations, you will be guided through 3 main sections:
7 | - **[Getting Started](https://www.okx.com/xlayer/docs/getting-started/welcome/welcome-to-xlayer "Getting Started")**: introduction and user guide of X Layer
8 | - **[Developer](https://www.okx.com/xlayer/docs/developer/build-on-xlayer/quickstart "Developer")**: guide to build on X Layer and our product(s)
9 |
--------------------------------------------------------------------------------
/academy/getting-started/erc-20-tokens.mdx:
--------------------------------------------------------------------------------
1 |
2 | # What are ERC-20 tokens?
3 |
4 | The term ERC stands for Ethereum Request for Comment, and 20 denotes the proposal identifier number, signifying its prominence in the Ethereum ecosystem.
5 |
6 | [ERC-20](https://eips.ethereum.org/EIPS/eip-20) tokens are crucial components in the realm of Web3 development, representing a standardized approach to token implementation on the Ethereum blockchain network. These tokens adhere to a set of rules outlined in the ERC-20 standard, offering a consistent framework for creating and interacting with blockchain-based assets.
7 |
8 | Unlike previous token implementations that lacked uniformity, ERC-20 tokens follow a structured set of guidelines, streamlining their integration into various applications, wallets, and exchange platforms.
9 |
10 | This standardization has revolutionized the development landscape by eliminating the need for developers to comprehend the intricacies of each unique token’s smart contract code. With ERC-20, creating and integrating tokens becomes more efficient, promoting seamless interactions and interoperability among diverse decentralized applications within the Web3 ecosystem.
11 |
12 | ## ERC-20 Features
13 |
14 | 1. **Standardization**: ERC-20 tokens adhere to a set of standardized rules and specifications, ensuring consistency in their implementation across the Ethereum blockchain. This standardization promotes interoperability and ease of integration with various platforms.
15 |
16 | 2. **Transferring and Receiving:** ERC-20 tokens can be easily sent and received between addresses on the Ethereum blockchain. The standard includes functions like `transfer` and `transferFrom` to facilitate these transactions.
17 |
18 | 3. **Total Supply and Balance Inquiry**: ERC-20 tokens provide methods to check the total supply of tokens in circulation (`totalSupply`) and to query the balance of tokens held by a specific address (`balanceOf`).
19 |
20 | 4. **Approval Mechanism:** The standard includes functions (`approve`, `allowance`, and `transferFrom`) that allow for a more complex interaction, enabling one address to approve another to spend a certain amount of tokens on its behalf.
21 |
22 | 5. **Events**: ERC-20 tokens utilize events, such as `Transfer` and `Approval`, which are triggered during transactions. These events help external applications or interfaces track token movements and changes in approval status.
23 |
24 |
25 | ## Use Cases of ERC-20 Tokens
26 |
27 | ERC-20 tokens are fundamental building blocks for DeFi applications. Here are some possible use cases:
28 |
29 | 1. **Liquidity Pools:** ERC-20 tokens are often used as assets in decentralized exchanges (DEXs) and liquidity pools, allowing users to trade and provide liquidity for various token pairs.
30 |
31 | 2. **Collateral in Lending Protocols:** Many decentralized lending platforms in DeFi accept ERC-20 tokens as collateral. Users can lock their ERC-20 tokens in smart contracts to borrow other assets.
32 |
33 | 3. **Governance Tokens:** Some DeFi projects issue ERC-20 tokens as governance tokens, allowing holders to participate in the decision-making processes of the protocol.
--------------------------------------------------------------------------------
/academy/getting-started/start-learning.mdx:
--------------------------------------------------------------------------------
1 |
2 | # Getting started
3 |
4 | ## Objectives
5 | At the end of this guide, you should be able to:
6 |
7 | - Explain what a layer 2 blockchain is.
8 | - Learn more about ERC-20 tokens and use cases.
9 | - Explain the rationale behind the utilization of Solidity for crafting smart contracts.
10 | - Provide a summary of the historical development and the rate of evolution of Solidity, highlighting its strengths and weaknesses.
11 | - Deploy an ERC-20 token using Remix.
12 |
13 |
14 | ## Introduction to layer 2 blockchains
15 |
16 | Scalability has been a persistent challenge within layer 1 blockchains, hindering their ability to handle a growing volume of transactions efficiently. As blockchain networks like Ethereum and Bitcoin face limitations in transaction throughput and confirmation times, the need for scaling solutions becomes paramount. Layer 2 blockchains emerge as [scaling solutions](https://ethereum.org/developers/docs/scaling) to address these scalability issues.
17 |
18 | Layer 2 solutions are designed to augment the capabilities of layer 1 blockchains by moving some of the transaction processing off-chain. This enables faster and more cost-effective transactions without compromising the security and decentralization inherent to Layer 1.
19 |
20 | Three prominent layer 2 solutions are Optimistic Rollups and ZK-rollups, and Validiums, each offering unique approaches to enhance scalability.
21 |
22 | - Optimistic Rollups: This approach relies on an optimistic execution of smart contracts, allowing transactions to occur off-chain and later be reconciled on the main blockchain. By assuming most transactions are valid, Optimistic Rollups significantly reduce the computational load and improve overall transaction throughput.
23 |
24 |
25 | - [ZK-Rollups](https://chain.link/education-hub/zero-knowledge-rollup) (Zero-Knowledge Rollups): Employing advanced cryptographic techniques, ZK-rollups ensure the validity of transactions without revealing the specific details. This not only enhances privacy but also provides a scalable solution by compressing transaction data, reducing the burden on Layer 1.
26 |
27 |
28 | - Validiums are scaling solutions that use off-chain data availability and computation designed to improve throughput by processing transactions off the Ethereum mainnet. Like ZK-Rollups (Zero-Knowledge Rollups), validiums publish zero-knowledge proofs to verify off-chain transactions on Ethereum. This prevents invalid state transitions and enhances the security guarantees of a validium chain. Validium distinguishes itself by placing a strong emphasis on privacy and confidentiality, making it a compelling solution for various decentralized applications. An example of such a layer 2 blockchain is [X Layer](https://www.okx.com/xlayer/docs/developer/build-on-xlayer/quickstart).
29 |
30 |
31 |
32 | Learn more about X Layer [here](https://www.okx.com/xlayer/docs/developer/build-on-xlayer/quickstart).
33 |
--------------------------------------------------------------------------------
/academy/learn-solidity/contract-size-limit.mdx:
--------------------------------------------------------------------------------
1 |
2 | # Contract size limit
3 |
4 | Understanding the contract size limit is crucial for Ethereum developers as it directly impacts the deployment and functionality of smart contracts on the blockchain. EIP-170, a pivotal Ethereum Improvement Proposal, set a compiled byte-code size limit of 24 KiB (24,576 B) for Ethereum Smart Contracts. This restriction is significantly smaller than what developers might be accustomed to, and it imposes constraints that necessitate a shift in perspective when designing and deploying contracts.
5 |
6 | This byte-code size limit doesn’t have a precise correlation to the number of lines of Solidity code. Developers find themselves working within the confines of deploying contracts that typically range from 300 to 500 lines of Solidity code. The compact nature of the byte-code limit requires careful consideration of code efficiency and optimization to stay within the prescribed size boundaries.
7 |
8 | To address the challenges posed by this limitation, developers can explore various strategies. One approach involves contracts exposing their functions to be invoked by other contracts, albeit with an associated additional cost. This allows for the creation of a network of contracts designed to collaboratively perform tasks. Additionally, developers can leverage pre-deployed contracts by others, providing a modular and efficient way to reuse code. More advanced solutions, such as EIP-2535, offer further alternatives to navigate and overcome the constraints imposed by the contract size limit. These considerations highlight the importance of strategic coding practices and the exploration of innovative solutions within the Ethereum ecosystem.
--------------------------------------------------------------------------------
/academy/learn-solidity/gas-fees.mdx:
--------------------------------------------------------------------------------
1 |
2 | # Gas fees
3 |
4 | Gas refers to the unit that measures the amount of computational effort required to execute specific operations on the Ethereum network.
5 |
6 | Since each Ethereum transaction requires computational resources to execute, those resources have to be paid for to ensure Ethereum is not vulnerable to spam and cannot get stuck in infinite computational loops. Payment for computation is made in the form of a gas fee.
7 |
8 | The gas fee is **the amount of gas used to do some operation, multiplied by the cost per unit gas**. The fee is paid regardless of whether a transaction succeeds or fails.
9 |
10 | The EVM operates on a unique cost model where initializing a variable requires a minimum of 20,000 gas, changing it costs a minimum of 5,000 gas, and basic arithmetic operations, such as adding two numbers, only cost 3 gas. This means that storage operations are significantly more expensive than computation in terms of gas expenditure.
11 |
12 | Furthermore, the concept of space complexity takes on a critical role. While in traditional programming, storage is relatively inexpensive, in Solidity, storing and manipulating data in storage incurs substantial gas costs. For instance, it is often more economical to repeatedly calculate a value derived from other data than to calculate it once and save it due to the high gas costs associated with storage operations.
13 |
14 | Predictable execution paths are crucial, as each transaction comes with a predetermined gas limit. Failure to accurately estimate and manage gas consumption may result in transaction failures, but users will still be charged for the gas used up until the point of failure. This highlights the importance of careful coding practices to optimize gas efficiency and ensure a cost-effective and reliable user experience in decentralized applications.
15 |
16 | 
17 |
--------------------------------------------------------------------------------
/academy/learn-solidity/img/gas-fee-structure.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/academy/learn-solidity/img/gas-fee-structure.jpg
--------------------------------------------------------------------------------
/academy/learn-solidity/introduction-to-solidity.mdx:
--------------------------------------------------------------------------------
1 | # Introduction to solidity
2 |
3 | Solidity is a programming language specifically designed for developing smart contracts, which are self-executing contracts with the terms of the agreement directly written into code. Solidity, tailored for blockchain platforms like Ethereum, empowers developers to build decentralized applications (DApps) and automate contract execution on the blockchain. Its syntax is similar to that of JavaScript, making it accessible to a wide range of developers. Solidity plays a crucial role in fostering the growth of blockchain-based applications by providing a secure and efficient means of implementing smart contracts on decentralized networks.
--------------------------------------------------------------------------------
/academy/learn-solidity/permanence.mdx:
--------------------------------------------------------------------------------
1 |
2 | # Permanence
3 |
4 | Permanence is a fundamental characteristic of deployed smart contracts within the blockchain ecosystem. Once a smart contract has been deployed, it attains an immutable status, meaning it becomes impervious to any modifications or alterations, even by its original creators. The concept of permanence underscores the irreversible nature of smart contracts on the blockchain; once coded and deployed, they are set in stone, and no party, including the creators, possesses the capability to edit or update them.
5 |
6 | This lack of editability introduces a unique challenge for smart contract developers. If vulnerabilities or issues are identified after deployment, there is no recourse for direct amendments. The only available action is often limited to withdrawing funds, provided the contract incorporates such functionality. This underscores the critical importance of rigorous testing, auditing, and thorough review processes prior to deployment. Developers need to ensure that the smart contract is robust and free from vulnerabilities, as any oversights become permanent and may have significant consequences.
7 |
8 | In light of the permanence inherent in smart contracts, it has become a standard industry practice to subject these contracts to expert audits before deployment. This proactive measure aims to identify and rectify potential vulnerabilities, ensuring that once deployed, smart contracts operate securely and as intended throughout their unalterable existence on the blockchain.
--------------------------------------------------------------------------------
/academy/learn-solidity/stack-limit.mdx:
--------------------------------------------------------------------------------
1 |
2 | # Stack limit
3 |
4 | In the realm of computer programming, especially when dealing with languages like Solidity for the Ethereum Virtual Machine (EVM), understanding the concept of a stack limit is vital. Unlike humans, computers and mobile devices process vast amounts of data simultaneously, manipulating numerous variables within the code. The EVM, which underlies the execution of smart contracts, utilizes a stack capable of holding 1,024 values. However, it can only directly access the top 16 values from the stack.
5 |
6 | This stack limit has significant implications for developers. One common challenge arises in the form of the "Stack too Deep" error, encountered when attempting to manage an excessive number of variables simultaneously. Essentially, the restriction forces developers to be mindful of how many variables are actively processed within their code.
7 |
8 | Specifically, in the context of Solidity and the EVM, functions face a constraint wherein they are limited to a total of 16 variables. These variables can include inputs, outputs, or those initialized by the function itself. Consequently, developers must carefully plan and optimize their code to stay within this variable limit, avoiding runtime errors and ensuring the smooth execution of their smart contracts on the Ethereum blockchain. This constraint emphasizes the importance of efficient coding practices to navigate and adhere to the stack limit imposed by the EVM.
--------------------------------------------------------------------------------
/academy/learn-solidity/update-frequency.mdx:
--------------------------------------------------------------------------------
1 |
2 | # Update frequency
3 |
4 | The dynamic and rapidly evolving nature of Solidity development contributes significantly to the necessity for specifying versions when compiling code. The Solidity language experiences frequent updates, and not all changes are backward-compatible. This rapid pace of development introduces potential incompatibilities between different versions of the language.
5 |
6 | To address this challenge, developers need to explicitly indicate the Solidity version when compiling their code. This ensures that the compiler understands which set of rules and features to apply when converting the Solidity code into bytecode. By specifying the version, developers can mitigate the risk of unintended consequences that may arise from using an incompatible compiler version.
7 |
8 | ```
9 | / / SPDX-License-Identifier: UNLICENSED
10 |
11 | pragma solidity ^0.8.17;
12 | ```
13 | Refer to [changelog](https://github.com/ethereum/solidity/blob/develop/Changelog.md) to review some of the recent updates and fixes.
--------------------------------------------------------------------------------
/academy/try-remix/features.mdx:
--------------------------------------------------------------------------------
1 | # Features
2 |
3 | ## Editor Pane
4 |
5 | The editor pane loads with the Remix home screen, which contains useful guides and warnings about common scams. Double-click on `HelloWorld.sol` to open it in the editor. You also have the option of closing the home tab if you want to.
6 |
7 | 
8 |
9 | You can edit your code under the editor pane, which will consist of features such as syntax and error highlighting. Do note that errors are highlighted with exclaimation marks next to the line number where the error is occurring.
10 |
11 | ## Terminal Output
12 |
13 | The terminal is directly below the editor pane. You can use this terminal panel to observe transaction logs from your smart contract and access the debugging tools in Remix. You also have the option to hide the terminal.
14 |
15 | 
16 |
17 |
18 | ## Left Panel
19 |
20 | The left panel in Remix has multiple vertical tabs. It allows you to switch between tools and functions. You can also create and switch between your workspaces, search your code and access a number of plugins.
21 |
22 | ## Plugins
23 |
24 | Remix primarily relies on plugins, with the most commonly used ones being active from the start. To access and control plugins, simply click the plug button located in the lower-left corner, just above the settings gear. Activation or deactivation of plugins can be easily done by clicking the activate/deactivate option. Certain plugins, like the Debug plugin, are automatically triggered through various sections of the editor.
25 |
26 | ## Compiler
27 |
28 | The initial default plugin, following the search function, is the Solidity Compiler. Make sure to enable the Auto compile option. Since smart contracts are typically small files, enabling this option should not pose any performance issues during code editing.
29 |
30 | The functionality of the **Compile and Run script** button in this plugin may be a bit misleading. It is not the usual method for testing your contract. For more information on this feature, click the **I** button.
31 |
32 | In case there are errors in your contracts, the complete text for each error will be displayed at the bottom of the pane. Experiment with this feature by introducing some typos into the HelloWorld.sol file.
--------------------------------------------------------------------------------
/academy/try-remix/img/artifact-generation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/academy/try-remix/img/artifact-generation.png
--------------------------------------------------------------------------------
/academy/try-remix/img/compiler-guide.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/academy/try-remix/img/compiler-guide.png
--------------------------------------------------------------------------------
/academy/try-remix/img/contract-deployed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/academy/try-remix/img/contract-deployed.png
--------------------------------------------------------------------------------
/academy/try-remix/img/deploy-and-run.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/academy/try-remix/img/deploy-and-run.png
--------------------------------------------------------------------------------
/academy/try-remix/img/editor-pane.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/academy/try-remix/img/editor-pane.png
--------------------------------------------------------------------------------
/academy/try-remix/img/faucet-example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/academy/try-remix/img/faucet-example.png
--------------------------------------------------------------------------------
/academy/try-remix/img/terminal-output.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/academy/try-remix/img/terminal-output.png
--------------------------------------------------------------------------------
/academy/try-remix/img/web3-wallet-transaction.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/academy/try-remix/img/web3-wallet-transaction.png
--------------------------------------------------------------------------------
/academy/try-remix/remix-overview.mdx:
--------------------------------------------------------------------------------
1 | # Overview
2 |
3 | Start by launching a web browser and visiting remix.ethereum.org. Access the project that you previously established and organized during the last session, then proceed to open the file labeled HelloWorld.sol. The layout of the editor should be recognizable, featuring three distinct sections:
4 |
5 | - Editor pane
6 | - Terminal or output
7 | - Left panel
--------------------------------------------------------------------------------
/academy/try-remix/tutorial-guide.mdx:
--------------------------------------------------------------------------------
1 | # How to create and deploy an ERC-20 token
2 |
3 | Now that you understand more about what ERC-20 tokens are, and how Remix is structured, it is time to create and deploy your own ERC-20 token! In this section, you will learn how to create and deploy an ERC-20 token using Remix.IDE!
4 |
5 | ## What you need
6 |
7 | - A Web3 Wallet (e.g OKX wallet or a WalletConnect-compatible wallet)
8 |
9 | - Testnet Ethereum ( You can request some at the [Ethereum Sepolia Facuet](https://www.alchemy.com/faucets/ethereum-sepolia))
10 |
11 | - A Web Browser (e.g., Google Chrome)
12 |
13 |
14 |
15 |
16 | ## Step 1
17 |
18 | Download a Web3 wallet. You can download OKX’s wallet from [here](https://chromewebstore.google.com/detail/okx-wallet/mcohilncbfahbmgdjkbpemcciiolgcge) or read more about installing a Web3 compatible wallet on [our website](https://www.okx.com/oktc/docs/dev/quick-start/wallet/metamask/quick-start#install-a-web3-compatible-wallet).
19 |
20 | ## Step 2
21 |
22 | Once your wallet is set up, you will have to acquire some test ETH from the Ethereum Sepolia Facuet. Simply enter your wallet address and login to Alchemy to a small amount of test ETH.
23 |
24 | 
25 |
26 | ## Step 3
27 |
28 | Open [Remix](https://remix.ethereum.org/) and make a new Solidity file, for instance NewToken.sol.
29 |
30 | ``` sol
31 | // SPDX-License-Identifier: MIT
32 |
33 | pragma solidity ^0.8.20;
34 |
35 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
36 |
37 | contract MyToken is ERC20 {
38 |
39 | constructor() ERC20("MyToken", "MT") {
40 |
41 | _mint(msg.sender, 1000000 * (10 ** uint256(decimals())));
42 |
43 | }
44 |
45 | }
46 | ```
47 | 
48 |
49 | Click on the **Compile** button. Do verify that the compiler’s version is at least **0.8.20** because of the line `pragma solidity ^0.8.20;` in the editor pane. You should see a green tick mark on the **Compile** button! Well done!
50 |
51 | ## Step 3 Code breakdown
52 |
53 | To help you understand the code better, here is a breakdown of the code we have written in **Step 3**!
54 |
55 |
56 | 1. **SPDX-License-Identifier Comment**:
57 |
58 | 1. This comment specifies the license under which the smart contract is released. It helps in identifying the open-source license associated with the code.
59 |
60 | 2. **Pragma Directive**:
61 |
62 | 1. The pragma directive specifies the compiler version to use. It ensures that the code is compiled with a specific version of the compiler to avoid compatibility issues.
63 |
64 | 3. **Importing ERC-20 from OpenZeppelin**:
65 |
66 | 1. The ERC-20 contract from OpenZeppelin is a well-established and widely used implementation of the ERC-20 standard, providing a foundation for creating tokens.
67 |
68 | 4. **Creating MyToken Contract**:
69 |
70 | 1. The `MyToken` contract is being defined and it extends the functionality of the ERC-20 contract. This means it inherits all the functions and features from the ERC-20 contract.
71 |
72 | 5. **Constructor Function**:
73 |
74 | 1. The constructor function is a special function that is executed only once when the contract is deployed. In this case, it initializes the token with a name ("MyToken") and a symbol ("MTK").
75 |
76 | 6. **Minting Initial Supply**:
77 |
78 | 1. The `_mint` function within the constructor is used to mint an initial supply of tokens. In this example, 1 million tokens are created and assigned to the address that deploys the contract.
79 |
80 | 7. **Decimals Adjustment**:
81 |
82 | 1. The number of tokens minted is adjusted by the `decimals` value. The `decimals` value is a standard in ERC-20 contracts and is often set to 18 by default in OpenZeppelin’s implementation.
83 |
84 | 8. You can see the full ERC-20 code on the OpenZeppelin website [here](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol).
85 |
86 |
87 | ## Step 4
88 |
89 | Great! Now click on the **Deploy & Run Transaction** button. For deployment, use the **Injected Provider option under Environment.** Connect to your Web3 wallet and select the Sepolia Test network. Then, click deploy.
90 |
91 | 
92 |
93 | > If you receive an error message before deployment - “This contract may be abstract”, ensure that the correct contract is selected under the Contract tab.
94 |
95 | ## Step 5
96 |
97 | Confirm the transaction in your Web3 wallet. In this case, we are using the OKX wallet.
98 |
99 | 
100 |
101 | Confirm the transaction in your wallet.
102 |
103 | Congratulations! Your contract is now deployed on Ethereum’s Sepolia test network! To see the contract that you have deployed, click on "Deployed Contracts" to see the functions of the contract. You should be able to edit the contract name as well.
104 |
105 | 
106 |
107 |
108 | ## Conclusion:
109 |
110 | Congratulations! You have created your very own token on the Ethereum Sepolia Test network!
111 |
112 | ## Storing and Retrieving a Value
113 |
114 | Utilizing the input to store and retrieve a value incurs a gas cost, and the nuanced aspect lies in the distinction between storing and retrieving.
115 |
116 | Both operations approximately cost 23500 gas. However, there’s an important nuance: the gas cost for the retrieve function is only applicable when it is called by another contract. When called from the web, there is no gas cost because you are merely reading data from the blockchain. In this case, you are not instructing the EVM to perform a computational task, making the retrieval operation free when accessed from the web.
117 |
118 | ## Disabling Artifact Generation
119 |
120 |
121 |
122 | 
123 |
124 | Navigate back to the File Explorer by clicking the double document icon in the upper left corner. You will now observe a folder named "artifacts" that has been included in your project. This folder houses various build artifacts, including the ABI for your contract, which will prove valuable in the future but may currently contribute to clutter.
125 |
126 | To disable this, you can deactivate artifact generation. Click the settings gear in the bottom left corner and then uncheck the first checkbox labeled "Generate contract metadata...".
--------------------------------------------------------------------------------
/developer/bridge/asset-transfer.mdx:
--------------------------------------------------------------------------------
1 | # Asset transfer
2 | This section describes how asset transfers are enabled by three smart contracts.
3 | - Bridge smart contract ([ZkEVMBridge.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/PolygonZkEVMBridgeV2.sol "ZkEVMBridge.sol"))
4 | - Global Exit Root Manager ([ZkEVMGlobalExitRoot.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/PolygonZkEVMGlobalExitRootV2.sol "ZkEVMGlobalExitRoot.sol"))
5 | - Consensus contract ([ZkEVM.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/consensus/validium/PolygonValidiumEtrog.sol "ZkEVM.sol"))
6 |
7 | ## Bridge smart contract
8 | The ZKEVM bridge smart contract (ZkEVMBridge.sol) has two main functions:
9 | - Bridge (or deposit) function
10 | - Claim (or withdrawal) function
11 |
12 | With these functions, we can bridge assets from one network to another, as well as claim assets received in the destination network.
13 | 1. User `Deposit` transfers assets layer 2 -> layer 1 or layer 1 -> layer 2. The bridge smart contract SC adds an exit leaf to the layer 2 exit tree, which holds the relevant transfer data.
14 | 2. Subsequently, the root of the layer 2 exit tree is updated and becomes accessible for the next smart contract in the workflow, known as the Global Exit Root Manager SC.
15 | 3. User `Claim` assets on opposite chain bridge SC.
16 |
17 | There are two bridge smart contracts: one deployed in layer 1, while the other is deployed in layer 2, both using the same ZKEVMBridge.sol code file, but using different parameters for the interaction.
18 |
19 | ## Global exit root manager contract
20 | The Global Exit Root Manager SC, implemented as `ZkEVMGlobalExitRoot.sol`, serves as the overseer of the Global Exit Tree Root. Its primary responsibilities include updating the Global Exit Tree Root and serving as a storage hub for the historical data of the Global Exit Tree.
21 |
22 | This contract has a main function:
23 | - `updateExitRoot`
24 | This separation of logic between the ZKEVM bridge SC and the Global Exit Root Manager SC has been strategically implemented to enhance interoperability, which uses the function `updateExitRoot`.
25 |
26 | This means that the ZKEVM bridge SC, in conjunction with the Global Exit Root Manager SC, can be installed on any network to achieve the same results.
27 |
28 | There are two Global Exit Root manager SCs: one deployed in L1, while the other is deployed in layer 2. Their Solidity code files are; ZkEVMGlobalExitRoot.sol, and ZkEVMGlobalExitRootL2.sol, respectively.
29 |
30 | ## Consensus contract
31 | The `ZkEVM.sol` smart contract is the consensus algorithm used in X Layer. It is located in L1 for batch verification purposes.
32 | The consensus smart contract (ZkEVM.sol) has two main functions:
33 | - `sequenceBatchesValidium`
34 | - `verifyBatchesTrustedAggregator`
35 |
36 | With these functions, layer 2 tx data can be rolled up and verified.
37 | 1. Transactions are grouped into batches by `sequenceBatchesValidium` function.
38 | 2. A request is made to an aggregator to prove the validity of these sequenced batches by `verifyBatchesTrustedAggregator`. This proof is ZK-proof and is verified using the `Verifier.sol` contract.
39 | 3. Following the verification of the ZK-proof, the consensus contract sends the ZKEVM Exit Tree Root to the Global Exit Root Manager SC `ZkEVMGlobalExitRoot.sol` to update the Global Exit Root.
40 |
41 | ## Smart contract interactions
42 | The following diagram illustrates the interactions among the three bridge-related smart contracts when assets are bridged. It describes the overall process of transferring assets from layer 1 to layer 2 and from layer 2 to layer 1 through contracts.
43 |
44 | 
45 |
46 | ### layer 1 → layer 2 transfer
47 | 1. When the user commits to transferring assets, the bridge SC `ZkEVMBridge.sol` uses the Bridge method to append the corresponding exit leaf to the L1 Exit Tree.
48 | 2. The updated root of the L1 Exit Tree is sent to the Global Exit Root Manager `ZkEVMGlobalExitRoot.sol` for an update of the Global Exit Root.
49 | 3. The consensus contract `ZkEVM.sol` retrieves the updated Global Exit Root from the Global Exit Root Manager, which is used for syncing with the ZKEVM as the destination network for bridged assets.
50 |
51 | The transfer from layer 1 to ZKEVM is completed with the `Claim` method of the bridge SC, but this time in the ZKEVM side.
52 |
53 | ### layer 2 → layer 1 transfer
54 | Now the reverse process, while focusing only at the L1 smart contracts.
55 | 1. The consensus contract uses the `sequenceBatchesValidium` function to sequence batches, which includes, among other transactions, asset transfer information.
56 | 2. A special smart contract called `Verify.sol` calls the `VerifyBatches` function and takes batch info as input. As part of the consensus process, but not shown in the above figure, the aggregator produces a validity proof for the sequenced batches. And this proof is automatically verified in this step.
57 | 3. The ZKEVM Exit Tree gets updated only after a successful verification of sequenced batches (again, for the sake of simplicity, this is not reflected in the above figure). The consensus contract (`ZkEVM.sol`) sends the updated ZKEVM Exit Root to the Global Exit Root Manager, which subsequently updates the Global Exit Root.
58 | 4. The ZKEVM bridge SC (`ZkEVMBridge.sol`) then retrieves the updated Global Exit Root and uses the `Claim` function to complete the transfer.
59 |
60 | ### Specific interaction in layer 2
61 | The focus in this subsection is on the bridge-related smart contracts used in layer 2, especially in the ZKEVM.
62 | 1. The bridge SC (`ZkEVMBridge.sol`) in layer 2 is the same smart contract deployed on layer 1.
63 | 2. The L2 Global Exit Root Manager SC is different, and it appears in code as `ZkEVMGlobalExitRootL2.sol`. This is a special contract that allows synchronization of L2 Exit Tree Root and the Global Exit Root.
64 | 3. The L2 Global Exit Root Manager has storage slots to store the Global Exit Root and the L2 Exit Tree Root. In order to correctly ensure validity of the synchronization between the Global Exit Tree and L2 Exit Tree, these storage slots are directly accessible to the low-level ZK-proof-generating circuit.
65 |
66 | Here is the step-by-step process:
67 |
68 | 
69 |
70 | 1. When a batch of transactions is processed, the ZKEVM bridge SC `ZkEVMBridge.sol` appends an exit leaf with the batch information to the L2 Exit Tree and updates the L2 Exit Tree Root.
71 | 2. The bridge SC communicates the L2 Exit Tree Root to the L2 Global Exit Root Manager. The L2 Global Exit Root Manager, however, does not update the Global Exit Tree at this stage.
72 | 3. For proof and verification, the circuit for generating ZK-proofs obtains the L2 Exit Tree root from the L2 Global Exit Root Manager.
73 | 4. Only after the batch has been successfully proved and verified does the L2 Global Exit Root Manager append the L2 Exit Tree Root to the Global Exit Tree. As a result, the Global Exit Root is updated.
74 |
75 | The circuit for generating ZK-proofs also writes the L2 Exit Tree Root to the mainnet. The ZKEVM bridge SC deployed on L1 can then finalize the transfer by using the `Claim` function.
76 |
--------------------------------------------------------------------------------
/developer/bridge/flow-of-assets.mdx:
--------------------------------------------------------------------------------
1 | # Flow of assets
2 | The X Layer bridge is a decentralized bridge that enables users to securely transfer assets between layer 1 and layer 2. Here's how it works:
3 | 1. To bridge an asset from layer 1 to layer 2, the user must lock the asset in layer 1. The **layer 2 bridge smart contract** will then mint a wrapped token in layer 2, representing an equivalent value of the asset. After the minting process is finished, the user or recipient can claim the asset in layer 2.
4 | 2. In the opposite operation, after burning the wrapped token in layer 2, the **layer 1 bridge smart contract** unlocks the original asset in L1.
5 |
6 | 
7 |
8 | Asset transferring is enabled by three smart contracts:
9 | - The bridge smart contract (`ZkEVMBridge.sol`)
10 | - The global exit root manager (`ZkEVMGlobalExitRoot.sol`)
11 | - The consensus contract (`ZkEVM.sol`)
12 |
13 | Please refer to the previous document for more detailed information:
14 |
15 |
16 | ## Flow of assets in X Layer bridge
17 | ### Asset flow from layer 1 → layer 2
18 | 1. The `Bridge` function of the ZKEVM bridge smart contract (`ZkEVMBridge.sol`) on the L1 network is invoked. If the bridge request is valid, the bridge smart contract appends an exit leaf to the L1 exit tree and computes the new L1 exit tree root.
19 | 2. The Global Exit Root Manager (`ZkEVMGlobalExitRoot.sol`) appends the new L1 exit tree root to the global exit tree and computes the global exit root.
20 | 3. The Sequencer fetches the latest global exit root from the global exit root manager.
21 | 4. At the start of the transaction batch, the sequencer stores the global exit root in special storage slots of the layer 2 Global Exit Root Manager smart contract (`ZkEVMGlobalExitRootL2.sol`), allowing L2 users to access it.
22 | 5. In order to complete the bridging process, the user calls the `Claim` function of the bridge smart contract and provides a Merkle proof to demonstrate that the correct exit leaf was included and represented in the Global Exit Root.
23 | 6. The bridge smart contract obtains the layer 2 Global Exit Root Manager smart contract’s global exit root and validates the user’s Merkle proof of inclusion. If the Merkle proof is valid, the bridging process succeeds; otherwise, the transaction fails.
24 |
25 | ### Asset flow from layer 2 → layer 1
26 | 
27 | 1. The user calls the Bridge function of the ZKEVM bridge smart contract (`ZkEVMBridge.sol`) on Layer 2. If the bridge request is valid, the bridge smart contract appends an exit leaf to the L2 Exit Tree and computes the new L2 exit tree root.
28 | 2. The L2 Global Exit Root Manager (`ZkEVMGlobalExitRootL2.sol`) is called to append the new layer 2 exit tree root to the global exit tree and compute the global exit root:
29 | For the sake of simplicity, the intermediate step is not depicted in the figure below. That step is: The user’s bridging transaction gets included in one of the batches selected and sequenced by the sequencer.
30 | 3. The aggregator generates a ZK-proof attesting to the computational integrity in the execution of sequenced batches (where one of these batches includes the user’s bridging transaction).
31 | 4. For verification purposes, the aggregator sends the ZK-proof together with all relevant batch information that leads to the new L2 Exit Tree root (computed in step 2 above), to the consensus contract (`ZkEVM.sol`).
32 | 5. The consensus contract utilizes the `verifyBatches` function to verify validity of the received ZK-proof. If valid, the consensus contract sends the new L2 Exit Tree Root to the Global Exit Root Manager smart contract (`ZkEVMGlobalExitRoot.sol`) in order to update the Global Exit Tree.
33 | 6. In order to complete the bridging process on the L1 network, the user calls the `Claim` function of the bridge smart contract, and provides Merkle proof of the fact that the correct exit leaf was included in the computation of Global Exit Root.
34 | 7. The bridge smart contract retrieves the global exit root from the L1 Global Exit Root Manager smart contract and verifies validity of the Merkle proof. If the Merkle proof is valid, the bridge smart contract successfully completes the bridging process. Otherwise, the transaction is reverted.
35 |
36 | The architecture shown in the diagram below is simplified, emphasizing the connection between different bridge elements.
37 | It doesn't include the interaction between the consensus contract and the sequencer, which is discussed in more detail in earlier subsections of this documentation, particularly in the [consensus contract](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/consensus/validium/PolygonValidiumEtrog.sol "consensus contract") section.
--------------------------------------------------------------------------------
/developer/bridge/img/bridge-asset-l1-l2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/bridge/img/bridge-asset-l1-l2.jpg
--------------------------------------------------------------------------------
/developer/bridge/img/bridgetoken-transaction-mainnet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/bridge/img/bridgetoken-transaction-mainnet.png
--------------------------------------------------------------------------------
/developer/bridge/img/bridgetoken-transaction-testnet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/bridge/img/bridgetoken-transaction-testnet.png
--------------------------------------------------------------------------------
/developer/bridge/img/l2-interactions-with-zk-circuit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/bridge/img/l2-interactions-with-zk-circuit.png
--------------------------------------------------------------------------------
/developer/bridge/img/sending-message-across-l1-l2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/bridge/img/sending-message-across-l1-l2.png
--------------------------------------------------------------------------------
/developer/bridge/img/smart-contract-interactions.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/bridge/img/smart-contract-interactions.png
--------------------------------------------------------------------------------
/developer/bridge/img/usdc-workflow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/bridge/img/usdc-workflow.png
--------------------------------------------------------------------------------
/developer/bridge/overview.mdx:
--------------------------------------------------------------------------------
1 | # X Layer bridge overview
2 | X Layer employs a flexible message bridge, allowing tokens to move and facilitating communication between layer 1 and layer 2 in a seamless manner. This empowers layer 1 DApps to initiate contract actions on layer 2, and vice versa.
3 |
4 | The X Layer zkEVM Bridge smart contract’s main feature is the use of **Exit Trees** and the **Global Exit Tree**, with the **Global Exit Tree Root** as the primary source of state truth.
5 |
6 | The use of two distinct **Global Exit Root managers** for layer 1 and layer 2, as well as separate logic for Bridge smart contract and each of these **Global Exit Root managers**, allows for extensive network interoperability.
7 | Meanwhile, all asset transfers can be validated by any layer 1 and layer 2 nodes due to data availability.
8 |
9 | The sections that follow explain how the X Layer ZKEVM Bridge-related smart contracts ensure the security of assets transferred between the ZKEVM and any network.
10 |
11 | In the following section, we'll delve into the smart contract used for asset transfer, and the mechanics of sending message/assets across layer 1 and layer 2.
12 |
13 |
14 |
--------------------------------------------------------------------------------
/developer/bridge/usdc-on-x-layer.mdx:
--------------------------------------------------------------------------------
1 | # USDC on X Layer
2 |
3 | 
4 |
5 | ## The difference between USDC and USDC.e
6 |
7 | ## USDC
8 | Circle brings USDC natively to new blockchain networks to empower developers to build on a stable foundation they can trust. Native USDC is officially issued by Circle. [Native USDC is now available on the other Layer 2](https://www.circle.com/blog/native-usdc-now-available-on-zksync "Native USDC").
9 |
10 | |Asset|X Layer mainnet address|
11 | |:----|:----|
12 | |USDC|0x74b7f16337b8972027f6196a17a631ac6de26d22|
13 |
14 | ## USDC.e
15 | There also exists a “bridged” form of USDC known as USDC.e, which is USDC that has been bridged from Ethereum. Bridged USDC (USDC.e) is not issued by Circle.
16 |
17 | |Asset|X Layer mainnet address|
18 | |:----|:----|
19 | |USDC.e|0xA8CE8aee21bC2A48a5EF670afCc9274C7bbbC035|
20 |
21 | ## Using USDC on X Layer
22 |
23 | Whether you are a developer or a user, we recommend that you use **USDC on X Layer**.
24 |
25 | ## For users
26 | Users can get USDC on the X Layer mainnet in these ways:
27 |
28 | 1. Using X Layer official bridge
29 |
30 | When you bridge USDC from Ethereum to the X Layer by [official bridge user interface](https://www.okx.com/xlayer/bridge "XLayer bridge"), you can automatically receive USDC on the X Layer.
31 |
32 | 2. Using OKX exchange
33 |
34 | [OKX](https://www.okx.com/ "OKX") now supports USDC (not USDC.e) deposits and withdrawals.
35 |
36 | 3. Using third-party bridges
37 |
38 | Some well known bridges are integrating with X Layers.
39 |
40 | ## For developers
41 | Please refer to the USDC workflow section.
42 |
43 |
44 |
--------------------------------------------------------------------------------
/developer/build-on-xlayer/bridge-to-xlayer.mdx:
--------------------------------------------------------------------------------
1 | # Bridge to X Layer
2 | You can use [ZKEVM Bridge Contract](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/PolygonZkEVMBridgeV2.sol "ZkEVM Bridge Contract") to bridge assets like ETH, OKB, and ERC-20 tokens between layer 1 and layer 2. However, there are a few points to note:
3 | - ETH is the native token of layer 1 (Ethereum). After bridging to layer 2 X Layer, it becomes a Wrapped ETH (WETH) ERC-20 token.
4 | - OKB is an ERC-20 token of layer 1 (Ethereum). After bridging to layer 2 X Layer, it becomes a native token.
5 | - Other ERC-20 tokens, which are bridged to the other side, remain ERC-20 tokens. You can calculate the new ERC-20 address by using the `precalculatedWrapperAddress` method.
6 | - There are no restrictions if you are bridging ERC-20 tokens from layer 1 to layer 2. However, there is a whitelist restriction when bridging assets from layer 2 to layer 1.
7 | - `NetworkId` and `ChainId` are not the same. `NetworkId` is a property that is unique to Polygon's Agglayer whereas `ChainId` is typically a transaction replay protection mechanism across EVM chains. The relevant information for Ethereum and X Layer are shown below.
8 |
9 | |Network (Mainnet)|ChainId|NetworkId|
10 | |:----|:----|:----|
11 | |Ethereum|1|0|
12 | |X Layer|196|3|
13 |
14 | |Network (Testnet)|ChainId|NetworkId|
15 | |:----|:----|:----|
16 | |Sepolia|11155111|0|
17 | |X Layer testnet|195|1|
18 |
19 | If you want to request layer 2 to layer 1 token whitelisting, you can join our [X Layer Discord server](https://discord.gg/xlayer "X Layer Discord server"), and navigate to `#support-tickets` to raise whitelising request.
20 |
21 | The mapping list for OKB and ETH is as follows:
22 | |ERC-20 Token|Testnet|Mainnet|
23 | |:----|:----|:----|
24 | |OKB|[0x3F4B6664338F23d2397c953f2AB4Ce8031663f80](https://sepolia.etherscan.io/address/0x3F4B6664338F23d2397c953f2AB4Ce8031663f80 "0x3F4B6664338F23d2397c953f2AB4Ce8031663f80") (Layer 1 Ethereum Sepolia)|[0x75231f58b43240c9718dd58b4967c5114342a86c](https://etherscan.io/address/0x75231f58b43240c9718dd58b4967c5114342a86c "0x75231f58b43240c9718dd58b4967c5114342a86c") (Layer 1 Ethereum)|
25 | |WETH|[0xBec7859BC3d0603BeC454F7194173E36BF2Aa5C8](https://www.okx.com/web3/explorer/xlayer-test/address/0xBec7859BC3d0603BeC454F7194173E36BF2Aa5C8 "0xBec7859BC3d0603BeC454F7194173E36BF2Aa5C8") (Layer 2 X Layer testnet)| [0x5a77f1443d16ee5761d310e38b62f77f726bc71c](https://www.okx.com/web3/explorer/xlayer/address/0x5a77f1443d16ee5761d310e38b62f77f726bc71c "0x5a77f1443d16ee5761d310e38b62f77f726bc71c") (Layer 2 X Layer mainnet)|
26 |
27 | ## Deposit OKB and ERC-20 tokens from layer 1
28 | The ZKEVM bridge contract allows ETH and ERC-20 token bridging from layer 1 to layer 2 using the bridgeAsset function. Notice that ERC-20 tokens will have a different address on layer 2. You can use the precalculatedWrapperAddress function to query the new address in [ZkEVMBridgeContract.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/PolygonZkEVMBridgeV2.sol "ZKEVMBridgeContract.sol") contract
29 |
30 | If the asset you bridged is USDC, please refer to this [document](https://www.okx.com/xlayer/docs/developer/bridge/usdc-on-x-layer "usdc document").
31 | ### bridgeAsset
32 | Deposit and add a new leaf to the Merkle tree:
33 | ```solidity
34 | function bridgeAsset(
35 | uint32 destinationNetwork,
36 | address destinationAddress,
37 | uint256 amount,
38 | address token,
39 | bool forceUpdateGlobalExitRoot,
40 | bytes permitData
41 | ) public
42 | ```
43 | **Parameters**
44 | |Name|Type|Description|
45 | |:----|:----|:----|
46 | |`destinationNetwork`|uint32|Network destination. 3 for X Layer|
47 | |`destinationAddress`|address|Address destination|
48 | |`amount`|uint256|Amount of tokens|
49 | |`token`|address|Token address, 0 address is reserved for ETH|
50 | |`forceUpdateGlobalExitRoot`|bool|Indicates if the new global exit root is updated or not|
51 | |`permitData`|bytes|Raw data of the call `permit` of the token|
52 |
53 | ### precalculatedWrapperAddress
54 | This returns the precalculated address of a wrapper using the token information.
55 | Note: Updating the metadata of a token is not supported.
56 | Since the metadata has relevance in the address deployed, this function will not return a valid wrapped address if the metadata provided is not the original one.
57 | ```solidity
58 | function precalculatedWrapperAddress(
59 | uint32 originNetwork,
60 | address originTokenAddress,
61 | string name,
62 | string symbol,
63 | uint8 decimals
64 | ) external returns (address)
65 | ```
66 | **Parameters**
67 | |Name|Type|Description|
68 | |:----|:----|:----|
69 | |`originNetwork`|uint32|Origin network|
70 | |`originTokenAddress`|address|Origin token address, 0 address is reserved for ETH|
71 | |`name`|string|Name of the token|
72 | |`symbol`|string|Symbol of the token|
73 | |`decimals`|uint8|Decimals of the token|
74 |
75 | ## Withdrawing OKB and ERC-20 tokens from layer 2
76 | You can use the `claimAsset` method to retrieve assets on layer 2. Calling this method on layer 2 incurs no Gas fees, so the official bridge service will be provided to automatically invoke the `claimAsset` method for you.
77 |
78 | If the asset you withdrew is native USDC, please refer to this [document](https://www.okx.com/xlayer/docs/developer/bridge/usdc-on-x-layer "usdc document").
79 | ### claimAsset
80 | ```solidity
81 | function claimAsset(
82 | bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProofLocalExitRoot,
83 | bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProofRollupExitRoot,
84 | uint256 globalIndex,
85 | bytes32 mainnetExitRoot,
86 | bytes32 rollupExitRoot,
87 | uint32 originNetwork,
88 | address originTokenAddress,
89 | uint32 destinationNetwork,
90 | address destinationAddress,
91 | uint256 amount,
92 | bytes calldata metadata
93 | ) external
94 | ```
95 | **Parameters**
96 | |Name|Type|Description|
97 | |:----|:----|:----|
98 | |`smtProofLocalExitRoot`|bytes32[32]| Smt proof to proof the leaf against the network exit root|
99 | |`smtProofRollupExitRoot`|bytes32[32]| Smt proof to proof the rollupLocalExitRoot against the rollups exit root |
100 | |`globalIndex`|uint32|Index of the leaf|
101 | |`mainnetExitRoot`|bytes32|Mainnet exit root|
102 | |`rollupExitRoot`|bytes32|Rollup exit root|
103 | |`originNetwork`|uint32|Origin network. 0 for assets from originating from layer 1|
104 | |`originTokenAddress`|address|Origin token address, 0 address is reserved for ETH|
105 | |`destinationNetwork`|uint32|Network destination. 0 for layer 1|
106 | |`destinationAddress`|address|Address destination|
107 | |`amount`|uint256`|Amount of tokens|
108 | |`metadata`|bytes|Abi encoded metadata if any, empty otherwise|
109 |
110 | # Bridge to Ethereum
111 | ## Creating an ERC-20 token with custom logic on X Layer (layer 2)
112 | ERC-20 is the technical standard for fungible tokens created using the Ethereum blockchain. A fungible token is interchangeable with another token — whereas the well-known non-fungible tokens (NFTs) are not interchangeable.
113 | You can read more information about ERC-20 [here](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/ "here").
114 | Deploy a simple ERC-20 contract with any of the tools like [Truffle](/developer/smart-contract/deploy-with-truffle "Truffle"), [Hardhat](/developer/smart-contract/deploy-with-hardhat "Hardhat"), or [Foundry](/developer/smart-contract/deploy-with-foundry "Foundry"). This contract is implemented based on the open-source library, which can be found at [OpenZeppelin](https://www.openzeppelin.com/contracts# "OpenZeppelin").
115 | ```go
116 | // SPDX-License-Identifier: MIT
117 | pragma solidity ^0.8.9;
118 |
119 | import "@openzeppelin/contracts@4.9.3/token/ERC20/ERC20.sol";
120 |
121 | contract MyToken is ERC20 {
122 | constructor() ERC20("MyToken", "MTK") {}
123 | }
124 | ```
125 |
126 | ## Depositing OKB and ERC-20 tokens from layer 2
127 | The same bridge contract is used on both layer 1 and layer 2, so the interface definition is identical.
128 |
129 |
130 | Claiming assets on Ethereum will consume gas fees and is not free.
--------------------------------------------------------------------------------
/developer/build-on-xlayer/gas-station.mdx:
--------------------------------------------------------------------------------
1 | # Gas station
2 | X Layer gas station aims to help DApp developers by suggesting gas prices before they send transactions on the X Layer network.
3 | It's now on the X Layer testnet, checking 1500 recent transactions for price recommendations.
4 |
5 | ## Usage
6 | Send a GET request to the [X Layer Gas Station endpoint](https://testrpc.xlayer.tech/gasstation "X Layer Gas Station endpoint") to get a gas price recommendation from this oracle.
7 |
8 | ### cURL
9 | ```shell
10 | curl https://testrpc.xlayer.tech/gasstation
11 | ```
12 |
13 | ### JavaScript
14 | ```javascript
15 | fetch('https://testrpc.xlayer.tech/gasstation') .then(response => response.json()) .then(json => console.log(json))
16 | ```
17 |
18 | ### Python
19 | ```python
20 | import requestsrequests.get('https://testrpc.xlayer.tech/gasstation').json()
21 | ```
22 |
23 | ## Interpretation
24 | An example JSON response will look like this:
25 | ```json
26 | {
27 | "safeLow": 1,
28 | "standard": 1,
29 | "fast": 1,
30 | "fastest": 1,
31 | "blockTime": 2,
32 | "blockNumber": 308789
33 | }
34 | ```
35 |
36 | - `safelow`, `standard`, `fast`, `fastest` are gas prices in Gwei. Feel free to utilize these prices according to your requirements before submitting the transaction to the X Layer testnet.
37 | - `blockTime`, in seconds, gives the average block time of the network.
38 | - `blockNumber` furnishes details about the most recent mined block at the time the recommendation was generated.
39 |
--------------------------------------------------------------------------------
/developer/build-on-xlayer/quickstart.mdx:
--------------------------------------------------------------------------------
1 | # Quickstart
2 | Welcome to X Layer developer documentation.
3 |
4 | X Layer is a ZKEVM Layer 2 network built on Ethereum, powered by [Polygon CDK](https://wiki.polygon.technology/docs/cdk/ "Polygon CDK") — a ZKEVM stack for building Ethereum layer 2 scaling solutions.
5 | Developers can easily deploy their existing contracts on ZKEVM, and users can move their assets from Ethereum and conduct transactions off-chain. These transactions are bundled into groups with a zero-knowledge proof to verify their validity.
6 |
7 | ## Why build on X Layer?
8 | - **Boundless scalability**: enable ZK-powered DApps on X Layer, with 100% EVM compatibility and easy-to-use developer tools for deployment
9 | - **Powered by OKX**: seamless OKX product integrations, all-in-one Web3 gateway, and access to 50M+ users in the OKX ecosystem
10 | - **Security**: rely on robust secure mechanisms from Ethereum, with trustless interoperability
11 | - **Low fee**: same coding experience as Ethereum, with 100x less in costs
12 | - **Portal to Web3**: enter the world of Web3 via OKX Wallet, built with compact infrastructure modules to create innovative DApps
13 | - **Powered by Polygon**: ZKEVM Layer 2 based on Polygon CDK, ensuring near-instant finality, unified liquidity, and independent data availability
14 |
15 | ## What’s the difference between building on X Layer vs. Ethereum for developers?
16 | Building DApps on X Layer is just like building them on Ethereum. All you have to do is switch to the X Layer RPC and begin your development on X Layer, that offers faster transactions, lower costs, and robust security. X Layer offers a user experience similar to the Ethereum Virtual Machine (EVM) for both developers and users. This means you won’t need any new tools or wallets to create or use DApps on ZKEVM.
17 |
18 | You can visit Polygon’s [Differences between EVM and ZKEVM](https://wiki.polygon.technology/docs/zkevm/protocol/evm-diff/ "Differences between EVM and ZKEVM") for detailed differences in terms of supported EIPs, opcodes, and additional changes to build on ZKEVM.
19 |
20 | ## Acquiring testnet OKB
21 | To start building on X Layer, you’ll first need some testnet OKB. See the [Faucet guide](/getting-started/user-guide/get-testnet-okb-from-faucet "Faucet guide") for the steps to get testnet OKB on X Layer.
22 |
23 | ## Connecting to X Layer (Mainnet)
24 | You can add X Layer mainnet by inputting the following network info:
25 | |Properties|Network details|
26 | |:----|:----|
27 | |Network name|X Layer mainnet|
28 | |RPC URL|https://rpc.xlayer.tech|
29 | |Chain ID|196|
30 | |Token symbol|OKB|
31 | |Block explorer URL|https://www.okx.com/web3/explorer/xlayer|
32 |
33 | ## Connecting to X Layer (Testnet)
34 | You can add X Layer testnet by inputting the following network info:
35 | |Properties|Network details|
36 | |:----|:----|
37 | |Network name|X Layer testnet|
38 | |RPC URL|https://testrpc.xlayer.tech|
39 | |Chain ID|195|
40 | |Token symbol|OKB|
41 | |Block explorer URL|https://www.okx.com/web3/explorer/xlayer-test|
42 |
43 | You can connect to the X Layer Testnet through the RPC service provider [ZAN Node](https://zan.top/home/node-service/?partner=X1 "ZAN Node") or simply add X Layer Testnet to MetaMask through [Chainlist](https://chainlist.org/chain/195 "Chainlist")
44 |
45 | The next step is to [bridge your assets](/getting-started/user-guide/bridge "bridge your assets") from Ethereum → X Layer. You can use the [X Layer Bridge](https://www.okx.com/xlayer/bridge-test "X Layer Bridge") to bridge your assets.
46 |
47 | ## Deploying smart contracts
48 | Developing on X Layer is seamless and identical to Ethereum Virtual Machine (EVM). Developers can use their existing code and toolings to deploy on X Layer with much better performance and lower fees.
49 | Check out how to deploy smart contracts on X Layer:
50 |
51 |
52 |
53 |
54 | ## Developer support
55 | If you need help with anything related to X Layer, you can raise your questions on our Discord channel:
56 | 1. Join the X Layer Discord server [here](https://discord.gg/xlayer "here").
57 | 2. Select "Yes" when asked if you are a developer.
58 | 3. Navigate to the `#dev-support` channel.
59 | You can now contact X Layer tech support staff with your questions and concerns. We will actively monitor for issues and work to resolve them asap.
--------------------------------------------------------------------------------
/developer/build-on-xlayer/safe-contracts.mdx:
--------------------------------------------------------------------------------
1 | # Safe contracts
2 |
3 | ## Version
4 |
5 | - Safe: Proxy Factory 1.3.0
6 | - Verified: True
7 | - Link: https://safe.xlayer.tech/welcome
8 |
9 | The table below shows the Safe contract addresses for X Layer. Alternatively, you can visit this [link](https://docs.safe.global/advanced/smart-account-supported-networks/v1.3.0 "Safe contract") to view the contract addresses.
10 |
11 | To access X Layer's Safe wallet, click [here](https://safe.xlayer.tech/welcome "safe wallet").
12 |
13 | ## X Layer Safe contracts
14 | |Name|Detail|Mainnet address|
15 | |:----|:--|:--|
16 | |Safe factory|Safe factory Address|v1:[0xa6B71E26C5e0845f74c812102Ca7114b6a896AB2](https://www.okx.com/web3/explorer/xlayer/address/0xa6b71e26c5e0845f74c812102ca7114b6a896ab2 "v1 safe factory")
v2:[0xC22834581EbC8527d974F8a1c97E1bEA4EF910BC](https://www.okx.com/web3/explorer/xlayer/address/0xc22834581ebc8527d974f8a1c97e1bea4ef910bc "v2 safe factory")|
17 | |Safe signleton|Safe signleton Address| v1:[0xd9Db270c1B5E3Bd161E8c8503c55cEABeE709552](https://www.okx.com/web3/explorer/xlayer/address/0xd9db270c1b5e3bd161e8c8503c55ceabee709552 "v1 safe signleton")
v2:[0x69f4D1788e39c87893C980c06EdF4b7f686e2938](https://www.okx.com/web3/explorer/xlayer/address/0x69f4d1788e39c87893c980c06edf4b7f686e2938 "v2 safe signleton")|
18 | |CompatibilityFallbackHandler|CompatibilityFallbackHandler Address|v1:[0xf48f2B2d2a534e402487b3ee7C18c33Aec0Fe5e4](https://www.okx.com/web3/explorer/xlayer/address/0xf48f2b2d2a534e402487b3ee7c18c33aec0fe5e4 "v1 fallbackhandler")
v2:[0x017062a1dE2FE6b99BE3d9d37841FeD19F573804](https://www.okx.com/web3/explorer/xlayer/address/0x017062a1de2fe6b99be3d9d37841fed19f573804 "v2 fallbackhandler")|
19 | |CreateCall|CreateCall Address|v1:[0x7cbB62EaA69F79e6873cD1ecB2392971036cFAa4](https://www.okx.com/web3/explorer/xlayer/address/0x7cbb62eaa69f79e6873cd1ecb2392971036cfaa4 "v1 createcall")
v2:[0xB19D6FFc2182150F8Eb585b79D4ABcd7C5640A9d](https://www.okx.com/web3/explorer/xlayer/address/0xb19d6ffc2182150f8eb585b79d4abcd7c5640a9d "v2 createcall")|
20 | |Gnosis_safe_l2|Gnosis safe Address|v1:[0x3E5c63644E683549055b9Be8653de26E0B4CD36E](https://www.okx.com/web3/explorer/xlayer/address/0x3e5c63644e683549055b9be8653de26e0b4cd36e "v1 gnosis safe")
v2:[0xfb1bffC9d739B8D520DaF37dF666da4C687191EA](https://www.okx.com/web3/explorer/xlayer/address/0xfb1bffc9d739b8d520daf37df666da4c687191ea "v2 gnosis safe")|
21 | |multi_send|Multi send Address|v1:[0xa238cbeb142c10ef7ad8442c6d1f9e89e07e7761](https://www.okx.com/web3/explorer/xlayer/address/0xa238cbeb142c10ef7ad8442c6d1f9e89e07e7761 "v1 multisend")
v2:[0x998739BFdAAdde7C933B942a68053933098f9EDa](https://www.okx.com/web3/explorer/xlayer/address/0x998739bfdaadde7c933b942a68053933098f9eda "V2 multisend")|
22 | |multi_send_call_only|Multi send call Address|v1:[0x40A2aCCbd92BCA938b02010E17A5b8929b49130D](https://www.okx.com/web3/explorer/xlayer/address/0x40a2accbd92bca938b02010e17a5b8929b49130d "v1 multisendcall")
v2:[0xA1dabEF33b3B82c7814B6D82A79e50F4AC44102B](https://www.okx.com/web3/explorer/xlayer/address/0xa1dabef33b3b82c7814b6d82a79e50f4ac44102b "V2 multisendcall")|
23 | |sign_message_lib|Sign message Address|v1:[0xA65387F16B013cf2Af4605Ad8aA5ec25a2cbA3a2](https://www.okx.com/web3/explorer/xlayer/address/0xa65387f16b013cf2af4605ad8aa5ec25a2cba3a2 "v1 signmessage")
v2:[0x98FFBBF51bb33A056B08ddf711f289936AafF717](https://www.okx.com/web3/explorer/xlayer/address/0x98ffbbf51bb33a056b08ddf711f289936aaff717 "v2 signmessage")|
24 | |simulate_tx_accessor|Simulate transaction Address|v1:[0x59AD6735bCd8152B84860Cb256dD9e96b85F69Da](https://www.okx.com/web3/explorer/xlayer/address/0x59ad6735bcd8152b84860cb256dd9e96b85f69da "v1 simulatetxn")
v2:[0x727a77a074D1E6c4530e814F89E618a3298FC044](https://www.okx.com/web3/explorer/xlayer/address/0x727a77a074d1e6c4530e814f89e618a3298fc044 "v2 simulatetxn")|
--------------------------------------------------------------------------------
/developer/build-on-xlayer/websocket-endpoints.mdx:
--------------------------------------------------------------------------------
1 | # Websocket endpoints
2 | X Layer supports Websocket methods that are compatible with Ethereum, and ZKEVM RPC methods for ZKEVM.
3 |
4 | The WebSockets (WSS) communication protocol enables two-way communication between a client and a server over a single TCP connection. The communication protocol maintains a network connection between the two parties, allowing for real-time, low-latency communication. WebSockets allow for ongoing, bidirectional communication unlike HTTP, which is a request-response protocol.
5 |
6 | ## Mainnet (chain-id: 0xC4, 196 in decimals)
7 | WSS:
8 | - wss://xlayerws.okx.com
9 | - wss://ws.xlayer.tech
10 |
11 | ## Testnet (chain-id: 0xC3, 195 in decimals)
12 | WSS:
13 | - wss://xlayertestws.okx.com
14 | - wss://testws.xlayer.tech
15 |
16 | ## Websocket methods
17 | Subscription methods are available for WebSocket connections only, and allow you to wait for events instead of polling for them. For example, DApps can subscribe to logs and receive notifications when a specific event occurs.
18 |
19 | The following subscription methods are available:
20 | - `eth_subscribe` - Create a subscription to a particular event
21 | - `eth_unsubscribe` - Cancel an active subscription
22 |
23 | It also supports Ethereum compatible and ZKEVM RPC methods with websocket.
24 | You need to install [ws](https://github.com/hashrocket/ws "ws"), or another websocket client
25 |
26 | ```shell
27 | # install wss tools
28 | go install github.com/hashrocket/ws@latest
29 |
30 | # connect to the wss server
31 | ws wss://xlayertestws.okx.com
32 | ```
33 |
34 | ### eth_subscribe
35 | Subscribe to different Ethereum event types like newHeads, logs, pendingTransactions, and minedTransactions using WebSockets.
36 |
37 | **Parameters**
38 | Specify the subscription event parameters, including the following:
39 | - `newHeads`: Subscribing to this returns a notification each time a new header is appended to the chain, including chain reorganizations. In chain reorganization, the subscription emits all new headers for the new chain. Therefore, the subscription can emit multiple headers at the same height.
40 | - `logs`: Returns logs that are included in new imported blocks and match the given filter criteria. In case of a chain reorganization, previously sent logs that are on the old chain are resent with the removed property set to `true`. Logs from transactions that ended up in the new chain are emitted. Therefore, a subscription can emit logs for the same transaction multiple times. This parameter has the following fields:
41 | - `address`: *(optional)* Either an address or an array of addresses. Only logs that are created from these addresses are returned.
42 | - `topics`: *(optional)* Only logs that match these specified topics are returned.
43 | - `newPendingTransactions`: not supported
44 |
45 | **Returns**
46 | `subscription ID`: The ID of the newly created subscription on the node.
47 |
48 | **Example**
49 | **Event newHeads**
50 | ```shell
51 | > {"id": 1, "method": "eth_subscribe", "params": ["newHeads"]}
52 | ```
53 | ```json
54 | // Response OK
55 | {"jsonrpc":"","id":1,"result":"0x4698d49adc4f4590a7a685702a7890a1"}
56 |
57 | // Response newHeads
58 | {"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0x4698d49adc4f4590a7a685702a7890a1","result":{"parentHash":"0x8cbb9b4bbd08169f6721ca427b7596d367343beafefd795a739aa7561e402aa6","sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","miner":"0x5e7b89ab3b2de21f0f35da4920b9d7310ccbe259","stateRoot":"0x82a790655c9731a90388eded2cfcb1dfb9ccd7fedc50a76027ece92b1a1c0a99","transactionsRoot":"0xca77a5c5bbc6ab7cc1a5aca874525d644602c06a8bd78b9a30530cbc311c1204","receiptsRoot":"0x59c28ec1a61258d901bdb099195292ec2ed440e3a8820401c28ec7c77f752791","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000008000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000","difficulty":"0x0","totalDifficulty":"0x0","size":"0x356","number":"0xf92e","gasLimit":"0x1c9c380","gasUsed":"0x2c84c","timestamp":"0x65558e95","extraData":"0x","mixHash":"0x0000000000000000000000000000000000000000000000000000000000000000","nonce":"0x0000000000000000","hash":"0x3313d5a4c5580d6db0310cd6a2e1107bb5b4f94cf16232619ac3bd7d9d04a8f0","transactions":["0x762b9a2eb0b13775beabdacd91fb9150dab945f998c93b92bb838a26542d49c5"],"uncles":[]}}}
59 | ```
60 | **Event logs**
61 | ```shell
62 | > {"jsonrpc":"2.0","method":"eth_subscribe","params":["logs",{"topics":["0x7bcec107ebaef6075ec44d44bbaceef2832d8ef887883240b63415dd770788e9"]}],"id":0}
63 | ```
64 | ```json
65 | // Response OK
66 | {"jsonrpc":"2.0","id":1,"result":"0x9aebda1c07ed47f78053751ebbbd26d5"}
67 |
68 | // Response Event Logs
69 | {"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0x9aebda1c07ed47f78053751ebbbd26d5","result":{"parentHash":"0x2f823eea412f288a4575c66f845b0eebb40fba3313c36197e20af204b6f7d3be","sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","miner":"0x4e830165ff22f4592f0933f01d2d4ffd0b1fccf8","stateRoot":"0xd579fdae44038a6654d23e18ab12d8447fb2732b49eae323f7586959a844f1b2","transactionsRoot":"0x60fd8387b75b3c2c16cd9a51e466d188a967d3a27ef845844cf56008a50b0ddc","receiptsRoot":"0xa0480d2161fb5802ed71872b85cd6828cf9ea74794dc04307d0009ac80e3ed73","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","difficulty":"0x0","totalDifficulty":"0x0","size":"0x273","number":"0x29502","gasLimit":"0x1c9c380","gasUsed":"0x5208","timestamp":"0x652cdae7","extraData":"0x","mixHash":"0x0000000000000000000000000000000000000000000000000000000000000000","nonce":"0x0000000000000000","hash":"0x9703f514105904358b28a804d2ceda3ee3bc075dae9a23d99f352e0346e3f582","transactions":["0x495faaf906c862af71e6f298880c239415a2f80f7fb103bedb00f57dd0392ab0"],"uncles":[]}}}
70 | ```
71 |
72 | ### eth_unsubscribe
73 | Cancel the specified subscription by calling `eth_unsubscribe`. Returns a Boolean value indicating whether the cancellation was successful
74 |
75 | **Parameter**
76 | - `subscription ID`: The ID of the subscription you want to unsubscribe.
77 |
78 | **Returns**
79 | - `unsubscribed flag`: (boolean) True if the subscription is canceled successfully.
80 |
81 | **Example**
82 | ```shell
83 | # subscribe to new block Headers
84 | > {"id": 1, "method": "eth_unsubscribe", "params":["0xefa20a66c94a4da7ae18294db6261b42"]}
85 | ```
86 | ```json
87 | // Response
88 | {"jsonrpc":"","id":1,"result":true}
89 | ```
90 |
91 | ### Others
92 | It also supports Ethereum compatible and ZKEVM [RPC methods](/developer/build-on-xlayer/rpc-endpoints "RPC methods") with websocket.
93 |
94 | **Example**
95 | ```shell
96 | # call eth_gasPrice method
97 | > {"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":73}
98 | ```
99 | ```json
100 | // Response
101 | {"jsonrpc":"2.0","id":73,"result":"0x1db0c8c80"}
102 | ```
--------------------------------------------------------------------------------
/developer/build-on-xlayer/zkevm-contracts.mdx:
--------------------------------------------------------------------------------
1 | # ZKEVM contracts
2 |
3 | ## X Layer ZKEVM contracts
4 | These smart contracts facilitate ZKEVM operation on Ethereum Mainnet and Sepolia Testnet.
5 | ### Ethereum Layer 1
6 | |Name|Detail|Mainnet address| Testnet address|
7 | |:----|:--|:--|:--|
8 | |[PolygonValidiumEtrog.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/consensus/validium/PolygonValidiumEtrog.sol "PolygonValidiumEtrog.sol")|Consensus smart contract|[0x2B0ee28D4D51bC9aDde5E58E295873F61F4a0507](https://etherscan.io/address/0x2B0ee28D4D51bC9aDde5E58E295873F61F4a0507 "0x2B0ee28D4D51bC9aDde5E58E295873F61F4a0507")|[0x01469dACfDDA885D68Ff0f8628F2629c14F95a20](https://sepolia.etherscan.io/address/0x01469dACfDDA885D68Ff0f8628F2629c14F95a20 "0x01469dACfDDA885D68Ff0f8628F2629c14F95a20")|
9 | |[RollupManagerAddress.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/PolygonRollupManager.sol "RollupManagerAddress.sol")|Rollup manager smart contract|[0x5132a183e9f3cb7c848b0aac5ae0c4f0491b7ab2](https://etherscan.io/address/0x5132a183e9f3cb7c848b0aac5ae0c4f0491b7ab2 "0x5132a183e9f3cb7c848b0aac5ae0c4f0491b7ab2")|[0x6662621411A8DACC3cA7049C8BddABaa9a999ce3](https://sepolia.etherscan.io/address/0x6662621411A8DACC3cA7049C8BddABaa9a999ce3 "0x6662621411A8DACC3cA7049C8BddABaa9a999ce3")|
10 | |[ZkEVMBridge.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/PolygonZkEVMBridgeV2.sol "ZkEVMBridge.sol")|Bridge smart contract| [0x2a3DD3EB832aF982ec71669E178424b10Dca2EDe](https://etherscan.io/address/0x2a3DD3EB832aF982ec71669E178424b10Dca2EDe "0x2a3DD3EB832aF982ec71669E178424b10Dca2EDe")|[0x7a4Ee6f9F0aB037fE771FC36D39C1E19bcc0Fdb5](https://sepolia.etherscan.io/address/0x7a4Ee6f9F0aB037fE771FC36D39C1E19bcc0Fdb5 "0x7a4Ee6f9F0aB037fE771FC36D39C1E19bcc0Fdb5")|
11 | |[ZkEVMGlobalExitRoot.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/PolygonZkEVMGlobalExitRootV2.sol "ZkEVMGlobalExitRoot.sol")|Global exit root manager smart contract|[0x580bda1e7A0CFAe92Fa7F6c20A3794F169CE3CFb](https://etherscan.io/address/0x580bda1e7A0CFAe92Fa7F6c20A3794F169CE3CFb "0x580bda1e7A0CFAe92Fa7F6c20A3794F169CE3CFb")|[0x66E61bA00F58b857A9DD2C500F3aBc424A46BD20](https://sepolia.etherscan.io/address/0x66E61bA00F58b857A9DD2C500F3aBc424A46BD20 "0x66E61bA00F58b857A9DD2C500F3aBc424A46BD20")|
12 | |[DataCommittee.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/consensus/validium/PolygonDataCommittee.sol "DataCommittee.sol")|Data availability committees smart contract|[0x05652Ec92366F3C2255991a265c499E01Ba58e6a](https://etherscan.io/address/0x05652Ec92366F3C2255991a265c499E01Ba58e6a "0x05652Ec92366F3C2255991a265c499E01Ba58e6a") |[0x9d89De09fa8666cD82fDb0E2466bB56D704D60e7](https://sepolia.etherscan.io/address/0x9d89De09fa8666cD82fDb0E2466bB56D704D60e7 "0x9d89De09fa8666cD82fDb0E2466bB56D704D60e7")|
13 | |OKBContract.sol|OKB smart contract|[0x75231f58b43240c9718dd58b4967c5114342a86c](https://etherscan.io/address/0x75231f58b43240c9718dd58b4967c5114342a86c "0x75231f58b43240c9718dd58b4967c5114342a86c")|[0x3F4B6664338F23d2397c953f2AB4Ce8031663f80](https://sepolia.etherscan.io/address/0x3F4B6664338F23d2397c953f2AB4Ce8031663f80 "0x3F4B6664338F23d2397c953f2AB4Ce8031663f80")|
14 |
15 | ### X Layer Layer 2
16 | |Name|Detail|Mainnet address| Testnet address|
17 | |:----|:--|:--|:--|
18 | |[ZkEVMBridge.sol](https://github.com/okx/xlayer-contracts/blob/v0.3.1/contracts/v2/PolygonZkEVMBridgeV2.sol "ZkEVMBridge.sol")|Bridge smart contract|[0x2a3DD3EB832aF982ec71669E178424b10Dca2EDe](https://www.okx.com/web3/explorer/xlayer/address/0x2a3DD3EB832aF982ec71669E178424b10Dca2EDe "0x2a3DD3EB832aF982ec71669E178424b10Dca2EDe")|[0x7a4Ee6f9F0aB037fE771FC36D39C1E19bcc0Fdb5](https://www.okx.com/web3/explorer/xlayer-test/address/0x7a4Ee6f9F0aB037fE771FC36D39C1E19bcc0Fdb5 "0x7a4Ee6f9F0aB037fE771FC36D39C1E19bcc0Fdb5")|
19 | |[ZkEVMGlobalExitRootL2.sol](https://github.com/okx/xlayer-contracts/blob/v0.3.1/contracts/v2/PolygonZkEVMGlobalExitRootV2.sol "ZkEVMGlobalExitRootL2.sol")|Global exit root manager smart contract|[0xa40d5f56745a118d0906a34e69aec8c0db1cb8fa](https://www.okx.com/web3/explorer/xlayer/address/0xa40d5f56745a118d0906a34e69aec8c0db1cb8fa "0xa40d5f56745a118d0906a34e69aec8c0db1cb8fa")|[0xa40d5f56745a118d0906a34e69aec8c0db1cb8fa](https://www.okx.com/web3/explorer/xlayer-test/address/0xa40d5f56745a118d0906a34e69aec8c0db1cb8fa "0xa40d5f56745a118d0906a34e69aec8c0db1cb8fa")|
20 | |[WOKB](https://www.okx.com/web3/explorer/xlayer/address/0xe538905cf8410324e03a5a23c1c177a474d59b2b "WOKB")|WOKB Token Address|[0xe538905cf8410324e03a5a23c1c177a474d59b2](https://www.okx.com/web3/explorer/xlayer/address/0xe538905cf8410324e03a5a23c1c177a474d59b2b "0xe538905cf8410324e03a5a23c1c177a474d59b2b")|-|
21 | |[WETH](https://www.okx.com/web3/explorer/xlayer/token/0x5a77f1443d16ee5761d310e38b62f77f726bc71c "WETH")|WETH Token Address|[0x5a77f1443d16ee5761d310e38b62f77f726bc71c](https://www.okx.com/web3/explorer/xlayer/address/0x5a77f1443d16ee5761d310e38b62f77f726bc71c "0x5a77f1443d16ee5761d310e38b62f77f726bc71c")|[0xBec7859BC3d0603BeC454F7194173E36BF2Aa5C8](https://www.okx.com/web3/explorer/xlayer-test/address/0xBec7859BC3d0603BeC454F7194173E36BF2Aa5C8 "0xBec7859BC3d0603BeC454F7194173E36BF2Aa5C8")|
22 | |[USDT](https://www.okx.com/web3/explorer/xlayer/address/0x1e4a5963abfd975d8c9021ce480b42188849d41d "USDT")|USDT Token Address|[0x1e4a5963abfd975d8c9021ce480b42188849d41d](https://www.okx.com/web3/explorer/xlayer/address/0x1e4a5963abfd975d8c9021ce480b42188849d41d "0x1e4a5963abfd975d8c9021ce480b42188849d41d")|-|
23 | |[USDC](https://www.okx.com/web3/explorer/xlayer/address/0x74b7f16337b8972027f6196a17a631ac6de26d22 "USDC")|USDC Token Address|[0x74b7F16337b8972027F6196A17a631aC6dE26d22](https://www.okx.com/web3/explorer/xlayer/address/0x74b7f16337b8972027f6196a17a631ac6de26d22 "0x74b7F16337b8972027F6196A17a631aC6dE26d22")|-|
24 | |[USDC.e](https://www.okx.com/web3/explorer/xlayer/address/0xA8CE8aee21bC2A48a5EF670afCc9274C7bbbC035 "USDC.e")|USDC.e Token Address|[0xA8CE8aee21bC2A48a5EF670afCc9274C7bbbC035](https://www.okx.com/web3/explorer/xlayer/address/0xA8CE8aee21bC2A48a5EF670afCc9274C7bbbC035 "0xA8CE8aee21bC2A48a5EF670afCc9274C7bbbC035")|-|
25 | |[WBTC](https://www.okx.com/web3/explorer/xlayer/address/0xea034fb02eb1808c2cc3adbc15f447b93cbe08e1 "WBTC")|WBTC Token Address|[0xEA034fb02eB1808C2cc3adbC15f447B93CbE08e1](https://www.okx.com/web3/explorer/xlayer/address/0xea034fb02eb1808c2cc3adbc15f447b93cbe08e1 "0xEA034fb02eB1808C2cc3adbC15f447B93CbE08e1")|-|
26 | |[DAI](https://www.okx.com/web3/explorer/xlayer/address/0xc5015b9d9161dca7e18e32f6f25c4ad850731fd4 "DAI")|DAI Token Address|[0xC5015b9d9161Dca7e18e32f6f25C4aD850731Fd4](https://www.okx.com/web3/explorer/xlayer/address/0xc5015b9d9161dca7e18e32f6f25c4ad850731fd4)
--------------------------------------------------------------------------------
/developer/learn-more/img/consensus-contract-flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/img/consensus-contract-flow.png
--------------------------------------------------------------------------------
/developer/learn-more/img/xlayer-architecture.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/img/xlayer-architecture.jpg
--------------------------------------------------------------------------------
/developer/learn-more/img/zknode-architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/img/zknode-architecture.png
--------------------------------------------------------------------------------
/developer/learn-more/img/zkprover-control-flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/img/zkprover-control-flow.png
--------------------------------------------------------------------------------
/developer/learn-more/img/zkvalidium-vs-zkrollup.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/img/zkvalidium-vs-zkrollup.jpg
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/batch-aggregation.mdx:
--------------------------------------------------------------------------------
1 | # Batch aggregation
2 | ## Aggregation summary
3 | Upon reaching the layer 1 (layer 1) network, after all sequenced batches have been processed, the final step involves creating a zero-knowledge (ZK) proof to validate the transactions’ legitimacy. Aggregator nodes collect the sequenced batches and deliver them to the ZKProver, which employs the fflonk protocol to produce a conclusive SNARK (Succinct Non-interactive Argument of Knowledge) proof. Subsequently, the aggregator receives a ZK-proof that is compact enough to be stored on Ethereum’s layer 1.
4 |
5 | SNARK, which stands for Succinct Non-interactive Arguments of Knowledge, serves as the underlying verification schema for Zero-Knowledge proofs. Its primary distinguishing features include its conciseness and rapid verification capabilities.
6 |
7 | 
8 |
9 | Ultimately, the batches of transactions are consolidated into a final state, thereby inheriting Ethereum’s security model. This is achieved by posting and proving all transaction data back on Ethereum’s layer 1.
10 |
11 | 
12 |
13 | As depicted in the above diagram, the off-chain execution of batches implies a transition to a new layer 2 (layer 2) state, resulting in a change to a new layer 2 state root. An aggregator generates computational integrity (CI) proof of this execution, and its on-chain verification ensures the validity of the resulting layer 2 state root.
14 |
15 | ## Aggregating batches
16 | Once the aggregator node possesses the proof, it invokes the [ZkEVM.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/consensus/validium/PolygonValidiumEtrog.sol "ZKEVM.sol") smart contract’s `trustedVerifyBatches` function and provides the received proof. Here’s the function’s source code:
17 | ```solidity
18 | function trustedVerifyBatches (
19 | uint64 pendingStateNum,
20 | uint64 initNumBatch,
21 | uint64 finalNewBatch,
22 | bytes32 newLocalExitRoot,
23 | bytes32 newStateRoot,
24 | uint256 [2] calldata proofA,
25 | uint256 [2][2] calldata proofB,
26 | uint256 [2] calldata proofC
27 | ) public onlyTrustedAggregator
28 | ```
29 | In the context of this function:
30 | - `pendingStateNum` represents the number of pending state transitions to be consolidated, which is set to 0 as long as the trusted aggregator is operational. This `pending state` acts as a security measure for layer 2 state consolidation by an independent aggregator.
31 | - `initNumBatch` is the index of the last batch in the previous aggregated sequence.
32 | - `finalNewBatch` is the index of the last batch in the sequence being aggregated.
33 | - `newLocalExitRoot` is the root of the bridge’s layer 2 exit Merkle tree at the end of sequence execution, which is used to compute the new global exit root during sequence aggregation, allowing bridge claiming transactions to be executed successfully on layer 1.
34 | - `newStateRoot` is the layer 2 state root resulting from the execution of the sequence of batches in an older layer 2 state.
35 | - `proof(A,B and C)` are the components of the ZK-proof.
36 |
37 | To successfully aggregate a sequence of batches, the following conditions must be met:
38 | - The aggregation transaction must be sent from the trusted aggregator account.
39 | - `initNumBatch` must correspond to an already aggregated batch, meaning it must have a layer 2 state root in the "batchNumToStateRoot" mapping.
40 | - `initNumBatch` must be less than or equal to the index of the last aggregated batch.
41 | - The sequence to be aggregated must contain at least one batch.
42 | - Both `initNumBatch` and `finalNewBatch` must be batches that are part of the `sequencedBatches` mapping.
43 | - ZK-proof of computational integrity must be successfully verified.
44 |
45 | The executor and the prover are tools used by the aggregator to execute batches of transactions and generate zk-proofs. The interaction process is as follows:
46 | 1. Execute a sequence of transaction batches based on the current layer 2 state.
47 | 2. Calculate the resulting layer 2 state root.
48 | 3. Generate a ZK-proof of computational integrity for execution.
49 |
50 | The following code demonstrates how to verify the ZK-proof on layer 1:
51 | ```solidity
52 | // Get snark bytes
53 | bytes memory snarkHashBytes = getInputSnarkBytes (
54 | initNumBatch,
55 | finalNewBatch,
56 | newLocalExitRoot,
57 | oldStateRoot,
58 | newStateRoot
59 | );
60 |
61 | // Calculate the snark input
62 | uint256 inputSnark = uint256(sha256(snarkHashBytes)) % _RFIELD;
63 |
64 | // Verify proof
65 | require (
66 | rollupVerifier.verifyProof(proofA, proofB, proofC, [inputSnark]),
67 | "ZkEVM :: _verifyBatches : Invalid proof"
68 | );
69 | ```
70 | Regarding the `inputSnark` section, please refer to the [**Transaction validation**](/developer/learn-more/xlayer-protocol/transaction-validation "Transaction validation") chapter for more details.
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/batch-sequencing.mdx:
--------------------------------------------------------------------------------
1 | # Batch sequencing
2 | Once we have batches of transactions, they are ready to be sequenced. The sequencer will call the layer 1 [ZkEVM.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/consensus/validium/PolygonValidiumEtrog.sol "ZKEVM.sol") contract’s `sequencedBatches` function and provide it with multiple batches of transactions. It is basically a storage structure that holds the queue of sequences defining the virtual state.
3 | ```solidity
4 | // SequenceBatchNum --> SequencedBatchData
5 | mapping(uint64 => SequencedBatchData) public sequencedBatches;
6 | ```
7 | In order to get sequenced, batches need to be included in the array of batches. To do this, the trusted sequencer invokes `ZkEVM.sol` contract’s `sequencedBatches` and takes an array of batches as an argument. Please see the code snippet below:
8 | ```solidity
9 | function sequenceBatches (
10 | BatchData[] memory batches
11 | ) public ifNotEmergencyState onlyTrustedSequencer
12 | ```
13 | The figure below shows how a sequence of batches is organized:
14 |
15 | 
16 |
17 | ## Contract constraints
18 | With the [validium](https://ethereum.org/en/developers/docs/data-availability/ "validium") mode, the contract has the following limits:
19 | - `signaturesAndAddrs` byte array containing the signatures and all the addresses of the committee in ascending order * [signature 0, ..., signature requiredAmountOfSignatures -1, address 0, ... address N]
20 | - `transactionsHash` is the hash of transactions data, while the `transactions` will be set nil.
21 |
22 | With the [rollup](https://ethereum.org/en/developers/docs/data-availability/ "rollup") mode, the contract has the following two public constants:
23 |
24 | - **Max transactions byte length**: determines the maximum number of transactions that can be included in a batch (300,000)
25 | - **Max verify batches**: limits a sequence to a maximum of 1,000 batches, and the batch array must contain at least one batch
26 |
27 | Only the trusted sequencer’s Ethereum account can access the `sequencedBatches` mapping. It is also necessary that the contract not be in an emergency state.
28 |
29 | **The function call will be reverted if the above conditions are not met.**
30 |
31 | ## Batch validity & layer 2 state integrity
32 | The `sequencedBatches` function iterates over every batch of the sequence, checking its validity. A valid batch must meet the following criteria:
33 | - It must include a `globalExitRoot` value that is present in the **GlobalExitRootMap** of the bridge’s layer 1 [ZkEVMGlobalExitRoot.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/PolygonZkEVMGlobalExitRootV2.sol "ZKEVMGlobalExitRoot.sol") contract. A batch is valid only if it includes a valid `globalExitRoot`.
34 | - The length of the transaction’s byte array must be less than the value of **MAX_TRANSACTIONS_BYTE_LENGTH** constant.
35 | - The timestamp of the batch must be greater or equal to that of the last batch sequenced, but less than or equal to the timestamp of the block where the sequencing layer 1 transaction is executed. All batches must be ordered by time.
36 |
37 | If one batch is not valid, the transaction reverts, meaning the whole sequence will be discarded. On the other hand, if all batches to be sequenced are valid, the sequencing process will continue.
38 |
39 | A storage variable named `lastBatchSequenced` is used to count and assign specific index numbers to each batch in the batch chain. This helps establish their positions in the batch chain.
40 |
41 | To ensure the integrity of the batch chain, a similar hashing mechanism is employed as seen in blockchains, linking each batch to the one that follows. This includes the previous batch’s digest in the calculation of the next batch’s digest. Consequently, a batch’s digest is essentially an accumulated hash of all the previously sequenced batches, referred to as `oldAccInputHash` for the previous and `newAccInputHash` for the current one.
42 | An accumulated hash of a specific batch has the following structure:
43 | ```solidity
44 | keccak256 (
45 | abi.encodePacked (
46 | bytes32 oldAccInputHash,
47 | keccak256(bytes transactions),
48 | bytes32 globalExitRoot ,
49 | uint64 timestamp ,
50 | address seqAddress
51 | )
52 | )
53 | ```
54 | Where:
55 | - `oldAccInputHash` is the accumulated hash of the previous sequenced batch
56 | - `keccack256(transactions)` is the keccak digest of the transactions byte array
57 | - `globalExitRoot` is the root of the bridge’s global exit Merkle tree
58 | - `timestamp` is the batch timestamp
59 | - `seqAddress` is the address of the batch sequencer
60 |
61 | 
62 |
63 | As shown in the diagram above, each accumulated input hash ensures the integrity of the current batch’s data (i.e., `transactions`, `timestamp`, and `globalExitRoot`, as well as the order in which they were sequenced.)
64 |
65 | Any change in the batch chain that causes all future accumulated input hashes to be incorrect, would indicate a lack of integrity in the resulting layer 2 state.
66 |
67 | The batch sequence is added to the `sequencedBatches` mapping using the following `SequencedBatchData` struct only after the validity of all batches in a sequence has been verified and the accumulated hash of each batch has been computed.
68 | ```solidity
69 | struct SequencedBatchData {
70 | bytes32 accInputHash;
71 | uint64 sequencedTimestamp;
72 | uint64 previousLastBatchSequenced;
73 | }
74 | ```
75 | Where:
76 | - `accInputHash` is the batch’s unique cryptographic fingerprint of the last batch in the sequence
77 | - `sequencedTimestamp` is the timestamp of the block where the sequencing layer 1 transaction is executed
78 | - `previousLastBatchSequenced` is the index of the last sequenced batch before the first batch of the current sequence (i.e., the last batch of the previous sequence)
79 |
80 | The index number of the last batch in the sequence is used as key and the `SequencedBatchData` struct is used as a value for when the sequence is entered into `sequencedBatches` mapping.
81 |
82 | ## BatchData minimal storage
83 | To minimize costly storage operations on layer 1, **storage slots** are primarily employed for sequence commitments. Each slot records two batch indices:
84 | - last batch of the previous sequence as a value of `SequencedBatchData` struct
85 | - last batch of the current sequence as a mapping key
86 | These entries also include the accumulated hash of the last batch in the current sequence and a timestamp.
87 |
88 | Only the accumulated hash of the final batch in the sequence is stored; the others are computed on-demand to reach the last one.
89 |
90 | Batch indices provide additional information about the number of batches in the sequence and their positions. The timestamp marks when the sequence occurred.
91 | The Data Availability of layer 2 transactions is ensured because the data for each batch can be reconstructed from the calldata of the sequencing transaction, which is not part of the contract storage but is recorded in the layer 1 state.
92 | Finally, a `SequenceBatches` event will be emitted:
93 | ```solidity
94 | event SequenceBatches (uint64 indexed numBatch)
95 | ```
96 | Once batches are successfully sequenced on layer 1, all ZKEVM nodes can sync their local layer 2 state directly from the layer 1 `ZkEVM.sol` contract, reducing reliance on the trusted sequencer and reaching the layer 2 virtual state.
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/img/batch-data-flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/xlayer-protocol/img/batch-data-flow.png
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/img/batch-hashes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/xlayer-protocol/img/batch-hashes.png
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/img/consolidated-state-on-l1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/xlayer-protocol/img/consolidated-state-on-l1.png
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/img/fees-and-rewards.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/xlayer-protocol/img/fees-and-rewards.jpg
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/img/l2-state-stages.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/xlayer-protocol/img/l2-state-stages.png
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/img/off-chain-execution-of-batches.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/xlayer-protocol/img/off-chain-execution-of-batches.png
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/img/sequence-of-batches.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/xlayer-protocol/img/sequence-of-batches.png
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/img/transactions-and-data-flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/learn-more/xlayer-protocol/img/transactions-and-data-flow.png
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/incentive-model.mdx:
--------------------------------------------------------------------------------
1 | # Incentive mechanism
2 | In X Layer, actors are rewarded for executing their jobs correctly and helping the protocol achieve finality.
3 |
4 | Unless stated otherwise, the incentive mechanism discussed here applies when the sequencer and aggregator roles are decentralized, meaning there are no trusted sequencers or aggregators involved.
5 |
6 | ## Layer 2 transaction fees and sequencing fees
7 | The native token used in X Layer is `Bridged OKB`, which originates from the Ethereum ERC-20 OKB. This is the token used to pay X Layer transaction fees. It can be bridged at a 1:1 exchange rate from Ethereum to X Layer and vice versa.
8 | The **sequencer** plays a crucial role in the network and receives transaction fees paid by users on X Layer when they submit transactions. These fees are paid in `Bridged OKB`. The exact fee amount depends on the Gas price set by users, indicating how much they are willing to pay for transaction execution.
9 |
10 | To motivate the **aggregator** for each batch it sequences, the **sequencer** is required to lock a specific number of OKB tokens in the layer 1 `ZkEVM.sol` contract. The number of tokens locked per batch is determined by the variable `batchFee`. The final aggregator reward is distributed from `[ZkEVM.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.1/contracts/v2/consensus/validium/PolygonValidiumEtrog.sol "ZkEVM.sol")` in the form of layer 1 OKB tokens.
11 |
12 | The diagram below illustrates the different fees and rewards earned by participants within the protocol.
13 |
14 | 
15 |
16 | X Layer uses the same incentive mechanism — or detailed rewarding formula for sequencers and aggregators, as Polygon ZKEVM does. You can visit [Polygon ZKEVM incentive mechanism](https://wiki.polygon.technology/docs/zkevm/protocol/incentive-mechanism/ "Polygon ZKEVM incentive mechanism") to learn more.
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/state-management.mdx:
--------------------------------------------------------------------------------
1 | # State management
2 | This document aims to explain how the X Layer protocol manages the layer 2 rollup’s states while providing state transition verifiability and security.
3 |
4 | ## Trustless layer 2 state management
5 | The trusted sequencer generates batches for quick layer 2 transaction finality. Instead of waiting for the next layer 1 block, these batches are shared with layer 2 nodes through a broadcast channel. Each node processes the batches locally to compute the layer 2 state.
6 | After the trusted sequencer commits batch sequences from layer 1, layer 2 nodes independently re-execute them, eliminating the need for complete trust. Off-chain batch execution is later verified on-chain using zero-knowledge proofs, and the resulting layer 2 state root is committed. With ZKEVM advancements, layer 2 nodes sync new layer 2 state roots directly from layer 1.
7 |
8 | Data Availability and transaction execution verification are based solely on layer 1 security assumptions. In the protocol’s final stage, nodes depend only on layer 1 data to stay in sync with every layer 2 state change.
9 |
10 | 
11 |
12 | In the diagram above, **layer 2 nodes receive batch data through three methods**:
13 | 1. **From the trusted sequencer**: before batches are committed to layer 1
14 | 2. **Directly from layer 1**: after the batches are sequenced
15 | 3. **After verification**: once execution correctness is proven by the aggregator and verified by the `ZkEVM.sol` contract
16 |
17 | Worth noting, these three batch data formats arrive in the order mentioned above.
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/transaction-validation.mdx:
--------------------------------------------------------------------------------
1 | # Transaction validation
2 | Once the batches have been successfully aggregated on layer 1, all ZKEVM nodes can verify their local layer 2 state by directly retrieving and validating consolidated roots from the layer 1 Consensus Contract ([ZkEVM.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/consensus/validium/PolygonValidiumEtrog.sol "ZKEVM.sol")). This marks the achievement of a consolidated layer 2 state.
3 |
4 | ## Batch rollup verifier
5 | The `rollupVerifier` is an external contract featuring a critical function known as `verifyProof`. This function takes a proof (`proofA`, `proofB`, `proofC`) and an input value called `inputSnark`. It then returns a Boolean value, which is `true` if the proof is valid and false`` if it is not.
6 | Verification of the proof successfully attests to the computation’s integrity. However, it does not guarantee the use of correct inputs or the production of accurate output values. To address this, public arguments are employed to openly disclose crucial aspects of computation under scrutiny. This disclosure proves that the computation was executed using the correct inputs and reveals the outputs.
7 | In the process of proof verification, the layer 1 smart contract configures these public arguments to confirm that the state transition being proven aligns with the execution of batches committed by the trusted sequencer.
8 |
9 | ## Batch inputSnark
10 | The `inputSnark` serves as a 256-bit unique cryptographic representation of a specific layer 2 state transition. It is utilized as a public argument. To calculate it, we take the `sha256 modulo % _RFIELD` hash of a byte string referred to as `snarkHashBytes`. The modulo operator is essential due to the mathematical primitives employed in SNARKs.
11 | The `snarkHashBytes` array is computed through a smart contract function known as `getInputSnarkBytes`. It is an ABI-encoded packed string encompassing the following values:
12 |
13 | |**Variable name**|**Description**|
14 | |:----|:----|
15 | |msg.sender|The address of the trusted aggregator|
16 | |oldStateRoot|The layer 2 state root representing the layer 2 state before the state transition being proven|
17 | |oldAccInputHash|The accumulated hash of the last batch that was aggregated|
18 | |initNumBatch|The index of the last batch that was aggregated|
19 | |chainID|A unique chain identifier|
20 | |newStateRoot|The layer 2 state root represents the layer 2 state after the state transition being proven|
21 | |newAccInputHash|The accumulated hash of the last batch in the sequence being aggregated|
22 | |newLocalExitRoot|The root of the bridge’s layer 2 Exit Merkle tree at the conclusion of sequence execution|
23 | |finalNewBatch|The number of the final batch within the execution range|
24 |
25 | `inputSnark` encapsulates all the layer 2 transactions associated with a specific layer 2 state transition, executed in a specific order, on a specific layer 2 (`chainID`), and validated by a specific trusted aggregator (`msg.sender`).
26 | The `trustedVerifyBatches` function not only verifies the validity of the zero-knowledge proof but also validates that the value of `inputSnark` corresponds to a pending layer 2 state transition scheduled for aggregation.
27 | If the internal call to `_verifyAndRewardBatches` returns `true`, it signifies the successful verification of the sequence of batches. Consequently, the `newStateRoot` argument is added to the `batchNumToStateRoot` mapping. The index of the last batch within the sequence is employed as the key for the entry.
28 | Finally, an event named `TrustedVerifyBatches` is emitted:
29 | ```solidity
30 | event TrustedVerifyBatches (
31 | uint64 indexed numBatch,
32 | bytes32 stateRoot,
33 | address indexed aggregator
34 | );
35 | ```
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/transactions-batching.mdx:
--------------------------------------------------------------------------------
1 | # Transaction batching
2 | ## Rollup or Validium mode
3 | The trusted sequencer must batch the transactions using the following `BatchData` struct specified in the [ZkEVM.sol](https://github.com/okx/xlayer-contracts/blob/release/v0.3.0/contracts/v2/consensus/validium/PolygonValidiumEtrog.sol "ZKEVM.sol") contract:
4 | ```solidity
5 | struct BatchData {
6 | bytes transactions;
7 | bytes32 transactionsHash;
8 | bytes32 globalExitRoot;
9 | uint64 timestamp;
10 | uint64 minForcedTimestamp;
11 | }
12 | ```
13 | The trusted sequencer can choose [Rollup or Validium](https://ethereum.org/en/developers/docs/data-availability/ "Rollup or Validium") mode when invoking the `sequenceBatches` method.
14 | ```solidity
15 | function sequenceBatches(
16 | BatchData[] calldata batches,
17 | address l2Coinbase,
18 | bytes calldata signaturesAndAddrs
19 | )
20 | ```
21 | - **Rollup**: `BatchData.transactions` data is set using the data from [transactions](#Transactions), while the `signaturesAndAddrs` field is empty.
22 | - **Validium**: The hash calculated based on the [transactions](#Transactions) is set as `BatchData.transactionsHash`. [Transactions](#Transactions) data is signed using the DAC private key from `DataCommittee.sol`, and the resulting signatures are set in the `signaturesAndAddrs` field.
23 |
24 | ## Batch data parameters
25 | ### Transactions
26 | These are byte arrays containing the concatenated batch transactions for rollup mode.
27 | Each transaction is encoded according to the Ethereum pre-EIP-155 or EIP-155 formats using the Recursive-Length Prefix (RLP) standard, but the signature values, `v`,` r`, and `s`, are concatenated as shown below:
28 | 1. `EIP-155`: `rlp(nonce, gasprice, gasLimit, to, value, data, chainid, 0, 0,)`
29 | 2. `pre-EIP-155`: `rlp(nonce,gasprice,gasLimit,to,value,data)`
30 |
31 | ### GlobalExitRoot
32 | This is the **root of the bridge’s Global Exit Merkle Tree**, which will be synchronized in the layer 2 State at the start of batch execution.
33 | The bridge moves assets back and forth between layer 1 and layer 2. To access the assets on the destination network, you need to complete a claiming transaction.
34 |
35 | ### Timestamp
36 | As Ethereum blocks have timestamps, each batch also has its own timestamp.
37 | To make sure batches are arranged in chronological order and align with layer 1 blocks, two conditions must be met:
38 | 1. The timestamp of a batch must be equal to or later than the timestamp of the last batch that was sequenced.
39 | 2. A trusted sequencer can’t assign a batch with a timestamp greater than the timestamp of the layer 1 block, where the sequencing transaction is processed.
40 |
41 | ### MinForcedTimestamp
42 | If a batch is a so-called forced batch, this parameter must be greater than zero. Censorship is countered by using forced batches. You can learn more about this in the next section - [Batch Sequencing](/developer/learn-more/xlayer-protocol/batch-sequencing "Batch Sequencing").
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/transactions-n-data-flow.mdx:
--------------------------------------------------------------------------------
1 | # Transactions and data flow
2 | The process of validating a specific transaction within the batch typically involves three steps:
3 | 1. **Trusted state**: This state is given by the trusted sequencer almost instantaneously. The state is updated on layer 2, but has not yet reached layer 1.
4 | 2. **Virtual state**: Batches have been sequenced and data is on layer 1. At this point, transactions and data can not be modified as the state is final, yet they are not yet proven and are available on layer 1 for anyone to prove.
5 | 3. **Verified state**: ZK-proof has been posted on layer 1, and the smart contract verifies the virtual state, allowing for the withdrawal of funds.
6 |
7 | 
8 |
9 | ## Data flow in X Layer
10 | Transactions on the X Layer network have a typical flow starting from the users’ interactions with their wallet on X Layer, to how the transactions are batched, sequenced, and aggregated on Ethereum layer 1:
11 | 1. Transactions are submitted to X Layer.
12 | 2. Transactions are executed almost instantly.
13 | 3. Transactions are batched together using data encryption methods.
14 | 4. Batches are sequenced and sent to Ethereum layer 1.
15 | 5. Consolidated finality is achieved on Ethereum layer 1 with the power of ZK-proofs.
16 |
17 | 
18 |
19 | ### 1. Submitting transactions
20 | As a user, you submit transactions by signing transactions and sending them through the JSON-RPC interface.
21 |
22 | ### 2. Executing transactions
23 | The transactions are then stored in the pending transaction pool, where the sequencer node running the ZKEVM software picks these transactions up and decides which ones it wants to process or discard.
24 | The sequencer will do a few of the following checks to see if the transaction should be discarded or processed:
25 | 1. If the sender has sufficient funds to complete the transaction
26 | 2. If the smart contract called actually exists and contains valid bytecode
27 | 3. If the transaction is not a duplicate
28 | 4. If the transaction does not involve a "double-spend", which means the sender’s funds have not already been used in another transaction
29 |
30 | Once the transaction is considered valid, the sequencer will update the X Layer state. Users will experience transactions going through almost instantly.
31 | From here onwards, the user remains engaged in the X Layer layer 2 state. Everything that follows involves sharing transaction data back to Ethereum layer 1, but this step is only important for users who wish to transfer their funds from X Layer layer 2 back to Ethereum layer 1.
32 |
33 | ### 3. Batching transactions
34 | The sequencer combines multiple transactions into a single batch and sends them to the `ZkEVM.sol` smart contract. This contract is stored on Ethereum mainnet and also has a separate version on the Ethereum Sepolia testnet.
35 | Batches are not necessarily validated or confirmed at this stage.
36 |
37 | ### 4. Verifying transactions
38 | Using ZKPs, the `ZkEVM.sol` smart contract acts as a verifier in verifying transactions. It verifies whether the batch just received is valid or not, through sending the batch to an aggregator node.
39 |
40 | ### 5. Generating & verifying zk-proofs/validity proofs
41 | The `ZkEVM.sol` smart contract sends the batch it just received to an aggregator node, which is a machine running ZKEVM software that communicates with a ZKProver. The flow is as follows:
42 | - The aggregator receives the batch from the smart contract
43 | - The aggregator sends the batch to the ZKProver
44 | - The ZKProver creates multiple ZK-STARKs -> a single ZK-STARK -> a ZK-SNARK
45 | - The ZK-SNARK (the validity proof) gets sent back to the aggregator
46 | - The aggregator sends back the validity proof to the `ZkEVM.sol` smart contract
47 | - `ZkEVM.sol` verifies the validity proof
48 | - If the validity proof is valid, accept it
49 | - If it is not valid, reject it
50 |
51 | ### 6. Reading events on X Layer
52 | Finally, DApps read information from X Layer through the synchronizer.
53 | It reads events from the Ethereum smart contract(s), storing knowledge of both the ZK-validity proofs from the aggregator, and the batches submitted from the sequencer.
54 | This way, DApps can easily get a view of the state of X Layer via JSON-RPC.
55 |
56 | To find answers to more transaction-related questions, you can visit [Polygon’s zkEVM protocol FAQ](https://wiki.polygon.technology/docs/zkevm/faq/zkevm-protocol-faq/ "Polygon’s ZKEVM protocol FAQ") for more info.
--------------------------------------------------------------------------------
/developer/learn-more/xlayer-protocol/transactions.mdx:
--------------------------------------------------------------------------------
1 | # Transactions
2 |
3 |
--------------------------------------------------------------------------------
/developer/oracle/best-practices.mdx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/oracle/best-practices.mdx
--------------------------------------------------------------------------------
/developer/oracle/direct-funding-method.mdx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/oracle/direct-funding-method.mdx
--------------------------------------------------------------------------------
/developer/oracle/feed-registry.mdx:
--------------------------------------------------------------------------------
1 | # Feed registry
2 |
3 | ## XLayerFeedRegistry
4 | An-on chain mapping of asset pairs to aggregators, allowing for fetching various asset prices through a single contract._createMdxContent
5 |
6 | ## IXLayerFeedRegistry
7 | - Includes batch view functions based on base-quote pairs
8 | - Includes IFeedRegistry listed below.
9 |
10 | ```
11 | // SPDX-License-Identifier: MIT
12 | pragma solidity ^0.8.20;
13 |
14 | interface IXLayerFeedRegistry is IFeedRegistry {
15 | //Batch view related queries
16 | function fetchRange(
17 | address base,
18 | address quote,
19 | uint80 startId,
20 | uint80 endId
21 | )
22 | external
23 | view
24 | returns (
25 | uint80[] memory roundId,
26 | int256[] memory answer,
27 | uint256[] memory startedAt,
28 | uint256[] memory updatedAt,
29 | uint80[] memory answeredInRound
30 | );
31 |
32 | function fetchLastEntries(
33 | address base,
34 | address quote,
35 | uint80 count
36 | )
37 | external
38 | view
39 | returns (
40 | uint80[] memory roundId,
41 | int256[] memory answer,
42 | uint256[] memory startedAt,
43 | uint256[] memory updatedAt,
44 | uint80[] memory answeredInRound
45 | );
46 | }
47 | ```
48 |
49 | |Function|Permission|Description|
50 | |:----|:----|:----|
51 | |fetchRange|-|1. Provide a range of entries in ascending order based on `startId` and `endId`, and base-quote pair.
2. Results include both `startId` and `endId`.|
52 | |fetchLastEntries|-|1. Provides a range of entries in ascending order based on `count` and base-quote pair.
2. Total number of entries returned will be counted, and includes the last entry.|
53 |
54 | ## IFeedRegistry
55 |
56 | - Exposes AggregatorV2V3 type view functions that support base-quote pair routing to the appropriate aggregator
57 | - Supports updating of feeds for base-quote pairs
58 |
59 | ```
60 | // SPDX-License-Identifier: MIT
61 | pragma solidity ^0.8.20;
62 |
63 | interface IFeedRegistry {
64 | //reusing the chainlink event, in case certain legacy systems rely on this
65 | event FeedConfirmed(
66 | address indexed asset,
67 | address indexed denomination,
68 | address indexed latestAggregator,
69 | address previousAggregator,
70 | uint16 nextPhaseId,
71 | address sender
72 | );
73 |
74 | // V3 AggregatorV3Interface
75 | function decimals(
76 | address base,
77 | address quote
78 | ) external view returns (uint8);
79 |
80 | function description(
81 | address base,
82 | address quote
83 | ) external view returns (string memory);
84 |
85 | function version(
86 | address base,
87 | address quote
88 | ) external view returns (uint256);
89 |
90 | function latestRoundData(
91 | address base,
92 | address quote
93 | )
94 | external
95 | view
96 | returns (
97 | uint80 roundId,
98 | int256 answer,
99 | uint256 startedAt,
100 | uint256 updatedAt,
101 | uint80 answeredInRound
102 | );
103 |
104 | function getRoundData(
105 | address base,
106 | address quote,
107 | uint80 _roundId
108 | )
109 | external
110 | view
111 | returns (
112 | uint80 roundId,
113 | int256 answer,
114 | uint256 startedAt,
115 | uint256 updatedAt,
116 | uint80 answeredInRound
117 | );
118 |
119 | // V2 AggregatorInterface
120 | function latestAnswer(
121 | address base,
122 | address quote
123 | ) external view returns (int256 answer);
124 |
125 | function latestTimestamp(
126 | address base,
127 | address quote
128 | ) external view returns (uint256 timestamp);
129 |
130 | function latestRound(
131 | address base,
132 | address quote
133 | ) external view returns (uint256 roundId);
134 |
135 | function getAnswer(
136 | address base,
137 | address quote,
138 | uint256 roundId
139 | ) external view returns (int256 answer);
140 |
141 | function getTimestamp(
142 | address base,
143 | address quote,
144 | uint256 roundId
145 | ) external view returns (uint256 timestamp);
146 |
147 | // Registry getters
148 |
149 | function getFeed(
150 | address base,
151 | address quote
152 | ) external view returns (IXLayerOffchainAggregator aggregator);
153 |
154 | function getPhaseFeed(
155 | address base,
156 | address quote,
157 | uint16 phaseId
158 | ) external view returns (IXLayerOffchainAggregator aggregator);
159 |
160 | function isFeedEnabled(address aggregator) external view returns (bool);
161 |
162 | function getRoundFeed(
163 | address base,
164 | address quote,
165 | uint80 roundId
166 | ) external view returns (IXLayerOffchainAggregator aggregator);
167 |
168 | function getPhaseRange(
169 | address base,
170 | address quote,
171 | uint16 phaseId
172 | ) external view returns (uint80 startingRoundId, uint80 endingRoundId);
173 |
174 | function getPreviousRoundId(
175 | address base,
176 | address quote,
177 | uint80 roundId
178 | ) external view returns (uint80 previousRoundId);
179 |
180 | function getNextRoundId(
181 | address base,
182 | address quote,
183 | uint80 roundId
184 | ) external view returns (uint80 nextRoundId);
185 |
186 | // Feed management
187 |
188 | function updateFeed(
189 | address base,
190 | address quote,
191 | address aggregator
192 | ) external;
193 |
194 | // Phases
195 | function getCurrentPhaseId(
196 | address base,
197 | address quote
198 | ) external view returns (uint16 currentPhaseId);
199 | }
200 | ```
201 | |Function|Permission|Description|
202 | |:----|:----|:----|
203 | |decimals|-|Number of decimals present in the response|
204 | |description|-|Description of the underlying aggregator |
205 | |version|-|Version number of the aggregator. Increases each time the contract is upgraded|
206 | |getRoundData|-|Retrieves data for a specific roundId. Reverts if it does not fall in the range of the current aggregator,|
207 | |latestRoundData|-|Retrieves data from the latest round.|
208 | |latestAnswer|-|Retrieves price from latest round.|
209 | |latestTimestamp|-|Retrieves timestamp from latest round.|
210 | |latestRound|-|Retrieves latest roundid.|
211 | |getAnswer|-|Retrieves price for a specific roundId. Reverts if it does not fall in the range of the current aggregator.|
212 | |getTimestamp|-|Retrieves price for a specific roundId. Reverts if it does not fall in the range of the current aggregator.|
213 | |getFeed|-|Retrieves the current aggregator for the pair.|
214 | |getPhaseFeed|-|1. Retrieves the aggregator based on the phase specified.
2. Reverts if phase specified is < 1|
215 | |isFeedEnabled|-|Returns a bool to indicate whether aggregator is active.|
216 | |getPhaseRange|-|1. Returns the aggregator for a particular base-quote pair.
2. Reverts if phase specified is < 1|
217 | |getRoundFeed|-|Returns the previous roundId if it falls within the range of the aggregator. Reverts if it is invalid.|
218 | |getNextRoundId|-|Returns the next roundId if it falls within the range of the aggregator. Reverts if it is invalid.|
219 | |updateFeed|Owner|Updates the aggregator for a base quote pair if the following conditions are met:
1. Addresses are not 0.
2. New aggregator is not the same as the current.
3. Base and quote are not the same address emits FeedConfired when successful.|
220 | |getCurrentPhaseId|-|Retrieves the latest round from the specified base-quote pair and returns the phase.|
--------------------------------------------------------------------------------
/developer/oracle/offchain-aggregator.mdx:
--------------------------------------------------------------------------------
1 | # Offchain aggregator
2 |
3 | ## IXLayerOffchainAggregator
4 | A dedicated price feed for an asset pair, which comes with batch viewing capabilities._createMdxContent
5 |
6 | ## XLayerOffchainAggregator
7 | - Includes batch view functions
8 | - Includes `IAggregator`, `IConfig` and `IExternalValidator` which are listed below
9 |
10 | ```
11 | // SPDX-License-Identifier: MIT
12 | pragma solidity ^0.8.20;
13 |
14 | interface IXLayerOffchainAggregator is
15 | IAggregator,
16 | IExternalValidator,
17 | IConfig
18 | {
19 | //Batch view related queries
20 | function fetchRange(
21 | uint80 startId,
22 | uint80 endId
23 | )
24 | external
25 | view
26 | returns (
27 | uint80[] memory roundId,
28 | int256[] memory answer,
29 | uint256[] memory startedAt,
30 | uint256[] memory updatedAt,
31 | uint80[] memory answeredInRound
32 | );
33 |
34 | function fetchLastEntries(
35 | uint80 count
36 | )
37 | external
38 | view
39 | returns (
40 | uint80[] memory roundId,
41 | int256[] memory answer,
42 | uint256[] memory startedAt,
43 | uint256[] memory updatedAt,
44 | uint80[] memory answeredInRound
45 | );
46 | }
47 | ```
48 |
49 | |Function|Permission|Description|
50 | |:----|:----|:----|
51 | |fetchRange|-|1. Provide a range of entries in ascending order based on `startId` and `endId`
2. Results include both `startId` and `endId`.|
52 | |fetchLastEntries|-|1. Provides a range of entries in ascending order based on `count`.
2. Total number of entries returned will be counted, and includes the last entry.|
53 |
54 | ## IAggregator
55 | This is a Chainlink compatible interface for retrieving asset prices on contracts. It supports both AggregatorV3 (latest) and AggregatorV2 (deprecated).
56 |
57 | ```
58 | // SPDX-License-Identifier: MIT
59 | pragma solidity ^0.8.20;
60 |
61 | interface IAggregator {
62 | event AnswerUpdated(
63 | int256 indexed current,
64 | uint256 indexed roundId,
65 | uint256 updatedAt
66 | );
67 | event NewRound(
68 | uint256 indexed roundId,
69 | address indexed startedBy,
70 | uint256 startedAt
71 | );
72 |
73 | struct Transmission {
74 | int192 answer; // 192 bits ought to be enough for anyone
75 | uint64 timestamp;
76 | }
77 |
78 | struct HotVars {
79 | bytes16 latestConfigDigest; //rewrote as bytes16(keccak256(abi.encode(implAddr, description, version, min, max)))
80 | uint80 latestAggregatorRoundId;
81 | }
82 |
83 | // AggregatorV3Interface
84 | function decimals() external view returns (uint8);
85 |
86 | function description() external view returns (string memory);
87 |
88 | function version() external view returns (uint256);
89 |
90 | function getRoundData(
91 | uint80 _roundId
92 | )
93 | external
94 | view
95 | returns (
96 | uint80 roundId,
97 | int256 answer,
98 | uint256 startedAt,
99 | uint256 updatedAt,
100 | uint80 answeredInRound
101 | );
102 |
103 | function latestRoundData()
104 | external
105 | view
106 | returns (
107 | uint80 roundId,
108 | int256 answer,
109 | uint256 startedAt,
110 | uint256 updatedAt,
111 | uint80 answeredInRound
112 | );
113 |
114 | // AggregatorV2Interface
115 | function latestAnswer() external view returns (int256);
116 |
117 | function latestTimestamp() external view returns (uint256);
118 |
119 | function latestRound() external view returns (uint256);
120 |
121 | function getAnswer(uint256 roundId) external view returns (int256);
122 |
123 | function getTimestamp(uint256 roundId) external view returns (uint256);
124 | }
125 | ```
126 |
127 | |Function|Permission|Description|
128 | |:----|:----|:----|
129 | |decimals|-|Number of decimals present in the response|
130 | |description|-|Description of the underlying aggregator |
131 | |version|-|Version number of the aggregator. Increases each time the contract is upgraded|
132 | |getRoundData|-|Retrieves data for a specific roundId. Reverts if it does not fall in the range of the current aggregator,|
133 | |latestRoundData|-|Retrieves data from the latest round.|
134 | |latestAnswer|-|Retrieves price from latest round.|
135 | |latestTimestamp|-|Retrieves timestamp from latest round.|
136 | |latestRound|-|Retrieves latest roundid.|
137 | |getAnswer|-|Retrieves price for a specific roundId. Reverts if it does not fall in the range of the current aggregator.|
138 | |getTimestamp|-|Retrieves price for a specific roundId. Reverts if it does not fall in the range of the current aggregator.|
139 |
140 | ## IConfig
141 | It retrieves the latest config details, and updates bounds of minimum and maximum price updates.
142 |
143 | ```
144 | // SPDX-License-Identifier: MIT
145 | pragma solidity ^0.8.20;
146 |
147 | interface IConfig {
148 | event UpdatedConfig(uint256 indexed version, bytes16 configDigest);
149 |
150 | function updateLowerBound(int192 newMinAnswer) external;
151 |
152 | function updateUpperBound(int192 newMaxAnswer) external;
153 |
154 | function latestConfigDetails() external view returns (bytes16 configDigest);
155 | }
156 |
157 | ```
158 | |Function|Permission|Description|
159 | |:----|:----|:----|
160 | |updateLowerBound|Owner|Updates the minimum price that can be transmitted to this aggregator. If valid, will trigger an update for configdigest and emit UpdatedConfig.|
161 | |updateUpperBound|Owner|Updates the maximum price that can be transmitted to this aggregator. If valid, will trigger an update for configdigest and emit UpdatedConfig.|
162 | |latestConfigDetails|-|Retrieves the current configdigest|
163 |
164 | ## IExternalValidator
165 | This is used for updating the external validator configuration, which will be triggered as a callback during price update.
166 |
167 | ```
168 | // SPDX-License-Identifier: MIT
169 | pragma solidity ^0.8.20;
170 |
171 | interface IExternalValidator {
172 | struct ValidatorConfig {
173 | AggregatorValidatorInterface validator;
174 | uint32 gasLimit;
175 | }
176 |
177 | event ValidatorConfigSet(
178 | AggregatorValidatorInterface indexed previousValidator,
179 | uint32 previousGasLimit,
180 | AggregatorValidatorInterface indexed currentValidator,
181 | uint32 currentGasLimit
182 | );
183 |
184 | function validatorConfig()
185 | external
186 | view
187 | returns (AggregatorValidatorInterface validator, uint32 gasLimit);
188 |
189 | function setValidatorConfig(
190 | AggregatorValidatorInterface _newValidator,
191 | uint32 _newGasLimit
192 | ) external;
193 | }
194 |
195 | interface AggregatorValidatorInterface {
196 | function validate(
197 | uint256 previousRoundId,
198 | int256 previousAnswer,
199 | uint256 currentRoundId,
200 | int256 currentAnswer
201 | ) external returns (bool);
202 | }
203 | ```
204 | |Function|Permission|Description|
205 | |:----|:----|:----|
206 | |validatorConfig|-|Retrieves the current validator confi
207 | |setValidatorConfig|Owner|1. Updates validator config if Validator address changes OR Gas allocated is changed.
2. Emits ValidatorConfigSet if update is successful.|
--------------------------------------------------------------------------------
/developer/oracle/price-feed-interface.mdx:
--------------------------------------------------------------------------------
1 | # Price feed interface
2 |
3 |
--------------------------------------------------------------------------------
/developer/oracle/security-considerations.mdx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/oracle/security-considerations.mdx
--------------------------------------------------------------------------------
/developer/oracle/subscription-method.mdx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/oracle/subscription-method.mdx
--------------------------------------------------------------------------------
/developer/oracle/vrf.mdx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/oracle/vrf.mdx
--------------------------------------------------------------------------------
/developer/setup-zknode/setup-local-zknode.mdx:
--------------------------------------------------------------------------------
1 | # Setup local ZKNode
2 | It’s crucial that developers can thoroughly test the network for a developing blockchain technology like X Layer ZKEVM without putting users or themselves at unnecessary risk. Developers should be able to test their smart contracts, experiment with new code, and play around with the network on their local machines.
3 | X Layer ZKEVM has a local development environment setup for this reason. This tutorial will help you create a local single-node ZKEVM blockchain with no connections to external peers. It only exists on your local machine.
4 |
5 | Currently the ZKProver does not run on ARM-powered Macs. For Windows users, using WSL/WSL2 is not recommended. Unfortunately, Apple M1 chips are not supported for now - since some optimizations on the ZKProver require specific Intel instructions. This means some non-M1 computers won’t work regardless of the OS, for example: AMD.
6 |
7 | After completing this tutorial, you will have the following components running:
8 | - ZKEVM node databases
9 | - Explorer databases
10 | - Layer 1 network
11 | - Prover
12 | - ZKEVM node components
13 | - Explorers
14 |
15 | ## Prerequisites
16 | The tutorial for current version of the environment requires `Foundryup`, `go`, `docker` and `docker-compose` to be previously installed on your machine. If you don’t have these installed, check out the links provided below:
17 | - https://book.getfoundry.sh/getting-started/installation
18 | - https://go.dev/doc/install
19 | - https://www.docker.com/get-started
20 | - https://docs.docker.com/compose/install/
21 |
22 | ### System requirements
23 | - ZKEVM node: 16GB RAM with 4-core CPU
24 | - Mock ZKProver (Default): 16GB RAM with 4-core CPU
25 | - Full ZKProver: 1TB RAM with 128-core CPU
26 |
27 | If you want to run a full-fledged ZKProver on your own, you’ll need at least 1TB of RAM. If you are unable to meet the Prover requirements, you can still run the zkNode.
28 |
29 | ## Setup ZKNode
30 | Before starting the ZKEVM node setup, we need to clone the [official ZKNode repository](https://github.com/okx/xlayer-node "official ZKNode repository") from xlayer-node Github.
31 |
32 | ```bash
33 | git clone -b release/v0.3.0 https://github.com/okx/xlayer-node.git
34 | cd xlayer-node
35 | ```
36 |
37 | The `xlayer-node` docker image must be built at least once and whenever the code is changed. If you haven’t already built the `xlayer-node` image, you must run:
38 | ```bash
39 | make build-docker
40 | ```
41 |
42 | Certain commands on the `xlayer-node` can interact with smart contracts, run specific components, create encryption files, and print debug information.
43 | To interact with the binary program, we provide `docker-compose` files and a `Makefile` to spin up/down the various services and components, ensuring smooth local deployment and a better command line interface for developers.
44 |
45 | All the data is stored inside of each docker container. This means once you remove the container, the data will be lost.
46 |
47 | The `test/` directory contains scripts and files for developing and debugging. Change the working directory to `test/` on your local machine.
48 | ```bash
49 | cd test/
50 | ```
51 | Now, run the ZKNode environment:
52 | ```bash
53 | make run
54 | ```
55 | To stop the ZKNode:
56 | ```bash
57 | make stop
58 | ```
59 | To restart the whole ZKNode environment:
60 | ```bash
61 | make restart
62 | ```
63 |
64 | ## Configuration parameters
65 | The Synchronizer regularly pulls for network updates, mainly from Ethereum but also via the Trusted Sequencer’s broadcasting mechanism, in order to stay up-to-date. Unless otherwise specified in the setup, the Synchronizer’s default syncing rate is every 2 seconds.
66 | The Keystore file, used to store private keys, is normally required for running the Sequencer & Aggregator but not for a Synchronizer/RPC-setup.
67 |
68 | We have the inconvenient situation where the Keystore file is required to run the node when it shouldn’t be, for example, if no transactions are sent to layer 1. Keystore is not required in the Mango Testnet as it uses a trusted sequencer and aggregator.
69 | This will be reviewed when a decentralised ZKEVM network is implemented.
70 |
71 | ## Sample data
72 | It’s important to populate your local ZKEVM node with some data before you start testing out the network. The `make run` command will execute the containers required to run the environment, but it will not execute anything else. Your local layer 2 network will be essentially empty.
73 | The following scripts are available if you require sample data that has already been deployed to the network.
74 | ```bash
75 | cast send --legacy --from 0x2ECF31eCe36ccaC2d3222A303b1409233ECBB225 --private-key 0xde3ca643a52f5543e84ba984c4419ff40dbabd0e483c31c1d09fee8168d68e38 --rpc-url http://127.0.0.1:8123 0xC949254d682D8c9ad5682521675b8F43b102aec4 --value 10ether
76 |
77 | # To add some examples of transactions and smart contracts:
78 | make deploy-sc
79 |
80 | # To deploy a full Uniswap environment:
81 | make deploy-uniswap
82 |
83 | # To grant the OKB smart contract a set amount of tokens:
84 | make run-approve-matic
85 | ```
86 |
87 | ## Connecting to Metamask
88 | Metamask requires the network to be running while configuring it, so make sure your network is up.
89 |
90 | To configure your MetaMask to use your local ZKEVM environment, follow these steps:
91 |
92 | 1. Log in to your MetaMask wallet.
93 | 2. Click on your account picture and then on Settings.
94 | 3. On the left menu, click on **Networks**.
95 | 4. Click on **Add Network** button.
96 | 5. Fill in the layer 2 network information:
97 | - Network Name: X Layer zkEVM - Local
98 | - New RPC URL: http://localhost:8123
99 | - ChainID: 1001
100 | - Currency Symbol: OKB
101 | - Block Explorer URL: http://localhost:4000
102 | 6. Click on **Save**.
103 | 7. Click on **Add Network** button.
104 | 8. Fill in the layer 1 network information:
105 | - Network name: Geth - Local
106 | - New RPC URL: http://localhost:8545
107 | - ChainID: 1337
108 | - Currency symbol: ETH
109 | 9. Click on **Save**.
110 |
111 | You can now interact with your local ZKEVM network and sign transactions from your MetaMask wallet.
--------------------------------------------------------------------------------
/developer/setup-zknode/setup-production-zknode.mdx:
--------------------------------------------------------------------------------
1 | # Setup production ZKNode
2 | X Layer is now available on the Mainnet and Testnet for developers to launch smart contracts, execute transactions, and experiment with the network. This tutorial extends the exploration by allowing developers to launch their own node on the Public network.
3 | Before we begin, this document is fairly technical and requires prior exposure to Docker and CLI. Post spinning up your ZKNode instance, you will be able to run the Synchronizer and utilize the JSON-RPC interface.
4 |
5 | ## Prerequisites
6 | This tutorial assumes that you have docker-compose already installed. If you need any help with the installation, please check the [official docker-compose installation guide](https://docs.docker.com/compose/install/).
7 |
8 | ### Minimum System requirements
9 | ZKProver does not work on ARM-based Macs yet, and using WSL/WSL2 on Windows is not advisable. Currently, ZKProver optimizations require CPUs that support the AVX2 instruction, which means some non-M1 computers, such as AMD, won’t work with the software regardless of the OS.
10 |
11 | - 16GB RAM
12 | - 4-core CPU
13 | - 1 TB Storage (This will increase over time)
14 |
15 | ### Network components
16 | Here is a list of crucial network components that are required before you can run the ZKNode:
17 | - Ethereum Node - Use geth or any service providing a JSON RPC interface for accessing the layer 1 network
18 | - X Layer-Node (or ZKNode) - layer 2 network
19 | - Synchronizer - Responsible for synchronizing data between layer 1 and layer 2
20 | - JSON RPC Server - Interface to layer 2 network
21 | - State DB - Save the layer 2 account, block and tx data.
22 |
23 | Let’s set up each of the above components!
24 |
25 | ## Ethereum node setup
26 | The Ethereum RPC Node is the first component to be deployed because ZKNode needs to synchronize blocks and transactions on layer 1. You can invoke the ETH RPC (Mainnet: Ethereum OR Testnet: Sepolia) service through any of the following methods:
27 | - Third-party RPC services, such as [Infura](https://www.infura.io/) or [Ankr](https://www.ankr.com/).
28 | - Set up your own Ethereum node. Follow the instructions provided in this [guide to set up and install Geth](https://geth.ethereum.org/docs/getting-started/installing-geth).
29 |
30 | ## Installing
31 | Once the layer 1 RPC component is complete, we can start the ZKNode setup. This is the most straightforward way to run a ZKNode and it’s fine for most use cases.
32 | Furthermore, this method is purely subjective and feel free to run this software in a different manner. For example, Docker is not required, you could simply use the Go binaries directly.
33 | Let’s start setting up our ZKNode:
34 |
35 | 1. Download the installation script
36 | ``` bash
37 | mkdir -p ./xlayer-node && cd ./xlayer-node
38 |
39 | # mainnet
40 | wget https://static.okex.org/cdn/chain/xlayer/snapshot/run_xlayer_mainnet.sh && chmod +x run_xlayer_mainnet.sh && ./run_xlayer_mainnet.sh init && cp ./mainnet/example.env ./mainnet/.env
41 |
42 | # testnet
43 | wget https://static.okex.org/cdn/chain/xlayer/snapshot/run_xlayer_testnet.sh && chmod +x run_xlayer_testnet.sh && ./run_xlayer_testnet.sh init && cp ./testnet/example.env ./testnet/.env
44 | ```
45 |
46 | 2. The example.env file must be modified according to your configurations. Edit the .env file with your favourite editor (we’ll use vim in this guide):
47 |
48 | ``` bash
49 | # mainnet
50 | vim ./mainnet/.env
51 |
52 | # testnet
53 | vim ./testnet/.env
54 | ```
55 |
56 | ``` bash
57 | # URL of a JSON RPC for Ethereum mainnet or Sepolia testnet
58 | XLAYER_NODE_ETHERMAN_URL = "http://your.L1node.url"
59 |
60 | # PATH WHERE THE STATEDB POSTGRES CONTAINER WILL STORE PERSISTENT DATA
61 | XLAYER_NODE_STATEDB_DATA_DIR = "./xlayer_mainnet_data/statedb" # OR ./xlayer_testnet_datastatedb/ for testnet
62 |
63 | # PATH WHERE THE POOLDB POSTGRES CONTAINER WILL STORE PERSISTENT DATA #
64 | XLAYER_NODE_POOLDB_DATA_DIR = "./xlayer_mainnet_data/pooldb" # OR ./xlayer_testnet_data/pooldb/ for testnet
65 | ```
66 |
67 | 3. Restore the latest layer 2 snapshot locally database for synchronizing layer 2 data quickly.
68 | ``` bash
69 | # mainnet
70 | ./run_xlayer_mainnet.sh restore
71 |
72 | # testnet
73 | ./run_xlayer_testnet.sh restore
74 | ```
75 |
76 | ## Starting
77 | Use the below command to start the ZKNode instance:
78 | ``` bash
79 |
80 | # mainnet
81 | ./run_xlayer_mainnet.sh start
82 |
83 | # testnet
84 | ./run_xlayer_testnet.sh start
85 |
86 | docker ps -a
87 | ```
88 |
89 | You will see a list of the following containers :
90 | - xlayer-rpc
91 | - xlayer-sync
92 | - xlayer-state-db
93 | - xlayer-pool-db
94 | - xlayer-prover
95 |
96 | You should now be able to run queries to the JSON-RPC endpoint at http://localhost:8545.
97 | Run the following query to get the most recently synchronized layer 2 block; if you call it every few seconds, you should see the number grow:
98 | ``` bash
99 | curl -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":83}' http://localhost:8545
100 | ```
101 |
102 | ## Stopping
103 | Use the below command to stop the ZKNode instance:
104 | ``` bash
105 | # mainnet
106 | ./run_xlayer_mainnet.sh stop
107 |
108 | # testnet
109 | ./run_xlayer_testnet.sh stop
110 | ```
111 |
112 | ## Restarting
113 | Use the below command to stop the ZKNode instance:
114 | ``` bash
115 | # mainnet
116 | ./run_xlayer_mainnet.sh restart
117 |
118 | # testnet
119 | ./run_xlayer_testnet.sh restart
120 | ```
121 | ## Updating
122 | To update the ZKNode software, run the below command, and the file ```./mainnet(or testnet)/.env``` will be retained, the other config will be deleted.
123 | ``` bash
124 | # mainnet
125 | ./run_xlayer_mainnet.sh update
126 |
127 | # testnet
128 | ./run_xlayer_testnet.sh update
129 | ```
130 |
131 | ## Troubleshooting
132 | - It’s possible that the machine you’re using already uses some of the necessary ports. In this case, you can change them directly ```./mainnet(testnet)/docker-compose.yml```.
133 | - If one or more containers are crashing, please check the logs using the command below:
134 | ``` bash
135 | docker ps -a
136 |
137 | docker logs
138 | ```
139 |
140 | ## Force resync From specific batch
141 |
142 | 1. Stop xlayer-sync and xlayer-rpc services
143 | ``` bash
144 | docker stop xlayer-sync
145 | docker stop xlayer-rpc
146 | ```
147 | 2. Select max verified batch
148 | ``` bash
149 | PGPASSWORD=state_password psql -h 127.0.0.1 -p 5432 -d state_db -U state_user
150 |
151 | SELECT max(batch_num) FROM state.verified_batch;
152 | # Use the batch_num above to perform the resync from a specific batch (e.g. 330000):
153 | ```
154 |
155 | 3. Look for the target block and batch to delete
156 | - Look for this batch in [OK Link](https://www.oklink.com/xlayer-test/batch/330000 "OK Link")
157 | and get "Sequence Tx Hash" value (0xf5bcff8bc5e03be47e36d642d26f0551ff4a66094e1fb67c9e02ec739c7fca82)
158 | - Go to previous batches (you can use "\<" button) until you reach the first batch sequenced with the same "Sequence Tx Hash" (in this example **329992**).
159 | - Look for the "Sequence Tx Hash" in [etherscan](https://sepolia.etherscan.io/tx/0xf5bcff8bc5e03be47e36d642d26f0551ff4a66094e1fb67c9e02ec739c7fca82 "Sequence Tx Hash") to get the layer 1 block where that tx was confirmed (in this example **5517146**).
160 | 4. Delete the block and batch
161 | ``` bash
162 | delete from state.block where block_num >= 5517146;
163 | delete from state.batch where batch_num >= 329992;
164 | ```
165 | 5. Start the sync service to sync again.
--------------------------------------------------------------------------------
/developer/smart-contract/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zikc2023/xlayer-docs/962df6dec4ac5931c1c943d654df3bb8981dc5a0/developer/smart-contract/.DS_Store
--------------------------------------------------------------------------------
/developer/smart-contract/deploy-with-foundry.mdx:
--------------------------------------------------------------------------------
1 | # Deploying with Foundry
2 | In this tutorial, we explain step-by-step how to create, compile and deploy a simple smart contract on the X Layer testnet using Foundry.
3 |
4 | ## What is Foundry
5 | [Foundry](https://github.com/foundry-rs/foundry "Foundry") offers a complete set of tools for building and deploying decentralized applications (DApps) on the Ethereum blockchain. Utilizing Foundry, you can write smart contracts using the Solidity programming language, compile, deploy, and interact on the Ethereum blockchain.
6 |
7 | ## Setting up the development environment
8 | - [Node.js V18+ LTS and npm](https://nodejs.org/en "Node.js V18+ LTS and npm") (comes with node)
9 | - [Git](https://git-scm.com/ "Git")
10 |
11 | If you have not installed Foundry, go to book.getfoundry and select Installation from the side menu. Follow the instructions to download using Foundryup.
12 | ```shell
13 | curl -L https://foundry.paradigm.xyz | bash
14 | ```
15 | If everything goes successfully, you can use four CLI in the terminal: forge, cast, anvil, and chisel.
16 |
17 | ## Creating your contract
18 | Initialize a project with the following command:
19 | ```shell
20 | forge init hello_contract
21 | cd hello_contract
22 | ```
23 | In the `hello_contract/src` folder, you can edit the `Counter.sol` file:
24 | ```solidity
25 | // SPDX-License-Identifier: UNLICENSED
26 | pragma solidity ^0.8.13;
27 |
28 | contract Counter {
29 | uint256 public number;
30 |
31 | function setNumber(uint256 newNumber) public {
32 | number = newNumber;
33 | }
34 |
35 | function increment() public {
36 | number++;
37 | }
38 | }
39 | ```
40 |
41 | ## Compiling your contract
42 | Next, you can compile the contract with the `forge` command:
43 | ```shell
44 | forge build
45 | ```
46 | If all goes accordingly, you will see the details:
47 | ```shell
48 | [⠔] Compiling...
49 | [⠢] Compiling 22 files with 0.8.16
50 | [⠔] Solc 0.8.16 finished in 2.75s
51 | Compiler run successful!
52 | ```
53 |
54 | ## Deploying your contract
55 | You can run the **forge create** command to deploy your contract. Replace the **HTTP_URL** with your actual endpoint, and **PRIVATE_KEY** with your actual private key.
56 | ```bash
57 | forge create --rpc-url HTTP_URL \
58 | --private-key PRIVATE_KEY \
59 | src/Counter.sol: Counter
60 | ```
61 | If it goes well, you will see the details such as:
62 | ```shell
63 | [⠆] Compiling...
64 | No files changed, compilation skipped
65 | Deployer: 0x9536354AE32852A7E7C4BFe7415b104016d5Fb04
66 | Deployed to: 0xF0D4950d45CFf612A02f453771CF93418dCaaA0B
67 | Transaction hash: 0xc09923e09e5f4a72053bcf72ca66e0fdf434ab63380481ab39ae281c63a716a0
68 | ```
69 |
70 | ## Interacting with your contract
71 | You can run the **cast** command to interact with your contract.
72 | Write a call with the **setNumber** function, such as:
73 | ```bash
74 | cast send CONTRACT_ADDRESS "setNumber(uint256)" 10 --rpc-url HTTP_URL --private-key PRIVATE_KEY
75 | ```
76 | If all goes accordingly, you will see the details:
77 | ```bash
78 | blockHash 0xf1ceea989197708be58264f3e7ebeae3ebffc5d6f345d053fd73c932627ea7fb
79 | blockNumber 9760236
80 | contractAddress
81 | cumulativeGasUsed 2638507
82 | effectiveGasPrice 3000000070
83 | gasUsed 43494
84 | logs []
85 | logsBloom 0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
86 | root
87 | status 1
88 | transactionHash 0xd17510371187101f37e96a6287dea64467eeeddae56207e45807e8626c4b01b4
89 | transactionIndex 6
90 | type 2
91 | ```
92 | Read a call with the **number** function, such as:
93 | ```bash
94 | cast call CONTRACT_ADDRESS "number()" --rpc-url HTTP_URL
95 | ```
96 | If all goes accordingly, you will see the details:
97 | ```bash
98 | 0x000000000000000000000000000000000000000000000000000000000000000a
99 | ```
--------------------------------------------------------------------------------
/developer/smart-contract/deploy-with-hardhat.mdx:
--------------------------------------------------------------------------------
1 | # Deploying with Hardhat
2 | In this tutorial, we explain step-by-step how to create, compile and deploy a simple smart contract on the X Layer testnet using Hardhat.
3 |
4 | ## What is Hardhat
5 | Hardhat is a development environment to compile, deploy, test, and debug your smart contract.
6 |
7 | ## Setting up the development environment
8 | Prerequisites:
9 | - [Node.js v18+ LTS and npm](https://nodejs.org/en "Node.js v18+ LTS and npm") (comes with Node)
10 | - [Git](https://git-scm.com/ "Git")
11 |
12 | To install Hardhat, you need to create an npm project by going to an empty folder, running `npm init`, and following its instructions. You can use another package manager, like yarn, but we recommend you use npm 7 or later, as it makes installing Hardhat plugins simpler.
13 |
14 | Once your project is ready, you should run `npm install --save-dev hardhat` , install Hardhat toolbox `npm install @nomicfoundation/hardhat-toolbox` . In order to use your local installation of Hardhat, you need to use `npx` to run it (i.e., `npx hardhat`).
15 |
16 | ## Creating your contract
17 | To create the sample project, run `npx hardhat` in your project folder:
18 | ```shell
19 | $ npx hardhat
20 | 888 888 888 888 888
21 | 888 888 888 888 888
22 | 888 888 888 888 888
23 | 8888888888 8888b. 888d888 .d88888 88888b. 8888b. 888888
24 | 888 888 "88b 888P" d88" 888 888 "88b "88b 888
25 | 888 888 .d888888 888 888 888 888 888 .d888888 888
26 | 888 888 888 888 888 Y88b 888 888 888 888 888 Y88b.
27 | 888 888 "Y888888 888 "Y88888 888 888 "Y888888 "Y888
28 |
29 | 👷 Welcome to Hardhat v2.9.9 👷
30 |
31 | ? What do you want to do? …
32 | ❯ Create a JavaScript project
33 | Create a TypeScript project
34 | Create an empty hardhat.config.js
35 | Quit
36 | ```
37 | ## Compiling your contract
38 | Next, if you take a look at the `contracts/` folder, you will see `Lock.so`l:
39 | ```shell
40 | // SPDX-License-Identifier: UNLICENSED
41 | pragma solidity ^0.8.9;
42 |
43 | // Uncomment this line to use console.log
44 | // import "hardhat/console.sol";
45 |
46 | contract Lock {
47 | uint public unlockTime;
48 | address payable public owner;
49 |
50 | event Withdrawal(uint amount, uint when);
51 |
52 | constructor(uint _unlockTime) payable {
53 | require(
54 | block.timestamp < _unlockTime,
55 | "Unlock time should be in the future"
56 | );
57 |
58 | unlockTime = _unlockTime;
59 | owner = payable(msg.sender);
60 | }
61 |
62 | function withdraw() public {
63 | // Uncomment this line, and the import of "hardhat/console.sol", to print a log in your terminal
64 | // console.log("Unlock time is %o and block timestamp is %o", unlockTime, block.timestamp);
65 |
66 | require(block.timestamp >= unlockTime, "You can't withdraw yet");
67 | require(msg.sender == owner, "You aren't the owner");
68 |
69 | emit Withdrawal(address(this).balance, block.timestamp);
70 |
71 | owner.transfer(address(this).balance);
72 | }
73 | }
74 | ```
75 | To compile it, simply run `npx hardhat compile`
76 |
77 | ## Setting configuration file
78 | In order to connect to the X Layer network, we need to configure the corresponding network.
79 | To set up your config, you have to export an object from `hardhat.config.js`:
80 | ```javascript
81 | module.exports = {
82 | defaultNetwork: "hardhat",
83 | networks: {
84 | hardhat: {
85 | },
86 | xlayer: {
87 | url: "https://testrpc.xlayer.tech",
88 | accounts: [privateKey1, privateKey2, ...]
89 | }
90 | }
91 | }
92 | ```
93 | ## Deploying your contract
94 | Next, to deploy the contract, we will use a Hardhat script. Inside the `scripts/` folder you will find a file with the following code:
95 | ```javascript
96 | // We require the Hardhat Runtime Environment explicitly here. This is optional
97 | // but useful for running the script in a standalone fashion through `node