diff --git a/app.vue b/app.vue index b3a5b82f..c7baafbb 100644 --- a/app.vue +++ b/app.vue @@ -45,8 +45,7 @@ useSeoMeta({ - - + diff --git a/content/00.zksync-era/10.guides/10.quick-start/1.index.md b/content/00.zksync-era/10.guides/10.quick-start/1.index.md index 639d5f4b..41f934a3 100644 --- a/content/00.zksync-era/10.guides/10.quick-start/1.index.md +++ b/content/00.zksync-era/10.guides/10.quick-start/1.index.md @@ -10,13 +10,13 @@ In the first step, you will build and deploy a simple contract and interact with The second section will have you creating your own ERC20 token and the final section will introduce a specialized feature of ZKsync Era, native account abstraction and paymasters. -This section is designed for developers new to ZKsync Era and uses online IDE's - Remix and AtlasZK - +This section is designed for developers new to ZKsync Era and uses Remix - an online IDE - to help you learn as quickly and efficiently as possible. ## Get started - If you haven't already added ZKsync Era to your wallet, follow the instructions in [Connect ZKsync Era to your wallet](/zksync-era/environment). -- Continue to [Deploy your first contract](/zksync-era/guides/quick-start/deploy-your-first-contract) to learn how to use Remix or Atlas - to deploy a contract onto ZKsync Era. +- Continue to [Deploy your first contract](/zksync-era/guides/quick-start/deploy-your-first-contract) + to learn how to use Remix to deploy a contract onto ZKsync Era. - If you are familiar with ZKsync Era and want to develop using `zksync-cli` locally on your machine, you can jump over to the [ZKsync 101](/zksync-era/guides/zksync-101) section. diff --git a/content/00.zksync-era/10.guides/10.quick-start/3.deploy-your-first-contract.md b/content/00.zksync-era/10.guides/10.quick-start/3.deploy-your-first-contract.md index 66cbbf0f..e81f4f86 100644 --- a/content/00.zksync-era/10.guides/10.quick-start/3.deploy-your-first-contract.md +++ b/content/00.zksync-era/10.guides/10.quick-start/3.deploy-your-first-contract.md @@ -1,27 +1,24 @@ --- title: Deploy your first contract -description: Deploy a smart contract to ZKsync from your browser using Remix or Atlas in under 5 minutes +description: Deploy a smart contract to ZKsync from your browser using Remix in under 5 minutes --- This tutorial shows you how to deploy and interact with a smart contract on ZKsync Era in less than 5 minutes. It will help you get familiar with the ZKsync smart contract development and deployment process using different tools. - - - In this section you will learn how to: :check-icon Build a smart contract to exchange messages with Zeek. :check-icon Deploy the smart contract to the %%zk_testnet_name%%. -:check-icon Interact with the contract from your browser using Remix or Atlas. +:check-icon Interact with the contract from your browser using Remix. ## Prerequisites 1. Before you start, make sure that [you’ve configured the %%zk_testnet_name%% in your wallet](/zksync-era/environment). -2. Have at least 0.5 %%zk_testnet_name%% ETH. If you need more, use [one of the faucets](/zksync-era/ecosystem/network-faucets). +2. Have at least 0.05 %%zk_testnet_name%% ETH. If you need more, use [one of the faucets](/zksync-era/ecosystem/network-faucets). ## Review the smart contract code @@ -29,82 +26,35 @@ The smart contract will store messages from users and emit events with replies f The entire code is as follows: ```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -contract ZeekMessages { - string[] private messages; - - // Event to acknowledge a new message - event MessageReceived(string); - - constructor() { - // Zeek initializes the contract with a welcome message - emit MessageReceived("Zeek welcomes you to ZKsync!"); - } - - function sendMessage(string memory _message) public { - messages.push(_message); - - // Acknowledge the message receipt with Zeek's reply - emit MessageReceived("ZK is the endgame - Message received!"); - } - - // Function to count the total messages sent to Zeek - function getTotalMessages() public view returns (uint) { - return messages.length; - } - - // Function to return the last message sent to Zeek - function getLastMessage() public view returns (string memory) { - require(messages.length > 0, "No messages sent to Zeek yet!"); - return messages[messages.length - 1]; - } -} - +:code-import{filePath="hardhat-sol/contracts/ZeekMessages.sol"} ``` -The Solidity smart contract contains two functions: +The Solidity smart contract contains three functions: - `sendMessage` stores the messages sent by users in the `messages` state variable. - `getTotalMessages` returns the number of messages stored in the smart contract. - `getLastMessage` returns the last message sent. -::callout{icon="i-heroicons-light-bulb"} -ZKsync Era is [EVM compatible](/zksync-protocol/glossary#evm-compatible). -You can write smart contracts with Solidity or Vyper and use existing popular libraries like OpenZeppelin, just like on Ethereum. -:: - ## Compile and deploy the contract -To compile and deploy the contract you can use either Atlas or Remix: +To compile and deploy the contract you can use either EVM or EraVM bytecode: + +:display_partial{path="/_partials/_eravm_vs_evm"} + +
::content-switcher --- items: [{ - label: 'Atlas', - partial: '_deploy_first/_atlas_deploy_contract' + label: 'EVM', + partial: '_deploy_first/_evm_remix_deploy_contract' }, { - label: 'Remix', - partial: '_deploy_first/_remix_deploy_contract' + label: 'EraVM', + partial: '_deploy_first/_eravm_remix_deploy_contract' }] --- :: -## Check the contract in explorer - -Copy the smart contract address from Atlas/Remix and search it via the [%%zk_testnet_name%% -explorer](%%zk_testnet_block_explorer_url%%). You’ll see the contract has a transaction from the message you just sent. - -![Contract in ZKsync explorer](/images/101-quickstart/101-contract-deployed.png) - -The status will be “Processed” on ZKsync Era and “Sending” on Ethereum. [Learn more about the transaction lifecycle on ZKsync](/zksync-protocol/rollup/transaction-lifecycle). - -In the “Contract” tab you’ll see the contract source code as Atlas and Remix automatically verified the contract for us. -When a smart contract is verified in a block explorer, it means that the source code of the contract has been published -and matched to the compiled version on the blockchain enhancing transparency, as users can review the contract’s source -code to understand its functions and intentions. - Finally in the “Events” tab, you’ll see the replies from Zeek as these are emitted as events in our smart contract. ![Contract events in ZKsync explorer](/images/101-quickstart/101-contract-events.png) @@ -115,9 +65,10 @@ ZK is the endgame ✌️ - **EVM-compatibility**: ZKsync Era is EVM-compatible and you can write smart contracts in Solidity or Vyper as in Ethereum. -- **Custom compilers**: smart contracts deployed to ZKsync Era must be compiled with the customs compilers: `zksolc` for - Solidity and `zkvyper` for Vyper. -- **Browser-based IDEs**: Existing tools like Atlas and Remix use ZKsync custom compilers under the hood. +- **Custom compilers**: smart contracts deployed to ZKsync Era can either be compiled as EVM using default compilers and tools, + or EraVM with the custom compilers: + `zksolc` for Solidity and `zkvyper` for Vyper. +- **Browser-based IDEs**: You can use existing tools like Remix to deploy EVM or EraVM contracts. ## Next steps diff --git a/content/00.zksync-era/10.guides/10.quick-start/4.erc20-token.md b/content/00.zksync-era/10.guides/10.quick-start/4.erc20-token.md index 255757b7..b44bab0a 100644 --- a/content/00.zksync-era/10.guides/10.quick-start/4.erc20-token.md +++ b/content/00.zksync-era/10.guides/10.quick-start/4.erc20-token.md @@ -9,13 +9,13 @@ This is what you're going to do: :check-icon Build an ERC20 token smart contract with additional custom logic -:check-icon Deploy the smart contract to the %%zk_testnet_name%% using Remix or Atlas. +:check-icon Deploy the smart contract to the %%zk_testnet_name%% using Remix. ## Prerequisites 1. Before you start, make sure that [you’ve configured the %%zk_testnet_name%% in your wallet](/zksync-era/environment). -2. Have at least 0.5 %%zk_testnet_name%% ETH. If you need more, use [one of the faucets](/zksync-era/ecosystem/network-faucets). +2. Have at least 0.05 %%zk_testnet_name%% ETH. If you need more, use [one of the faucets](/zksync-era/ecosystem/network-faucets). ## Custom ERC20 token code @@ -26,28 +26,9 @@ The ERC20 token we’re going to deploy will allow users to mint and burn tokens follows: ```solidity -// SPDX-License-Identifier: Unlicensed -pragma solidity ^0.8.19; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; -import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; - -contract TestToken is ERC20, Ownable, ERC20Burnable { - constructor(string memory name, string memory symbol) ERC20(name, symbol) { - _mint(msg.sender, 100 * 10 ** decimals()); - } - - function mint(address to, uint256 amount) public onlyOwner { - _mint(to, amount); - } -} +:code-import{filePath="hardhat-sol/contracts/TestToken.sol"} ``` -::callout{icon="i-heroicons-light-bulb"} -ZKsync Era is [EVM compatible](/zksync-protocol/glossary#evm-compatible), so you can use existing popular libraries like OpenZeppelin. -:: - The most important features are: - `Ownable` : this extension sets the deployer account as owner of the smart contract. It also introduces the @@ -61,16 +42,20 @@ The most important features are: ## Deploy and interact with the contract -To complete this tutorial you'll use either Atlas or Remix. Select your preferred tool: +To compile and deploy the contract you can use either EVM or EraVM: + +:display_partial{path="/_partials/_eravm_vs_evm"} + +
::content-switcher --- items: [{ - label: 'Atlas', - partial: '_erc20_tutorial/_atlas_erc20_tutorial' + label: 'EVM', + partial: '_erc20_tutorial/_evm' }, { - label: 'Remix', - partial: '_erc20_tutorial/_remix_erc20_tutorial' + label: 'EraVM', + partial: '_erc20_tutorial/_eravm' }] --- :: @@ -92,7 +77,7 @@ The ERC20 token code is provided “as is” without any express or implied warr ## Next steps -- Continue learning about [paymasters and paying transaction fees with this ERC20 token](/zksync-era/guides/quick-start/paymasters-introduction). +- Continue building with ZKsync in the [ZKsync 101 section](/zksync-era/guides/zksync-101). - Join the [ZKsync developer community in Discord](https://join.zksync.dev/) where you can ask any questions about this tutorial in the `#dev-quickstart` channel. - Join our [GitHub Discussions Community](%%zk_git_repo_zksync-developers%%/discussions/) to diff --git a/content/00.zksync-era/10.guides/10.quick-start/5.paymasters-introduction.md b/content/00.zksync-era/10.guides/10.quick-start/5.paymasters-introduction.md deleted file mode 100644 index 2ff4c681..00000000 --- a/content/00.zksync-era/10.guides/10.quick-start/5.paymasters-introduction.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -title: Paymasters introduction -description: Learn about paymasters and use one to pay transaction fees with your own token ---- - -This tutorial makes use of smart contracts deployed in the previous two tutorials, -[Deploy your first contract](/zksync-era/guides/quick-start/deploy-your-first-contract) and [Create an ERC20 token](/zksync-era/guides/quick-start/erc20-token). -This section introduces one of the custom features -of ZKsync: native account abstraction and paymasters. - -In this tutorial we will: - -:check-icon Learn about paymasters. - -:check-icon Review the testnet paymaster smart contract code. - -:check-icon Use the testnet paymaster to pay transaction fees with our own ERC20 token. - -## Prerequisites - -1. Before you start, make sure that -[you’ve configured the %%zk_testnet_name%% in your browser wallet by following the instructions here](/zksync-era/environment). -1. In addition, fund your wallet with %%zk_testnet_name%% ETH using [one of the available faucets](/zksync-era/ecosystem/network-faucets). - -## What is a Paymaster? - -Paymasters in the ZKsync ecosystem represent a groundbreaking approach to handling transaction fees. -They are special accounts designed to subsidize transaction costs for other accounts, -potentially making certain transactions free for end-users. -This feature is particularly useful for dApp developers looking -to improve their platform's accessibility and user experience by covering transaction fees on behalf of their users. - -Every paymaster has the following two functions: - -- `validateAndPayForPaymasterTransaction` : this function uses the transaction parameters (fields like `from`, `amount` , `to` - ) to execute the required validations and pay for the transaction fee. - -- `postTransaction`: this optional function runs after the transaction is executed. - -![zksync paymaster](/images/101-paymasters/zksync-paymaster.png) - -## Paymaster smart contract code - -Although application developers are encouraged to create their own paymaster smart contract, ZKsync provides a testnet -paymaster for convenience and testing purposes. - -::callout{icon="i-heroicons-exclamation-triangle" color="amber"} -The paymaster smart contract code is provided "as-is" without any express or implied warranties. -
- -- Users are solely responsible for ensuring that their design, implementation, - and use of the paymaster smart contract software complies with all applicable laws, - including but not limited to money transmission, anti-money laundering (AML), and payment processing regulations. - -- The developers and publishers of this software disclaim any liability for any legal issues that may arise from its use. -:: - -The testnet paymaster address is -[0x3cb2b87d10ac01736a65688f3e0fb1b070b3eea3](https://sepolia.explorer.zksync.io/address/0x3cb2b87d10ac01736a65688f3e0fb1b070b3eea3) - -::drop-panel - ::panel{label="TestnetPaymaster.sol"} - ```solidity - // SPDX-License-Identifier: MIT - - pragma solidity 0.8.20; - - import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; - - import "./interfaces/IPaymaster.sol"; - import "./interfaces/IPaymasterFlow.sol"; - import "./L2ContractHelper.sol"; - - // This is a dummy paymaster. It expects the paymasterInput to contain its "signature" as well as the needed exchange rate. - // It supports only approval-based paymaster flow. - contract TestnetPaymaster is IPaymaster { - function validateAndPayForPaymasterTransaction( - bytes32, - bytes32, - Transaction calldata _transaction - ) external payable returns (bytes4 magic, bytes memory context) { - // By default we consider the transaction as accepted. - magic = PAYMASTER_VALIDATION_SUCCESS_MAGIC; - - require(msg.sender == BOOTLOADER_ADDRESS, "Only bootloader can call this contract"); - require(_transaction.paymasterInput.length >= 4, "The standard paymaster input must be at least 4 bytes long"); - - bytes4 paymasterInputSelector = bytes4(_transaction.paymasterInput[0:4]); - if (paymasterInputSelector == IPaymasterFlow.approvalBased.selector) { - // While the actual data consists of address, uint256 and bytes data, - // the data is not needed for the testnet paymaster - (address token, uint256 amount, ) = abi.decode(_transaction.paymasterInput[4:], (address, uint256, bytes)); - - // Firstly, we verify that the user has provided enough allowance - address userAddress = address(uint160(_transaction.from)); - address thisAddress = address(this); - - uint256 providedAllowance = IERC20(token).allowance(userAddress, thisAddress); - require(providedAllowance >= amount, "The user did not provide enough allowance"); - - // The testnet paymaster exchanges X wei of the token to the X wei of ETH. - uint256 requiredETH = _transaction.gasLimit * _transaction.maxFeePerGas; - if (amount < requiredETH) { - // Important note: while this clause definitely means that the user - // has underpaid the paymaster and the transaction should not accepted, - // we do not want the transaction to revert, because for fee estimation - // we allow users to provide smaller amount of funds then necessary to preserve - // the property that if using X gas the transaction success, then it will succeed with X+1 gas. - magic = bytes4(0); - } - - // Pulling all the tokens from the user - try IERC20(token).transferFrom(userAddress, thisAddress, amount) {} catch (bytes memory revertReason) { - // If the revert reason is empty or represented by just a function selector, - // we replace the error with a more user-friendly message - if (revertReason.length <= 4) { - revert("Failed to transferFrom from users' account"); - } else { - assembly { - revert(add(0x20, revertReason), mload(revertReason)) - } - } - } - - // The bootloader never returns any data, so it can safely be ignored here. - (bool success, ) = payable(BOOTLOADER_ADDRESS).call{value: requiredETH}(""); - require(success, "Failed to transfer funds to the bootloader"); - } else { - revert("Unsupported paymaster flow"); - } - } - - function postTransaction( - bytes calldata _context, - Transaction calldata _transaction, - bytes32, - bytes32, - ExecutionResult _txResult, - uint256 _maxRefundedGas - ) external payable override { - // Nothing to do - } - - receive() external payable {} - } - ``` - :: -:: - -In the `validateAndPayForPaymasterTransaction` it is: - -1. Checking that the paymasterInput is `approvalBased`. -2. Checking that the allowance of a given ERC20 is enough. -3. Transferring the transaction fee (`requiredETH`) in ERC20 from the user’s balance to the paymaster. -4. Transferring the transaction fee in ETH from the paymaster contract to the bootloader. - -## How to send a transaction through a paymaster? - -In order to send a transaction through a paymaster, the transaction must include the following additional parameters: - -- `paymasterAddress`: the smart contract address of the paymaster -- `type`: should be `General` or `ApprovalBased` (to pay fees with ERC20 tokens) -- `minimalAllowance`: the amount of ERC20 tokens to be approved for spending (for `approvalBased` type paymasters only). -- `innerInput`: any payload we want to send to the paymaster (optional). - -We’ll see an example next. - -## Interacting with the testnet paymaster - -We’re going to interact with the `ZeekMessages.sol` contract that we created in the first tutorial and use the -ERC20 token that we deployed in the second tutorial to pay the transaction fees. - -::content-switcher ---- -items: [{ - label: 'Atlas', - partial: '_paymaster_intro/_atlas_paymaster_intro' -}, { - label: 'Remix', - partial: '_paymaster_intro/_remix_paymaster_intro' -}] ---- -:: - -## Takeaways - -- Paymasters on ZKsync allow any account to pay fees with ERC20 tokens or enable gasless transactions. - -- Paymasters are smart contracts that can have any validations and rules. -- To send a transaction through a paymaster, we only need to include additional parameters in the transaction. - -## Next steps - -- Learn more about paymasters and native account abstraction in [this section of the docs](/zksync-protocol/account-abstraction). -- Browse different paymaster examples in [this open source repository](https://github.com/matter-labs/paymaster-examples). -- Continue learning in ZKsync 101 by building a [GoFundMe clone](/zksync-era/guides/zksync-101). diff --git a/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_atlas_deploy_contract.md b/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_atlas_deploy_contract.md deleted file mode 100644 index f3cd6dc5..00000000 --- a/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_atlas_deploy_contract.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Quickstart with Atlas ---- -Atlas is a browser-based IDE with an integrated AI assistant that allows you to write, test and deploy smart contracts -directly from your browser. Click the button below to open the project in Atlas. - -:u-button{ icon="i-heroicons-code-bracket" size="lg" color="primary" variant="solid" :trailing="false" -to="https://app.atlaszk.com/templates/33EAJkwrTKFaDJiEuy9Om?chainId=%%zk_testnet_chain_id%%&openFile=/contracts/ZeekSecretMessages.sol" -target="_blank" label="Open smart contract in Atlas"} - -### Compile and deploy the contract - -Enter a name for the project and you will see the contract in the Atlas code editor. -On the right side, make sure the selected network is “%%zk_testnet_name%%“ -and click on **“Deploy”** to trigger the smart contract compilation and deployment. - -![Contract in Atlas](/images/101-quickstart/101-atlas-contract.png) - -::callout{icon="i-heroicons-light-bulb"} -Behind the scenes, Atlas is using the ZKsync Era custom solidity compiler -(named `zksolc` ) to generate ZKEVM compatible bytecode. [Learn more about ZKsync custom compilers](/zksync-protocol/compiler/toolchain). -:: - -Once compiled sign the transaction with your wallet and wait until it's processed. You’ll see the contract in the -“Deployed contracts” section. Congratulations, you’ve deployed your first smart contract to %%zk_testnet_name%%! - -### Interact with the contract - -Below the contract name you can find its deployment address. The “Live Contract State” section displays the smart -contract balance and the value returned by the `getTotalMessages` function. - -![Contract deployed](/images/101-quickstart/101-atlas-deployed.png) - -The “Write Functions” section contains the form to interact with the `sendMessage` function. Write a message, click the -“Run” button and confirm the transaction in your wallet. You’ll see that the `getTotalMessages` is updated to `1` and -`getLastMessage` returns the message you just sent. That means our contract is storing the messages as expected! But how -can you see the replies from Zeek? diff --git a/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_eravm_remix_deploy_contract.md b/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_eravm_remix_deploy_contract.md new file mode 100644 index 00000000..8ea1e756 --- /dev/null +++ b/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_eravm_remix_deploy_contract.md @@ -0,0 +1,52 @@ +--- +title: EraVM Quickstart with Remix +--- + +:display_partial{path="/_partials/remix/deploy/_remix-intro"} + +:display_partial{path="/_partials/remix/deploy/_enable-remix-zksync-plugin"} + +:display-partial{path="/_partials/remix/erc20/_template"} + +### Connect your wallet + +:display_partial{path="/_partials/remix/deploy/_remix-era-wallet"} + +:display_partial{path="/_partials/remix/deploy/_connect"} + +:display_partial{path="/_partials/remix/deploy/_remix-compile-era"} + +::callout{icon="i-heroicons-light-bulb"} +Behind the scenes, Remix is using the ZKsync Era custom solidity compiler +(named `zksolc`) to generate ZKsync VM compatible bytecode. [Learn more about ZKsync custom compilers](/zksync-protocol/compiler/toolchain). +:: + +### Deploy the contract + +To deploy the contract, open the "Deploy" dropdown, check the "Verify contract" checkbox, and click on “Deploy & +Verify”. Sign the transaction in your wallet and wait a few seconds until it's processed. Congratulations, you’ve +deployed your first contract to %%zk_testnet_name%%! + +![Remix interact ZKsync contract](/images/101-quickstart/101-remix-deploy.png) + +### Interact with the contract + +Next to the contract name you can find the address where the contract is deployed. The “Interact” section displays the +forms to interact with the `getTotalMessages` and `sendMessage` functions. + +![Remix interact ZKsync contract](/images/101-quickstart/101-remix-interact.png) + +:display_partial{path="/_partials/remix/deploy/_remix-template-interact-2"} + +## Check the contract in explorer + +Copy the smart contract address from Remix and search it via the [%%zk_testnet_name%% +explorer](%%zk_testnet_block_explorer_url%%). You’ll see the contract has a transaction from the message you just sent. + +![Contract in ZKsync explorer](/images/101-quickstart/101-contract-deployed.png) + +:display_partial{path="/_partials/remix/deploy/_status"} + +In the “Contract” tab you’ll see the contract source code as Remix automatically verified the contract for us. + +:display_partial{path="/_partials/remix/deploy/_verification"} diff --git a/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_evm_remix_deploy_contract.md b/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_evm_remix_deploy_contract.md new file mode 100644 index 00000000..df5740f4 --- /dev/null +++ b/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_evm_remix_deploy_contract.md @@ -0,0 +1,48 @@ +--- +title: EVM Quickstart with Remix +--- + +:display_partial{path="/_partials/remix/deploy/_remix-intro"} + +:display-partial{path="/_partials/remix/erc20/_template"} + +Then, open up the `ZeekMessages.sol` contract file. + +### Connect your wallet + +:display_partial{path="/_partials/remix/deploy/_remix-evm-wallet"} + +:display_partial{path="/_partials/remix/deploy/_connect"} + +### Compile the contract + +To compile the contract, click on the "Solidity Compiler" tab and press the "Compile `ZeekMessages.sol`" button. + +### Deploy the contract + +To deploy the contract, go back to the "Deploy and run transactions" tab and click on the "Deploy" button. +Sign the transaction in your wallet and wait a few seconds until it's processed. Congratulations, you’ve +deployed your first contract to %%zk_testnet_name%%! + +![Remix interact ZKsync contract](/images/101-quickstart/deploy.gif) + +### Interact with the contract + +Under "Deployed Contracts", click on your contract to show the interaction options: + +![Remix interact ZKsync contract](/images/101-quickstart/interact.gif) + +:display_partial{path="/_partials/remix/deploy/_remix-template-interact-2"} + +## Check the contract in explorer + +Copy the smart contract address from Remix and search it via the [%%zk_testnet_name%% +explorer](%%zk_testnet_block_explorer_url%%). You’ll see the contract has a transaction from the message you just sent. + +![Contract in ZKsync explorer](/images/101-quickstart/explorer.png) + +:display_partial{path="/_partials/remix/deploy/_status"} + +In the “Contract” tab you’ll see the contract source code as the block explorer automatically partially verified the contract for us. + +:display_partial{path="/_partials/remix/deploy/_verification"} diff --git a/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_remix_deploy_contract.md b/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_remix_deploy_contract.md deleted file mode 100644 index 53663dd4..00000000 --- a/content/00.zksync-era/10.guides/10.quick-start/_deploy_first/_remix_deploy_contract.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Quickstart with Remix ---- - -The Remix IDE is an open-source web and desktop application that supports Ethereum smart contract development and -deployment, offering tools for writing, testing, debugging, and deploying smart contracts written in Solidity to EVM -compatible protocols. - -### Enable the Remix ZKsync plugin - -:display_partial{path="/_partials/_enable-remix-zksync-plugin"} - -Click the button below to open the project in Remix and see the contract in the Remix code editor. - -:u-button{ icon="i-heroicons-code-bracket" size="lg" color="primary" variant="solid" :trailing="false" -to="https://remix.ethereum.org/?#activate=zkSync&call=zkSync//loadFromGithub//ZKsync-Community-Hub//zksync-quickstart-remix//" -target="_blank" label="Open project in Remix"} - -### Connect your wallet - -Make sure your wallet is currently connected to the %%zk_testnet_name%% as we will use our wallet’s configured -network to deploy our smart contract. In the ZKsync Remix plugin, under the Environment Section, select “Wallet” and click on -“Connect Wallet” as shown below: - -![Connect wallet in Remix](/images/remix-connect-wallet.gif) - -### Compile the contract - -To compile the contract, open the `ZeeksSecretMessages.sol` file in the editor, go the ZKsync plugin, and click on "Compile ZeeksSecretMessages.sol". -If you get a popup message requesting permissions to -access **`ACCESS TO "WRITEFILE" OF "FILE MANAGER"`,** click on "Accept". - -::callout{icon="i-heroicons-light-bulb"} -Behind the scenes, Remix is using the ZKsync Era custom solidity compiler -(named `zksolc`) to generate ZKsync VM compatible bytecode. [Learn more about ZKsync custom compilers](/zksync-protocol/compiler/toolchain). -:: - -### Deploy the contract - -To deploy the contract, open the "Deploy" dropdown, check the "Verify contract" checkbox, and click on “Deploy & -Verify”. Sign the transaction in your wallet and wait a few seconds until it's processed. Congratulations, you’ve -deployed your first contract to %%zk_testnet_name%%! - -![Remix interact ZKsync contract](/images/101-quickstart/101-remix-deploy.png) - -### Interact with the contract - -Next to the contract name you can find the address where the contract is deployed. The “Interact” section displays the -forms to interact with the `getTotalMessages` and `sendMessage` functions. - -![Remix interact ZKsync contract](/images/101-quickstart/101-remix-interact.png) - -Write a message in the form, click the “sendMessage” button and confirm the transaction in your wallet. Once processed, -click the `getTotalMessages` and check the response in the terminal, which should be `1`. The `getLastMessage` function -should also return the message you just sent. That means the contract is storing the messages as expected! But how can -we see the replies from Zeek? diff --git a/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_atlas_erc20_tutorial.md b/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_atlas_erc20_tutorial.md deleted file mode 100644 index a33bb455..00000000 --- a/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_atlas_erc20_tutorial.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: ERC20 token with Atlas ---- - -## Deploy the smart contract - -Atlas is a browser-based IDE with an integrated AI assistant that allows you to write, test and deploy smart contracts -directly from your browser. Click the button below to open the project in Atlas. - -:u-button{ icon="i-heroicons-code-bracket" size="lg" color="primary" variant="solid" :trailing="false" -to="https://app.atlaszk.com/templates/33EAJkwrTKFaDJiEuy9Om?chainId=%%zk_testnet_chain_id%%&openFile=/contracts/TestToken.sol" -target="_blank" label="Open smart contract in Atlas"} - -You can see the contract in the Atlas code editor. In the right sidebar, -make sure the selected network is “%%zk_testnet_name%%“ -and click on **"Deploy"** to trigger the smart contract compilation and deployment. - -::callout{icon="i-heroicons-light-bulb"} -Behind the scenes, Atlas is using the ZKsync Era custom solidity compiler -(named `zksolc` ) to generate ZKEVM compatible bytecode. [Learn more about ZKsync custom compilers](/zksync-protocol/compiler/toolchain). -:: - -![ERC20 interact script in Atlas](/images/101-erc20/atlas-deploy-erc20.png) - -Once compiled sign the transaction with your wallet and wait until its processed. You’ll see the contract in the -**“Deployed contracts”** section. - -## Interact with the ERC20 contract - -In the `scripts` folder you can find the `mint-token.ts` script containing the following code: - -```ts -import { ethers } from "hardhat"; - -// Address of the ERC20 token contract -const TOKEN_CONTRACT_ADDRESS = ""; -// Wallet that will receive tokens -const RECEIVER_WALLET = ""; -// Amount of tokens to mint in ETH format, e.g. 1.23 -const TOKEN_AMOUNT = ""; - -async function main() { - const Token = await ethers.getContractFactory("TestToken"); - const tokenContract = Token.attach(TOKEN_CONTRACT_ADDRESS); - - console.log("Minting tokens..."); - - const tx = await tokenContract.mint( - RECEIVER_WALLET, - ethers.parseEther(TOKEN_AMOUNT), - ); - await tx.wait(); - - console.log("Success!"); - console.log( - `The account ${RECEIVER_WALLET} now has ${await tokenContract.balanceOf( - RECEIVER_WALLET, - )} tokens`, - ); -} - -main() - .then(() => process.exit(0)) - .catch((error) => { - console.error(error); - process.exit(1); - }); -``` - -This scripts uses `ethers` to interact with the contract we’ve just deployed. - -::callout{icon="i-heroicons-light-bulb"} -Existing libraries like `ethers` , `viem` and `web3.js` can be used to interact with smart contracts deployed on ZKsync. -:: - -Fill the following variables: - -- `TOKEN_CONTRACT_ADDRESS`: the contract address of the ERC20 token we just deployed. -- `RECEIVER_WALLET`: address of a different account that will receive new tokens. -- `TOKEN_AMOUNT`: the amount of tokens we’ll send to the account. - -With the `mint-token.ts` file open in the Atlas editor, click on the “Deploy” button to run the script and see the output -in the terminal. - -![ERC20 interact script in Atlas](/images/101-erc20/atlas-erc20-interact.png) - -To confirm the account has received the tokens, visit the [%%zk_testnet_name%% -explorer](%%zk_testnet_block_explorer_url%%) and search the receiver wallet -address. You’ll see the new token balance in the assets table: - -![ERC20 tokens in account balance](/images/101-erc20/erc20-tokens-minted.png) diff --git a/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_eravm.md b/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_eravm.md new file mode 100644 index 00000000..f2aef74e --- /dev/null +++ b/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_eravm.md @@ -0,0 +1,22 @@ +--- +title: ERC20 with Remix EraVM +--- + +:display_partial{path="/_partials/remix/erc20/_intro"} + +:display_partial{path="/_partials/remix/erc20/_deploy_eravm"} + +## Interact with the ERC20 contract + +In the `scripts` folder you can find the `mint-token-era-vm.ts` script containing the following code: + +:display_partial{path="/_partials/remix/erc20/_script_code_eravm"} + +:display_partial{path="/_partials/remix/erc20/_ethers"} + +With the `mint-token-era-vm.ts` file open in the editor, click on the “▶️” button to run the script. +Sign the transaction in your wallet and see the output in the terminal. + +![ERC20 interact script in Remix](/images/101-erc20/remix-erc20-interact.png) + +:display_partial{path="/_partials/remix/erc20/_run_script"} diff --git a/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_evm.md b/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_evm.md new file mode 100644 index 00000000..89671631 --- /dev/null +++ b/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_evm.md @@ -0,0 +1,49 @@ +--- +title: ERC20 with Remix EVM +--- + +:display_partial{path="/_partials/remix/erc20/_intro"} + +:display-partial{path="/_partials/remix/erc20/_template"} + +Then, open up the `TestToken.sol` contract file. + +### Connect your wallet + +:display_partial{path="/_partials/remix/deploy/_remix-evm-wallet"} + +:display_partial{path="/_partials/remix/deploy/_connect"} + +### Compile the contract + +To compile the contract, click on the "Solidity Compiler" tab and press the "Compile `TestToken.sol`" button. + +### Deploy the contract + +To deploy the contract, go back to the "Deploy and run transactions" tab. +Enter the name and symbol for your token in the input field by the "Deploy" button, then click "Deploy". +Sign the transaction in your wallet and wait a few seconds until it's processed. + +![Deploy ERC20 Remix EVM](/images/101-erc20/deploy-erc20.gif) + +Congratulations, your ERC20 token +contract is now deployed on %%zk_testnet_name%%! + +Under the "Deployed Contracts" section, you should now see your contract deployment. +Click on the copy icon to copy your contract address. +You will need this for the next section. + +## Interact with the ERC20 contract + +In the `scripts` folder you can find the `mint-token-evm.ts` script containing the following code: + +:display_partial{path="/_partials/remix/erc20/_script_code_evm"} + +:display_partial{path="/_partials/remix/erc20/_ethers"} + +With the `mint-token-evm.ts` file open in the editor, click on the “▶️” button to run the script. +Sign the transaction in your wallet and see the output in the terminal. + +![ERC20 interact script in Remix](/images/101-erc20/run-script-evm.png) + +:display_partial{path="/_partials/remix/erc20/_run_script"} diff --git a/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_remix_erc20_tutorial.md b/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_remix_erc20_tutorial.md deleted file mode 100644 index f5f49933..00000000 --- a/content/00.zksync-era/10.guides/10.quick-start/_erc20_tutorial/_remix_erc20_tutorial.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: ERC20 with Remix ---- - -The Remix IDE is an open-source web and desktop application that supports Ethereum smart contract development and -deployment, offering tools for writing, testing, debugging, and deploying smart contracts written in Solidity to EVM -compatible protocols. - -### Enable the Remix ZKsync plugin - -:display-partial{path="/_partials/_enable-remix-zksync-plugin"} - -Click the button below to open the project in Remix and see the contract in the Remix code editor. - -:u-button{ icon="i-heroicons-code-bracket" size="lg" color="primary" variant="solid" :trailing="false" -to="https://remix.ethereum.org/?#activate=zkSync&call=zkSync//loadFromGithub//ZKsync-Community-Hub//zksync-quickstart-remix//" -target="_blank" label="Open project in Remix"} - -Once the project is imported, open the `contracts/TestToken.sol` file. To compile the contract, click on the ZKsync -plugin on the left menu and then "Compile TestToken.sol". If you get a popup message requesting permissions to access -**`ACCESS TO "WRITEFILE" OF "FILE MANAGER"`,** click on Accept. - -::callout{icon="i-heroicons-light-bulb"} -Behind the scenes, Remix is using the ZKsync Era custom Solidity compiler (named `zksolc` ) to generate ZKEVM compatible -bytecode. -[Learn more about ZKsync custom compilers](/zksync-protocol/compiler/toolchain). -:: - -We will use our wallet’s configured -network to deploy our smart contract. In the ZKsync Remix plugin, under the Environment Section, select “Wallet” and click on -“Connect Wallet” as shown below: - -![Connect wallet in Remix](/images/remix-connect-wallet.gif) - -## Deploy the contract - -To deploy the contract, select the `TestToken.sol` contract on the on the “Deploy” section, check the "Verify contract" checkbox, and -click on “Deploy & Verify”. -Sign the transaction on your wallet and wait a few seconds until the transaction is confirmed. - -Congratulations, your ERC20 token -contract is now deployed on %%zk_testnet_name%%! - -## Interact with the ERC20 contract - -In the `scripts` folder you can find the `mint-token.ts` script containing the following code: - -```typescript -import {ethers} from "ethers"; - -// Address of the ERC20 token contract -const TOKEN_CONTRACT_ADDRESS = "" -// Wallet that will receive tokens -const RECEIVER_WALLET = ""; -// Amount of tokens to mint in ETH format, e.g. 1.23 -const TOKEN_AMOUNT = "123.55"; - -(async () => { - try { - - // Note that the script needs the ABI which is generated from the compilation artifact. - // Make sure contract is compiled for ZKsync and artifacts are generated - const artifactsPath = `browser/artifacts/contracts/TestToken.sol/TestToken.json` - - const metadata = JSON.parse(await remix.call('fileManager', 'getFile', artifactsPath)) - - // 'web3Provider' is a remix global variable object - const signer = (new ethers.providers.Web3Provider(web3Provider)).getSigner(0) - - // initialise token contract with address, abi and signer - const tokenContract= new ethers.Contract(TOKEN_CONTRACT_ADDRESS, metadata.abi, signer); - - console.log("Minting tokens..."); - const tx = await tokenContract.mint( - RECEIVER_WALLET, - ethers.utils.parseEther(TOKEN_AMOUNT) - ); - console.log(`Mint transaction is ${tx.hash}`) - await tx.wait(); - console.log("Success!"); - - const balance = await tokenContract.balanceOf(RECEIVER_WALLET) - - console.log(`The account ${RECEIVER_WALLET} now has ${balance} tokens`) - - } catch (e) { - console.log(e.message) - } -})() - -``` - -This scripts uses `ethers` to interact with the contract we’ve just deployed. - -::callout{icon="i-heroicons-light-bulb"} -Existing libraries like `ethers` , `viem` and `web3.js` can be used to interact with smart contracts deployed on ZKsync Era. -:: - -Fill the following variables: - -- `TOKEN_CONTRACT_ADDRESS`: the contract address of the ERC20 token we just deployed. -- `RECEIVER_WALLET`: address of a different account that will receive new tokens. -- `TOKEN_AMOUNT`: the amount of tokens we’ll send to the account. - -::callout{icon="i-heroicons-exclamation-triangle" color="amber"} -Open the "Deploy & run transactions" menu in Remix and select "Injected Provider - Metamask" -from the environment dropdown to target the network selected in your wallet when running scripts. -:: - -With the `mint-token.ts` file open in the editor, click on the “▶️” button to run the script. -Sign the transaction in your wallet and see the output in the terminal. - -![ERC20 interact script in Remix](/images/101-erc20/remix-erc20-interact.png) - -To confirm the account has received the tokens, visit the [%%zk_testnet_name%% -explorer](%%zk_testnet_block_explorer_url%%) and search the receiver wallet -address. You’ll see the new token balance in the assets table: - -![ERC20 tokens in account balance](/images/101-erc20/erc20-tokens-minted.png) diff --git a/content/00.zksync-era/10.guides/10.quick-start/_paymaster_intro/_atlas_paymaster_intro.md b/content/00.zksync-era/10.guides/10.quick-start/_paymaster_intro/_atlas_paymaster_intro.md deleted file mode 100644 index 259e3b50..00000000 --- a/content/00.zksync-era/10.guides/10.quick-start/_paymaster_intro/_atlas_paymaster_intro.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Paymaster with Atlas ---- - -Click the following button to open the project in Atlas: - -:u-button{ icon="i-heroicons-code-bracket" size="lg" color="primary" variant="solid" :trailing="false" -to="https://app.atlaszk.com/templates/33EAJkwrTKFaDJiEuy9Om?chainId=%%zk_testnet_chain_id%%&openFile=/scripts/paymaster-transaction.ts" -target="_blank" label="Open script in Atlas"} - -It’ll open the script to send a transaction via the paymaster. Let’s go through the most important parts: - -### Retrieve the token balance - -```typescript -// retrieve and print the current balance of the wallet -let ethBalance = await provider.getBalance(walletAddress) -let tokenBalance = await tokenContract.balanceOf(walletAddress) -console.log(`Account ${walletAddress} has ${ethers.formatEther(ethBalance)} ETH`); -console.log(`Account ${walletAddress} has ${ethers.formatUnits(tokenBalance, 18)} tokens`); -``` - -In this part we’re retrieving the ETH and ERC20 token balances of the account. We’ll compare them after the transaction -is executed to see the difference. - -### Estimate transaction fee - -```typescript -// retrieve the testnet paymaster address -const testnetPaymasterAddress = await zkProvider.getTestnetPaymasterAddress(); - -console.log(`Testnet paymaster address is ${testnetPaymasterAddress}`); - -const gasPrice = await zkProvider.getGasPrice(); - -// define paymaster parameters for gas estimation -const paramsForFeeEstimation = utils.getPaymasterParams(testnetPaymasterAddress, { - type: "ApprovalBased", - token: TOKEN_CONTRACT_ADDRESS, - // set minimalAllowance to 1 for estimation - minimalAllowance: ethers.toBigInt(1), - // empty bytes as testnet paymaster does not use innerInput - innerInput: new Uint8Array(0), -}); - -// estimate gasLimit via paymaster -const gasLimit = await messagesContract.sendMessage.estimateGas(NEW_MESSAGE, { - customData: { - gasPerPubdata: utils.DEFAULT_GAS_PER_PUBDATA_LIMIT, - paymasterParams: paramsForFeeEstimation, - }, -}); - -// fee calculated in ETH will be the same in -// ERC20 token using the testnet paymaster -const fee = gasPrice * gasLimit; -``` - -1. Retrieve the testnet paymaster address. -2. Generate the paymaster parameters to estimate the transaction fees passing the paymaster address, token address, and - `ApprovalBased` as the paymaster flow type. -3. Retrieve the `gasLimit` of sending the transaction with the paymaster params. -4. Calculate the final estimated fee which is equal to `gasPrice` multiplied by `gasLimit`. - -### Send the transaction - -```typescript -// new paymaster params with fee as minimalAllowance - const paymasterParams = utils.getPaymasterParams(testnetPaymasterAddress, { - type: "ApprovalBased", - token: TOKEN_CONTRACT_ADDRESS, - // provide estimated fee as allowance - minimalAllowance: fee, - // empty bytes as testnet paymaster does not use innerInput - innerInput: new Uint8Array(0), - }); - - // full overrides object including maxFeePerGas and maxPriorityFeePerGas - const txOverrides = { - maxFeePerGas: gasPrice, - maxPriorityFeePerGas: "1", - gasLimit, - customData: { - gasPerPubdata: utils.DEFAULT_GAS_PER_PUBDATA_LIMIT, - paymasterParams, - } - } - - console.log(`Sign the transaction in your wallet`); - - // send transaction with additional paymaster params as overrides - const txHandle = await messagesContract.sendMessage(NEW_MESSAGE, txOverrides); -``` - -1. Create the new paymaster params with the calculated `fee` as `minimalAllowance` . -2. Complete the transaction overrides object with `maxFeePerGas`, `maxPriorityFeePerGas` and `gasPerPubdata` -3. Send the transaction including the `txOverrides` - -### Compare the final balance - -```typescript -ethBalance = await provider.getBalance(walletAddress) -tokenBalance = await tokenContract.balanceOf(walletAddress) -console.log(`Account ${walletAddress} now has ${ethers.formatEther(ethBalance)} ETH`); -console.log(`Account ${walletAddress} now has ${ethers.formatUnits(tokenBalance, 18)} tokens`); -``` - -Finally we retrieve and print the ETH and ERC20 balances to see how they’ve changed. - -## Run the script - -To run the script, first enter the addresses of the `ZeekMessages.sol` and `TestToken.sol` contracts that we -deployed previously ([Deploy your first contract](/zksync-era/guides/quick-start/deploy-your-first-contract) and -[Erc20 Token](/zksync-era/guides/quick-start/erc20-token)) in the following variables at the beginning of -the script: - -```typescript -// Address of the ZeekMessages contract -const ZEEK_MESSAGES_CONTRACT_ADDRESS = ""; -// Address of the ERC20 token contract -const TOKEN_CONTRACT_ADDRESS = "" -// Message to be sent to the contract -const NEW_MESSAGE = "This tx cost me no ETH!"; -``` - -Next, make sure the script file is selected in the Atlas editor and click on the “Deploy” button. - -![ERC20 interact script in Remix](/images/101-paymasters/atlas-paymaster-script.png) - -You’ll see the progress in the console. - -If everything worked as expected, only the ERC20 balance will decrease, meaning the fee was paid with the ERC20 token -instead of ETH. diff --git a/content/00.zksync-era/10.guides/10.quick-start/_paymaster_intro/_remix_paymaster_intro.md b/content/00.zksync-era/10.guides/10.quick-start/_paymaster_intro/_remix_paymaster_intro.md deleted file mode 100644 index 3a9dfc71..00000000 --- a/content/00.zksync-era/10.guides/10.quick-start/_paymaster_intro/_remix_paymaster_intro.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Paymaster with Remix ---- - -::callout{icon="i-heroicons-exclamation-triangle" color="amber"} -**The Remix provider does not support EIP712 transactions yet, which are required to interact with paymaster contracts. -Please use Atlas for this part.** -:: - -Click the button below to open the project in Remix and see the contract in the Remix code editor. - -:u-button{ icon="i-heroicons-code-bracket" size="lg" color="primary" variant="solid" :trailing="false" -to="https://remix.ethereum.org/?#activate=zkSync&call=zkSync//loadFromGithub//ZKsync-Community-Hub//zksync-quickstart-remix//" -target="_blank" label="Open project in Remix"} - -Once the project is imported, open the `scripts/paymaster-transaction.ts` file, which contains the code to send a -transaction via the paymaster. Let’s go through the most important parts: - -### Retrieve the token balance - -```typescript -// retrieve and print the current balances of the wallet -let ethBalance = await zkProvider.getBalance(walletAddress) -console.log(`Account ${walletAddress} has ${ethers.utils.formatEther(ethBalance)} ETH`); -let tokenBalance = await tokenContract.balanceOf(walletAddress) -console.log(`Account ${walletAddress} has ${ethers.utils.formatUnits(tokenBalance, 18)} tokens`); -``` - -In this part we’re retrieving the ETH and ERC20 token balances of the account. We’ll compare them after the transaction -is executed to see the difference. - -### Estimate transaction fee - -```typescript -// retrieve the testnet paymaster address -const testnetPaymasterAddress = await zkProvider.getTestnetPaymasterAddress(); - -console.log(`Testnet paymaster address is ${testnetPaymasterAddress}`); - -const gasPrice = await zkProvider.getGasPrice(); - -// define paymaster parameters for gas estimation -const paramsForFeeEstimation = utils.getPaymasterParams(testnetPaymasterAddress, { - type: "ApprovalBased", - token: TOKEN_CONTRACT_ADDRESS, - // set minimalAllowance to 1 for estimation - minimalAllowance: ethers.BigNumber.from(1), - // empty bytes as testnet paymaster does not use innerInput - innerInput: new Uint8Array(0), -}); - -// estimate gasLimit via paymaster -const gasLimit = await messagesContract.estimateGas.sendMessage(NEW_MESSAGE, { - customData: { - gasPerPubdata: utils.DEFAULT_GAS_PER_PUBDATA_LIMIT, - paymasterParams: paramsForFeeEstimation, - }, -}); - -// fee calculated in ETH will be the same in -// ERC20 token using the testnet paymaster -const fee = gasPrice * gasLimit; -``` - -In this part of the script we: - -1. Retrieve the testnet paymaster address. -2. Generate the paymaster parameters to estimate the transaction fees passing the paymaster address, token address, and - `ApprovalBased` as the paymaster flow type. -3. Retrieve the `gasLimit` of sending the transaction with the paymaster params. -4. Calculate the final estimated fee which is equal to `gasPrice` multiplied by `gasLimit`. - -### Send the transaction - -```typescript -// new paymaster params with fee as minimalAllowance -const paymasterParams = utils.getPaymasterParams(testnetPaymasterAddress, { - type: "ApprovalBased", - token: TOKEN_CONTRACT_ADDRESS, - // provide estimated fee as allowance - minimalAllowance: fee, - // empty bytes as testnet paymaster does not use innerInput - innerInput: new Uint8Array(0), -}); - -// full overrides object including maxFeePerGas and maxPriorityFeePerGas -const txOverrides = { - maxFeePerGas: gasPrice, - maxPriorityFeePerGas: "1", - gasLimit, - customData: { - gasPerPubdata: utils.DEFAULT_GAS_PER_PUBDATA_LIMIT, - paymasterParams, - } -} - -console.log(`Sign the transaction in your wallet`); - - // send transaction with additional paymaster params as overrides - const txHandle = await messagesContract.sendMessage(NEW_MESSAGE, txOverrides); -``` - -1. Create the new paymaster params with the calculated `fee` as `minimalAllowance` . -2. Complete the transaction overrides object with `maxFeePerGas`, `maxPriorityFeePerGas` and `gasPerPubdata` -3. Send the transaction including the `txOverrides` - -### Compare the final balance - -```typescript -ethBalance = await zkProvider.getBalance(walletAddress) -tokenBalance = await tokenContract.balanceOf(walletAddress) -console.log(`Account ${walletAddress} now has ${ethers.utils.formatEther(ethBalance)} ETH`); -console.log(`Account ${walletAddress} now has ${ethers.utils.formatUnits(tokenBalance, 18)} tokens`); -``` - -Finally we retrieve and print the ETH and ERC20 balances to see how they’ve changed. - -## Run the script - -To run the script, first enter the addresses of the `ZeekMessages.sol` and `TestToken.sol` contracts that we -deployed previously ([Deploy your first contract](/zksync-era/guides/quick-start/deploy-your-first-contract) and -[Erc20 Token](/zksync-era/guides/quick-start/erc20-token)) in the following variables at the beginning of -the script: - -```typescript -// Address of the ZeekMessages contract -const ZEEK_MESSAGES_CONTRACT_ADDRESS = ""; -// Address of the ERC20 token contract -const TOKEN_CONTRACT_ADDRESS = "" -// Message to be sent to the contract -const NEW_MESSAGE = "This tx cost me no ETH!"; -``` - -::callout{icon="i-heroicons-exclamation-triangle" color="amber"} -Open the "Deploy & run transactions" menu in Remix and select "Injected Provider - Metamask" -from the environment dropdown to target the network selected in your wallet when running scripts. -:: - -Next, make sure the script file is selected in the Remix editor and click on the “▶️” button. You’ll see the progress in the console. - -![Contract events in ZKsync explorer](/images/101-paymasters/remix-paymaster-tx.png) - -If everything worked as expected, only the ERC20 balance will decrease, meaning the fee was paid with the ERC20 token -instead of ETH. diff --git a/content/00.zksync-era/10.guides/20.zksync-101/00.index.md b/content/00.zksync-era/10.guides/20.zksync-101/00.index.md index 81594594..afc112e9 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/00.index.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/00.index.md @@ -38,76 +38,30 @@ Open a terminal and install ZKsync CLI with the following command: npm install -g zksync-cli ``` -## Setup local node - -This series of guides will use in memory anvil-zksync node which allows for quicker testing and debugging processes. -A great benefit of using a local node is that you will avoid incurring any actual transaction costs as the node provides -a set of rich wallets that come with more than enough ETH to use for development. - -### Run a local in memory anvil-zksync node - -To run a local in memory anvil-zksync node on your machine, you will need Docker running. -The easiest way to start Docker is to run the Docker Desktop app. - -We are going to use the "In memory node" module for our local node setup. - -1. Run the following command in your terminal: - - ```bash - zksync-cli dev config - ``` - - It will provide a list of available node types you can run locally. - -2. Use the arrow keys to navigate to "In memory node" and press **Enter** to select. - The next question will ask what additional modules you want to use. - Make sure additional modules are unselected for this setup and press **Enter** to finish the configuration. - - ```bash - ? Node to use (Use arrow keys) - ❯ In memory node - Quick startup, no persisted state, only L2 node - zkcli-in-memory-node - Dockerized node - Persistent state, includes L1 and L2 nodes - zkcli-dockerized-node - (Move up and down to reveal more choices) - ``` - - The in memory node module will run a lighter version of the ZKsync Era node - which is ideal for swift testing, prototyping, bootloader and system contract testing. - -3. Run the following command in your terminal to start up the node: - - ```bash - zksync-cli dev start - ``` - - anvil-zksync node includes pre-configured rich wallets for use, see [anvil-zksync rich wallets](/build/test-and-debug/in-memory-node#pre-configured-rich-wallets). - -Your anvil-zksync node is accessible at **[http://127.0.0.1:8011](http://127.0.0.1:8011/)**, ready for deployment or testing purposes. -You can use the Docker Desktop app to view logs from the running ZKsync Era node or use the `zksync-cli dev logs` command. - -When you are done running your anvil-zksync node, you can stop it with `zksync-cli dev stop`. -You can learn more about managing a local node with ZKsync CLI on [Running a node](/build/zksync-cli/running-a-node). - ## Create the ZKsync 101 project We have a template available for you to get started with quickly in the ZKsync 101 series. -In a directory where you want to create your project, run the following command in your terminal: +You can choose to use either EVM or EraVM to compile and deploy to ZKsync: -```sh -zksync-cli create zksync-101 --template zksync-101 -``` - -After you run the `create` command, the CLI will download and install packages for the project. -You should see a success message and instructions to get started with your project. +:display_partial{path="/_partials/_eravm_vs_evm"} -Since we are using a local in memory anvil-zksync node for development, we can use one of the -rich wallets for transactions and deployments. +
-Rename the `.env.example` to `.env` which includes the private key for the first rich wallet. - -::callout{icon="i-heroicons-exclamation-triangle" color="amber"} -Never save a real private key to the `.env` file! +::content-switcher +--- +items: [{ + label: 'EVM', + partial: 'zksync-101/_getting_started/_evm' +}, { + label: 'EraVM', + partial: 'zksync-101/_getting_started/_era-vm' +}] +--- :: +After you run the `create` command, the CLI will download and install packages for the project. +You should see a success message and instructions to get started with your project. + --- ## Next Steps diff --git a/content/00.zksync-era/10.guides/20.zksync-101/10.hello-zksync.md b/content/00.zksync-era/10.guides/20.zksync-101/10.hello-zksync.md index 7e7449b2..14bd065c 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/10.hello-zksync.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/10.hello-zksync.md @@ -9,7 +9,7 @@ In this section you will learn how to: :check-icon Craft a smart contract to fund Zeek's latest adventure. -:check-icon Deploy the contract onto your local in memory anvil-zksync node. +:check-icon Deploy the contract onto your local in-memory `anvil-zksync` node. :check-icon Interact with the contract with ZKsync CLI @@ -23,175 +23,32 @@ development experience building for ZKsync. Make sure to go through the setup provided in the initial [Getting started](/zksync-era/guides/zksync-101) section. :: -## Compile the CrowdfundingCampaign.sol contract +## Compile the `CrowdfundingCampaign.sol` contract -This guide introduces a crowdfunding campaign contract aimed at supporting Zeek's creative ventures. -Let's start by reviewing the starter contract `CrowdfundingCampaign.sol` in the -[`contracts/1-hello-zksync/CrowdfundingCampaign.sol` directory][crowdfunding-campaign-sol]. +To compile and deploy to ZKsync you can use either EVM or EraVM: -The `CrowdfundingCampaign` contract is designed for a simple crowdfunding campaign. -This contract features: +:display_partial{path="/_partials/_eravm_vs_evm"} -- A constructor to initialize the campaign's funding target. -- The `contribute` method to log funds, triggering `ContributionReceived` and `GoalReached` events. -- The `withdrawFunds` method, allowing the owner to collect accumulated funds post-goal achievement. -- The `getTotalFundsRaised` method to return the total amount of funds that's been raised. -- The `getFundingGoal` method to return the goal for the campaign to reach. +
-Run the compile script from your project in the terminal: - -```bash [npm] -npm run compile -``` - -Upon successful compilation, you'll receive output detailing the -`zksolc` and `solc` versions used during compiling and the number -of Solidity files compiled. - -```bash -Compiling contracts for ZKsync Era with zksolc v1.4.1 and solc v0.8.17 -Compiling 15 Solidity files -Successfully compiled 15 Solidity files -``` - -The compiled artifacts will be located in the `/artifacts-zk` folder. - -::callout{icon="i-heroicons-information-circle" color="blue"} -Smart contracts deployed to ZKsync must be compiled using our custom compiler. -`zksolc` is the compiler used for Solidity. -This is why they're placed in the `artifacts-zk` folder! +::content-switcher +--- +items: [{ + label: 'EVM', + partial: '_hello/_evm' +}, { + label: 'EraVM', + partial: '_hello/_era-vm' +}] +--- :: -## Deploy the contract - -The deployment script is located at -[`/deploy/1-hello-zksync/deploy.ts`][deploy-script]. - -**Key Components:** - -- **contractArtifactName:** Identifies the `CrowdfundingCampaign` contract for deployment. -- **constructorArguments:** Sets initialization parameters for the contract. In this case, -the fundraising goal, converted from ether to wei to match Solidity's `uint256` type. - -1. Execute the deployment command from `package.json`. - -```bash [npm] -npm run deploy:hello-zksync -``` - -Upon successful deployment, you'll receive output detailing the deployment process, -including the contract address, source, and encoded constructor arguments: - -```bash -Starting deployment process of "CrowdfundingCampaign"... -Estimated deployment cost: 0.0065057128 ETH - -"CrowdfundingCampaign" was successfully deployed: - - Contract address: 0x26b368C3Ed16313eBd6660b72d8e4439a697Cb0B - - Contract source: contracts/1-hello-zksync/CrowdfundingCampaign.sol:CrowdfundingCampaign - - Encoded constructor arguments: 0x00000000000000000000000000000000000000000000000000470de4df820000 -``` - -## Interact with the contract - -Now that our contract is deployed to our local in memory anvil-zksync node, let's interact with it! -We initially set up the crowdfunding campaign with an amount of `.02 ETH` for the goal. - -### Read from the contract using ZKsync CLI - -We can confirm the amount by calling the `getFundingGoal` method using ZKsync CLI. - -In the terminal, run the following in your project directory, -replacing the contract address with your contract's address: - -```bash -zksync-cli contract read \ ---chain in-memory-node \ ---contract <0xYOUR_CONTRACT_ADDRESS> \ ---abi artifacts-zk/contracts/1-hello-zksync/CrowdfundingCampaign.sol/CrowdfundingCampaign.json -``` - -The CLI will prompt you with a list of available methods to select from. Navigate with the arrow keys and press **Enter** -on the method `getFundingGoal()`. - -```bash -Using provided ABI file -? Contract method to call (Use arrow keys) - ──────────────── Provided contract ──────────────── -❯ getFundingGoal() view returns (uint256) - getTotalFundsRaised() view returns (uint256) - owner() view returns (address) - ─────────────────────────────────────────────────── - Type method manually -``` - -- The `--chain` option defines the network we want to use, which is our local in-memory node. -- The `--contract` is the address of the contract you just deployed. -- The `--abi` provides the ABI to decode the contract and provide the list of methods to select from. - Without the ABI provided, you will have to manually type out the method name. - -You will get a response with the amount that we passed in to the constructor on deploy: - -```bash -? Contract method to call getFundingGoal() view returns (uint256) - -✔ Method response (raw): 0x00000000000000000000000000000000000000000000000000470de4df820000 -✔ Decoded method response: 20000000000000000 -``` - -### Write to the contract using ZKsync CLI - -Let's fund this crowdfunding campaign and make Zeek happy! - -We will write to the contract using ZKsync CLI, which requires a private key. -In this demonstration we will use the second wallet provided in the list of rich wallets. - -In the terminal, run the following command with your deployed contract's address: - -```bash -zksync-cli contract write \ ---chain in-memory-node \ ---contract <0xCONTRACT_ADDRESS> \ ---abi artifacts-zk/contracts/1-hello-zksync/CrowdfundingCampaign.sol/CrowdfundingCampaign.json \ ---pk 0xac1e735be8536c6534bb4f17f06f6afc73b2b5ba84ac2cfb12f7461b20c0bbe3 \ ---value 0.5 -``` - -In the prompt, press **Enter** on the `contribute() payable` method. -The CLI will then output the transaction information upon success. - -We can read the transaction data of the contribution with the following: - -```bash -zksync-cli transaction info \ ---tx <0xTRANSACTION_HASH> \ ---chain in-memory-node -``` - -Our crowdfund has reached its funding goal! Let's withdraw the funds for the owner: - -```bash -zksync-cli contract write \ ---chain in-memory-node \ ---contract <0xCONTRACT_ADDRESS> \ ---pk 0x7726827caac94a7f9e1b160f7ea819f172f7b6f9d2a97f992c38edeab82d4110 -``` - -The CLI will prompt for the method to call, we will call `withdrawFunds()`: - -```bash -? Enter method to call withdrawFunds() -``` - -Congratulations! You've deployed a crowdfunding contract and learned how -to interact with the deployed contract using ZKsync CLI! - ## Takeaways - **EVM Compatibility:** ZKsync is EVM compatible and you can write smart contracts in Solidity or Vyper. - **Custom Compilation:** Contracts deployed to ZKsync are compiled using `zksolc` or `zkvyper` as they generate a special bytecode for ZKsync's ZKEVM. -- **Development Tools:** In memory anvil-zksync node is a quick and easy local node environment to deploy to, +- **Development Tools:** in-memory `anvil-zksync` node is a quick and easy local node environment to deploy to, saving costs on deployment while developing. - **ZKsync CLI:** A powerful command line tool to interact with contracts easily. @@ -208,6 +65,3 @@ and paymasters. - **Join the Community:** Engage with the ZKsync developer community through forums, Discord channels, Dev Discussions, or GitHub repositories. Share your experiences, ask questions, and collaborate on projects. - -[crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/1-hello-zksync/CrowdfundingCampaign.sol -[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/1-hello-zksync/deploy.ts diff --git a/content/00.zksync-era/10.guides/20.zksync-101/20.contract-factory.md b/content/00.zksync-era/10.guides/20.zksync-101/20.contract-factory.md index 0aaca574..507fa6ec 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/20.contract-factory.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/20.contract-factory.md @@ -22,138 +22,18 @@ contract instances from a single "factory" contract. It's essentially a contract that creates other contracts, streamlining and organizing the deployment of numerous similar contracts efficiently. +::content-switcher +--- +items: [{ + label: 'EVM', + partial: '_factory/_evm' +}, { + label: 'EraVM', + partial: '_factory/_era-vm' +}] --- - -## Setup the project - -Make sure to go through the setup provided in the initial [Getting started](/build/start-coding/zksync-101) section. -You will have downloaded the 101 project through ZKsync CLI `create` and started up a local in memory anvil-zksync node for development. - -If you haven't started up your local in memory anvil-zksync node or you're not sure, run the following: - -```bash -zksync-cli dev restart -``` - -## Compile the contracts - -This section will focus on compiling and deploying the `CrowdfundingFactory.sol` -contract that is provided under the [`/contracts/2-contract-factory` directory][crowdfunding-factory-sol]. - -The `CrowdfundingFactory.sol`contract will be used to deploy multiple instances of -the `CrowdfundingCampaign.sol` contract from the previous guide. -This contract factory approach streamlines the deployment of crowdfunding campaigns, -making it efficient to launch and manage multiple campaigns. - -The `CrowdfundingFactory` contract automates the creation and oversight of -`CrowdfundingCampaign` contracts, each with their own distinct funding goals. -The factory contract features: - -- **Campaign Creation**: Utilizes the `createCampaign` method to initiate a new -`CrowdfundingCampaign` contract. This function takes a `fundingGoal` as an argument, -deploys a new campaign contract with this goal, and tracks the created campaign in the -`campaigns` array. -- **Campaign Tracking**: The `getCampaigns` method offers a view into all the campaigns -created by the factory, allowing for easy access and management of multiple crowdfunding -initiatives. - -Run the compile script from your project in the terminal: - -```bash [npm] -npm run compile -``` - -### Deploy CrowdfundingCampaigns via the CrowdfundingFactory - -This section outlines the steps to deploy the `CrowdfundingCampaign` contract -using our new `CrowdfundingFactory`. - -The deployment script is located at [`/deploy/2-contract-factory/deploy.ts`][deploy-script]. - -The deploy script: - -- deploys a single `CrowdfundingFactory`. -- saves an instance of the deployed factory to `factoryContract`. - This gives us access to the factory's functionalities. -- The `createCampaign` method is called on this instance to create - and deploy a new crowdfunding campaign contract. - -Run the deployment command. - -```bash [npm] -npm run deploy:crowdfunding-factory -``` - -Upon successful deployment, you'll receive output detailing the deployment process, -including the contract address, source, and encoded constructor arguments: - -```bash -Starting deployment process of "CrowdfundingFactory"... -Estimated deployment cost: 0.0002500236 ETH - -"CrowdfundingFactory" was successfully deployed: - - Contract address: <0xFACTORY_CONTRACT_ADDRESS> - - Contract source: contracts/CrowdfundFactory.sol:CrowdfundingFactory - - Encoded constructor arguments: 0x - -✅ Deployment and campaign creation complete! -``` - -## Create another campaign with ZKsync CLI - -We've got one crowdfunding campaign created from the deployment script, -let's create another through ZKsync CLI! - -Run the following command: - -```bash -zksync-cli contract write \ ---chain in-memory-node \ ---contract <0xFACTORY_CONTRACT_ADDRESS> \ ---pk 0x7726827caac94a7f9e1b160f7ea819f172f7b6f9d2a97f992c38edeab82d4110 -``` - -The CLI will prompt you with a few questions. -We want to call the method `createCampaign(uint256 fundingGoal)` -and provide a funding goal in wei: - -```bash -? Enter method to call createCampaign(uint256 fundingGoal) -? Provide method arguments: -? [1/1] fundingGoal (uint256) 200000000000000000 -``` - -Now that we've created a second crowdfunding campaign, -let's check the list of campaigns! - -Run the following command from within your project directory. - -```bash -zksync-cli contract read \ ---chain in-memory-node \ ---contract <0xFACTORY_CONTRACT_ADDRESS> \ ---abi artifacts-zk/contracts/2-contract-factory/CrowdfundingFactory.sol/CrowdfundingFactory.json -``` - -::callout{icon="i-heroicons-information-circle" color="blue"} -We pass the ABI in to help decode the output. -Without the ABI, the CLI will return the raw response. :: -The CLI will prompt with a list of the available methods from the contract. -Navigate with the arrow keys and press **Enter** on `getCampaigns() view returns (address[])`. - -The ClI returns the method's response in raw format along with the decoded format -because we passed in the ABI. - -You should see two addresses in the decoded method response, the first created from -the deploy script and the second for the campaign you created with ZKsync CLI! - -```bash -✔ Method response (raw): 0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000020000000000000000000000009bf2281f53847387e1d8b5645cfcfbea576c4397000000000000000000000000ca55c6bbb6b122058ed742c33859f3621bc8030c -✔ Decoded method response: 0x9bf2281F53847387e1d8b5645cFCfbea576c4397,0xca55c6BBB6B122058Ed742C33859F3621bc8030c -``` - ## Takeaways - **Contract Factories:** Utilizing contract factories significantly streamlines @@ -179,6 +59,3 @@ experience and contract flexibility. - **Community Engagement and Contribution:** Join the vibrant ZKsync developer community. Participate in forums, Discord, or GitHub discussions. Sharing insights, asking queries, and contributing can enrich the ecosystem and your understanding of ZKsync. - -[crowdfunding-factory-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/2-contract-factory/CrowdfundingFactory.sol -[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/2-contract-factory/deploy.ts diff --git a/content/00.zksync-era/10.guides/20.zksync-101/30.testing.md b/content/00.zksync-era/10.guides/20.zksync-101/30.testing.md index 14d127a1..9b0a9baf 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/30.testing.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/30.testing.md @@ -3,11 +3,10 @@ title: Testing description: Discover how to effectively test smart contracts on ZKsync Era ecosystem. --- -Welcome back to our ZKsync 101 series, your fast-track to ZKsync development! In this -third guide, we transition from deploying and managing contracts to the critical phase -of testing. This guide will walk you through the steps to ensure your `CrowdfundingCampaign` -contract, introduced in our first guide and efficiently deployed through contract factories -in the second, work flawlessly. +Welcome back to our ZKsync 101 series, your fast-track to ZKsync development! +In this third guide, we transition from deploying and managing contracts to the critical phase of testing. +This guide will walk you through the steps to ensure your `CrowdfundingCampaign` contract, +introduced in our first guide and efficiently deployed through contract factories in the second, work flawlessly. :check-icon Elevate your ZKsync toolkit with robust contract testing techniques. @@ -15,118 +14,17 @@ in the second, work flawlessly. :check-icon Use Hardhat to write and run tests, ensuring your campaigns are ready. -## Setup the project - -Make sure to go through the setup provided in the initial [Getting started](/zksync-era/guides/zksync-101) section. -You will have downloaded the 101 project through ZKsync CLI `create`. -Since we are using `hardhat-zksync` for testing, you do not need to have the -in memory anvil-zksync node running for this section. - -If your local `anvil-zksync` node is running, stop it with the following command: - -```bash -zksync-cli dev stop -``` - -## `hardhat-zksync-node` - -Testing contracts requires a more structured setup. -We'll use `hardhat-zksync-node` which is a part of the `hardhat-zksync` package to run tests against its own implementation -of the in memory node. - -Within the `hardhat.config.ts`, you'll observe the `zksync` flag set to `true` under the -`hardhat` network, indicating the integration with ZKsync's testing environment. - -```typescript [hardhat.config.ts] -const config: HardhatUserConfig = { - defaultNetwork: "inMemoryNode" - networks: { - ... - hardhat: { - zksync: true, - }, - ... - } - ... -} -``` - -Your project has npm scripts for testing that set the `--network` to `"hardhat"`. - -Secondly within the `hardhat.config.ts`, you'll observe the importing of -`@nomicfoundation/hardhat-chai-matchers`. This plugin provides Hardhat with an extended -suite of assertion methods tailored for contract testing, significantly improving the testing -toolkit available for your project. - -```typescript -import "@nomicfoundation/hardhat-chai-matchers"; -``` - +::content-switcher --- - -## Compile the `CrowdfundingCampaign` contract - -Now that our setup is complete, it's time to focus on the core of this -guide - testing our `CrowdfundingCampaign.sol` contract. - -Thorough testing involves scrutinizing every function and aspect of our contract, -including potential failure scenarios. In this guide, we'll focus in on the `contribute` -method to ensure it's tested. - -To compile the contracts in your project, run the following command: - -```bash [npm] -npm run compile -``` - +items: [{ + label: 'EVM', + partial: '_testing/_evm' +}, { + label: 'EraVM', + partial: '_testing/_era-vm' +}] --- - -## Test `CrowdfundingCampaign` - -This section describes testing the `CrowdfundingCampaign.sol` contract. -Let's review the contract at [`test/1-hello-zksync/CrowdfundingCampaign.test.ts`][crowdfunding-campaign-test] - -- **Initialization**: Each test case initializes with fresh contract instances in the `beforeEach` - and predefined rich wallet accounts to simulate various contributors and the contract owner. -- **Deployment**: The `CrowdfundingCampaign` contract is deployed using - the `deployContract` utility, setting a specific funding goal for each test scenario. - -**`contribute` Method Tests:** - -- **Zero Contributions**: Verifies that the contract correctly rejects contribution attempts - with zero value, ensuring the integrity of the contribution process. -- **Funds Aggregation**: Tests the contract's ability to accurately aggregate contributions - from multiple addresses and update the `totalFundsRaised` accordingly. -- **Goal Achievement**: Checks for the `GoalReached` event emission upon meeting the funding goal, - confirming the contract's responsiveness to achieving its set target. - -Run the tests with the following command: - -```bash [npm] -npm run test:crowdfunding-campaign -``` - -Upon completion, the test suite will provide a summary of all executed tests, -indicating their success or failure: - -```bash - CrowdfundingCampaign - contribute - ✔ should reject contributions of 0 - ✔ should aggregate contributions in totalFundsRaised (150ms) - ✔ should emit GoalReached event when funding goal is met (81ms) - withdrawFunds - ✔ should revert if called by a non-owner - ✔ should revert if funding goal hasn't been reached - ✔ should transfer the funds to the owner when funds have been raised (229ms) - getFundingGoal - ✔ should return the correct funding goal - getTotalFundsRaised - ✔ should return 0 when no contributions have been made - - - 8 passing (2s) -``` +:: 🎉 Congratulations! Your `CrowdfundingCampaign` contract has been thoroughly tested and is ready for action. @@ -156,5 +54,3 @@ experience and contract flexibility. - **Community Engagement and Contribution:** Join the vibrant ZKsync developer community. Participate in forums, Discord, or GitHub discussions. Sharing insights, asking queries, and contributing can enrich the ecosystem and your understanding of ZKsync. - -[crowdfunding-campaign-test]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/test/1-hello-zksync/CrowdfundingCampaign.test.ts diff --git a/content/00.zksync-era/10.guides/20.zksync-101/40.upgrading.md b/content/00.zksync-era/10.guides/20.zksync-101/40.upgrading.md index 50c655da..ec66bb15 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/40.upgrading.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/40.upgrading.md @@ -16,18 +16,16 @@ lead you through the strategies and practices for making the `CrowdfundingCampai ## Setup the project Make sure to go through the setup provided in the initial [Getting started](/build/start-coding/zksync-101) section. -You will have downloaded the 101 project through ZKsync CLI `create` and started up a local anvil-zksync node for development. - -If you haven't started up your local `anvil-zksync` node or you're not sure, run the following: - -```bash -zksync-cli dev restart -``` +You will have downloaded the 101 project through ZKsync CLI `create` and started up a local in-memory node for development. --- Select your preferred upgrade mechanism: +::callout{icon="i-heroicons-information-circle" color="blue"} +Both EVM and EraVM templates can be used here. +:: + ::content-switcher --- items: [{ diff --git a/content/00.zksync-era/10.guides/20.zksync-101/50.paymaster.md b/content/00.zksync-era/10.guides/20.zksync-101/50.paymaster.md index 6c8665cd..0f112bad 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/50.paymaster.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/50.paymaster.md @@ -9,6 +9,11 @@ of smart contract deployment and the creation of contract factories to explore t in the ZKsync ecosystem. This guide will illuminate the power of paymasters to revolutionize transaction fee management and enhance user experiences within your dApps. +::callout{icon="i-heroicons-exclamation-triangle" color="amber"} +Note: Paymaster contracts must be compiled for EraVM. +Use the `zksync-101-eravm` template. +:: + :check-icon Delve deeper into ZKsync development with the introduction of paymasters. :check-icon Learn how paymasters can cover transaction fees for your dApp users, enhancing accessibility and user experience. @@ -24,6 +29,15 @@ potentially making certain transactions free for end-users. This feature is particularly useful for dApp developers looking to improve their platform's accessibility and user experience by covering transaction fees on behalf of their users. +Every paymaster has the following two functions: + +- `validateAndPayForPaymasterTransaction` : this function uses the transaction parameters (fields like `from`, `amount` , `to` + ) to execute the required validations and pay for the transaction fee. + +- `postTransaction`: this optional function runs after the transaction is executed. + +![zksync paymaster](/images/101-paymasters/zksync-paymaster.png) + ## Built-in Paymaster Flows Paymasters can operate under various flows, some of which may require user interaction, such as setting allowances @@ -71,11 +85,10 @@ items: [{ ## Takeaways -- **Comprehensive Understanding of Paymaster Contracts:** This guide has provided a detailed look at both the -`ApprovalFlowPaymaster` and the `GaslessPaymaster` contracts, illustrating how they manage transaction fees -in ZKsync. These paymasters are pivotal in handling gas payments, offering a more accessible transaction -experience for users. -- **Flexibility and User Empowerment:** By covering the transaction fees through ERC20 tokens or general subsidies, these +- Paymasters on ZKsync allow any account to pay fees with ERC20 tokens or enable gasless transactions. +- Paymasters are smart contracts that can have any validations and rules. +- To send a transaction through a paymaster, we only need to include additional parameters in the transaction. +- By covering the transaction fees through ERC20 tokens or general subsidies, these paymaster contracts offer significant flexibility and reduce the friction typically associated with on-chain interactions. This feature enhances user engagement and adoption of dApps. diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_factory/_era-vm.md b/content/00.zksync-era/10.guides/20.zksync-101/_factory/_era-vm.md new file mode 100644 index 00000000..7afa74f9 --- /dev/null +++ b/content/00.zksync-era/10.guides/20.zksync-101/_factory/_era-vm.md @@ -0,0 +1,92 @@ +--- +title: EraVM - Factory +--- + +:display_partial{path="/_partials/101/factory/_setup"} + +If you haven't started up your local in-memory `anvil-zksync` node or you're not sure, run the following: + +```bash +zksync-cli dev restart +``` + +## Compile the contracts + +This section will focus on compiling and deploying the `CrowdfundingFactory.sol` +contract that is provided under the [`/contracts/2-contract-factory` directory](https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/2-contract-factory). + +:display_partial{path="/_partials/101/factory/_setup2"} + +The deployment script is located at [`/deploy/2-contract-factory/deploy.ts`](https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/2-contract-factory/deploy.ts). + +:display_partial{path="/_partials/101/factory/_deploy"} + +Upon successful deployment, you'll receive output detailing the deployment process, +including the contract address, source, and encoded constructor arguments: + +```bash +Starting deployment process of "CrowdfundingFactory"... +Estimated deployment cost: 0.0002500236 ETH + +"CrowdfundingFactory" was successfully deployed: + - Contract address: <0xFACTORY_CONTRACT_ADDRESS> + - Contract source: contracts/CrowdfundFactory.sol:CrowdfundingFactory + - Encoded constructor arguments: 0x + +✅ Deployment and campaign creation complete! +``` + +## Create another campaign with ZKsync CLI + +We've got one crowdfunding campaign created from the deployment script, +let's create another through ZKsync CLI! + +Run the following command: + +```bash +zksync-cli contract write \ +--chain in-memory-node \ +--contract <0xFACTORY_CONTRACT_ADDRESS> \ +--pk 0x7726827caac94a7f9e1b160f7ea819f172f7b6f9d2a97f992c38edeab82d4110 +``` + +The CLI will prompt you with a few questions. +We want to call the method `createCampaign(uint256 fundingGoal)` +and provide a funding goal in wei: + +```bash +? Enter method to call createCampaign(uint256 fundingGoal) +? Provide method arguments: +? [1/1] fundingGoal (uint256) 200000000000000000 +``` + +Now that we've created a second crowdfunding campaign, +let's check the list of campaigns! + +Run the following command from within your project directory. + +```bash +zksync-cli contract read \ +--chain in-memory-node \ +--contract <0xFACTORY_CONTRACT_ADDRESS> \ +--abi artifacts-zk/contracts/2-contract-factory/CrowdfundingFactory.sol/CrowdfundingFactory.json +``` + +::callout{icon="i-heroicons-information-circle" color="blue"} +We pass the ABI in to help decode the output. +Without the ABI, the CLI will return the raw response. +:: + +The CLI will prompt with a list of the available methods from the contract. +Navigate with the arrow keys and press **Enter** on `getCampaigns() view returns (address[])`. + +The ClI returns the method's response in raw format along with the decoded format +because we passed in the ABI. + +You should see two addresses in the decoded method response, the first created from +the deploy script and the second for the campaign you created with ZKsync CLI! + +```bash +✔ Method response (raw): 0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000020000000000000000000000009bf2281f53847387e1d8b5645cfcfbea576c4397000000000000000000000000ca55c6bbb6b122058ed742c33859f3621bc8030c +✔ Decoded method response: 0x9bf2281F53847387e1d8b5645cFCfbea576c4397,0xca55c6BBB6B122058Ed742C33859F3621bc8030c +``` diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_factory/_evm.md b/content/00.zksync-era/10.guides/20.zksync-101/_factory/_evm.md new file mode 100644 index 00000000..097528a6 --- /dev/null +++ b/content/00.zksync-era/10.guides/20.zksync-101/_factory/_evm.md @@ -0,0 +1,24 @@ +--- +title: EVM - Factory +--- + +:display_partial{path="/_partials/101/factory/_setup"} + +## Compile the contracts + +This section will focus on compiling and deploying the `CrowdfundingFactory.sol` +contract that is provided under the [`/contracts/2-contract-factory` directory](https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/evm/contracts/2-contract-factory). + +:display_partial{path="/_partials/101/factory/_setup2"} + +The deployment script is located at [`/deploy/2-contract-factory/deploy.ts`](https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/evm/deploy/2-contract-factory/deploy.ts). + +:display_partial{path="/_partials/101/factory/_deploy"} + +Upon successful deployment, you'll receive the deployed factory and campaign addresses: + +```bash +🏭 CrowdfundingFactory address: <0xFACTORY_CONTRACT_ADDRESS> +🚀 New CrowdfundingCampaign deployed at: <0xCAMPAIGN_ADDRESS> +✅ Deployment and campaign creation complete! +``` diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_getting_started/_era-vm.md b/content/00.zksync-era/10.guides/20.zksync-101/_getting_started/_era-vm.md new file mode 100644 index 00000000..1a76c52d --- /dev/null +++ b/content/00.zksync-era/10.guides/20.zksync-101/_getting_started/_era-vm.md @@ -0,0 +1,9 @@ +--- +title: EraVM - Create Template +--- + +In a directory where you want to create your project, run the following command in your terminal: + +```sh +zksync-cli create zksync-101 --template zksync-101-eravm +``` diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_getting_started/_evm.md b/content/00.zksync-era/10.guides/20.zksync-101/_getting_started/_evm.md new file mode 100644 index 00000000..af2917b3 --- /dev/null +++ b/content/00.zksync-era/10.guides/20.zksync-101/_getting_started/_evm.md @@ -0,0 +1,9 @@ +--- +title: EVM - Create Template +--- + +In a directory where you want to create your project, run the following command in your terminal: + +```sh +zksync-cli create zksync-101 --template zksync-101-evm +``` diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_hello/_era-vm.md b/content/00.zksync-era/10.guides/20.zksync-101/_hello/_era-vm.md new file mode 100644 index 00000000..c17169b2 --- /dev/null +++ b/content/00.zksync-era/10.guides/20.zksync-101/_hello/_era-vm.md @@ -0,0 +1,202 @@ +--- +title: EraVM - Hello ZKsync +--- + +:display_partial{path="/_partials/101/hello/_campaign"} + +Run the compile script from your project in the terminal: + +:display_partial{path="/_partials/commands/_compile"} + +Upon successful compilation, you'll receive output detailing the +`zksolc` and `solc` versions used during compiling and the number +of Solidity files compiled. + +```bash +Compiling contracts for ZKsync Era with zksolc v1.5.13 and solc v0.8.17 +Compiling 15 Solidity files +Successfully compiled 15 Solidity files +``` + +The compiled artifacts will be located in the `/artifacts-zk` folder. + +::callout{icon="i-heroicons-information-circle" color="blue"} +Smart contracts deployed to ZKsync must be compiled using our custom compiler. +`zksolc` is the compiler used for Solidity. +This is why they're placed in the `artifacts-zk` folder! +:: + +## Setup local node + +This series of guides will use in-memory `anvil-zksync` node which allows for quicker testing and debugging processes. +A great benefit of using a local node is that you will avoid incurring any actual transaction costs as the node provides +a set of rich wallets that come with more than enough ETH to use for development. + +::callout{icon="i-heroicons-light-bulb"} +`anvil-zksync` can be used with EraVM or EVM. For EVM contracts, you can also use any standard EVM local node like [`anvil`](https://book.getfoundry.sh/anvil/). +:: + +### Run a local node + +To run a local in-memory `anvil-zksync` node on your machine, you will need Docker running. +The easiest way to start Docker is to run the Docker Desktop app. + +We are going to use the "in-memory node" module for our local node setup. + +1. Run the following command in your terminal: + + ```bash + zksync-cli dev config + ``` + + It will provide a list of available node types you can run locally. + +2. Use the arrow keys to navigate to "in-memory node" and press **Enter** to select. + The next question will ask what additional modules you want to use. + Make sure additional modules are unselected for this setup and press **Enter** to finish the configuration. + + ```bash + ? Node to use (Use arrow keys) + ❯ in-memory node - Quick startup, no persisted state, only L2 node - zkcli-in-memory-node + Dockerized node - Persistent state, includes L1 and L2 nodes - zkcli-dockerized-node + (Move up and down to reveal more choices) + ``` + + The in-memory node module will run a lighter version of the ZKsync Era node + which is ideal for swift testing, prototyping, bootloader and system contract testing. + +3. Run the following command in your terminal to start up the node: + + ```bash + zksync-cli dev start + ``` + + `anvil-zksync` node includes pre-configured rich wallets for use, see [anvil-zksync rich wallets](/build/test-and-debug/in-memory-node#pre-configured-rich-wallets). + +Your `anvil-zksync` node is accessible at **[http://127.0.0.1:8011](http://127.0.0.1:8011/)**, ready for deployment or testing purposes. +You can use the Docker Desktop app to view logs from the running ZKsync Era node or use the `zksync-cli dev logs` command. + +When you are done running your `anvil-zksync` node, you can stop it with `zksync-cli dev stop`. +You can learn more about managing a local node with ZKsync CLI on [Running a node](/build/zksync-cli/running-a-node). + +### Configuring a Hardhat Wallet + +Since we are using a local in-memory `anvil-zksync` node for development, we can use one of the +rich wallets for transactions and deployments. + +Copy the private key for the first rich wallet from `.env.example` to the `.env` file. + +::callout{icon="i-heroicons-exclamation-triangle" color="amber"} +Never save a real private key to the `.env` file! +:: + +## Deploy the contract + +The deployment script is located at +[`/deploy/1-hello-zksync/deploy.ts`](https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/1-hello-zksync/deploy.ts). + +:display_partial{path="/_partials/101/hello/_deploy"} + +Upon successful deployment, you'll receive output detailing the deployment process, +including the contract address, source, and encoded constructor arguments: + +```bash +Starting deployment process of "CrowdfundingCampaign"... +Estimated deployment cost: 0.0065057128 ETH + +"CrowdfundingCampaign" was successfully deployed: + - Contract address: 0x26b368C3Ed16313eBd6660b72d8e4439a697Cb0B + - Contract source: contracts/1-hello-zksync/CrowdfundingCampaign.sol:CrowdfundingCampaign + - Encoded constructor arguments: 0x00000000000000000000000000000000000000000000000000470de4df820000 +``` + +:display_partial{path="/_partials/101/hello/_interact"} + +### Read from the contract using ZKsync CLI + +We can confirm the amount by calling the `getFundingGoal` method using ZKsync CLI. + +In the terminal, run the following in your project directory, +replacing the contract address with your contract's address: + +```bash +zksync-cli contract read \ +--chain in-memory-node \ +--contract <0xYOUR_CONTRACT_ADDRESS> \ +--abi artifacts-zk/contracts/1-hello-zksync/CrowdfundingCampaign.sol/CrowdfundingCampaign.json +``` + +The CLI will prompt you with a list of available methods to select from. Navigate with the arrow keys and press **Enter** +on the method `getFundingGoal()`. + +```bash +Using provided ABI file +? Contract method to call (Use arrow keys) + ──────────────── Provided contract ──────────────── +❯ getFundingGoal() view returns (uint256) + getTotalFundsRaised() view returns (uint256) + owner() view returns (address) + ─────────────────────────────────────────────────── + Type method manually +``` + +- The `--chain` option defines the network we want to use, which is our local in-memory node. +- The `--contract` is the address of the contract you just deployed. +- The `--abi` provides the ABI to decode the contract and provide the list of methods to select from. + Without the ABI provided, you will have to manually type out the method name. + +You will get a response with the amount that we passed in to the constructor on deploy: + +```bash +? Contract method to call getFundingGoal() view returns (uint256) + +✔ Method response (raw): 0x00000000000000000000000000000000000000000000000000470de4df820000 +✔ Decoded method response: 20000000000000000 +``` + +### Write to the contract using ZKsync CLI + +Let's fund this crowdfunding campaign and make Zeek happy! + +We will write to the contract using ZKsync CLI, which requires a private key. +In this demonstration we will use the second wallet provided in the list of rich wallets. + +In the terminal, run the following command with your deployed contract's address: + +```bash +zksync-cli contract write \ +--chain in-memory-node \ +--contract <0xCONTRACT_ADDRESS> \ +--abi artifacts-zk/contracts/1-hello-zksync/CrowdfundingCampaign.sol/CrowdfundingCampaign.json \ +--pk <0xDEPLOYER_PRIVATE_KEY> \ +--value 0.5 +``` + +In the prompt, press **Enter** on the `contribute() payable` method. +The CLI will then output the transaction information upon success. + +We can read the transaction data of the contribution with the following: + +```bash +zksync-cli transaction info \ +--tx <0xTRANSACTION_HASH> \ +--chain in-memory-node +``` + +Our crowdfund has reached its funding goal! Let's withdraw the funds for the owner: + +```bash +zksync-cli contract write \ +--chain in-memory-node \ +--contract <0xCONTRACT_ADDRESS> \ +--pk <0xDEPLOYER_PRIVATE_KEY> +``` + +The CLI will prompt for the method to call, we will call `withdrawFunds()`: + +```bash +? Enter method to call withdrawFunds() +``` + +Congratulations! You've deployed a crowdfunding contract and learned how +to interact with the deployed contract using ZKsync CLI! diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_hello/_evm.md b/content/00.zksync-era/10.guides/20.zksync-101/_hello/_evm.md new file mode 100644 index 00000000..c3d13e2a --- /dev/null +++ b/content/00.zksync-era/10.guides/20.zksync-101/_hello/_evm.md @@ -0,0 +1,80 @@ +--- +title: EVM - Hello ZKsync +--- + +:display_partial{path="/_partials/101/hello/_campaign"} + +:display_partial{path="/_partials/commands/_compile"} + +Upon successful compilation, you'll receive output detailing the typings and Solidity files compiled. + +```bash +Generating typings for: 20 artifacts in dir: typechain-types for target: ethers-v6 +Successfully generated 78 typings! +Compiled 20 Solidity files successfully +``` + +The compiled artifacts will be located in the `/artifacts` folder. + +### Run a local node + +For this section, we will deploy to a local Hardhat node. +Run the command below to start a persistent in-memory node: + +```bash +npx hardhat node +``` + +### Configuring a Hardhat Wallet + +Since we are using a local Hardhat in-memory node for development, we can use one of the +rich wallets for transactions and deployments. + +Copy one of the private keys logged after starting the node to the `.env` file, using the `.env.example` file as an example. + +## Deploy the contract + +The deployment script is located at +[`/deploy/1-hello-zksync/deploy.ts`](https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/evm/deploy/1-hello-zksync/deploy.ts). + +:display_partial{path="/_partials/101/hello/_deploy"} + +Upon successful deployment, you'll receive output showing the contract name and address. + +```bash +Deploying CrowdfundingCampaign contract to localhost +CrowdfundingCampaign deployed to 0x5FbDB2315678afecb367f032d93F642f64180aa3 +``` + +:display_partial{path="/_partials/101/hello/_interact"} + +### Interact with contract + +Let's try interacting with the deployed contract. + +In the `deploy/1-hello-zksync/interact.ts` script, use your deployed contract address for the `CONTRACT_ADDRESS` variable. + +Then, run the script: + +::code-group + +```bash [npm] +npm run interact:hello-zksync +``` + +```bash [yarn] +yarn interact:hello-zksync +``` + +```bash [pnpm] +pnpm interact:hello-zksync +``` + +```bash [bun] +bun interact:hello-zksync +``` + +:: + +Congratulations! You've deployed a crowdfunding contract and learned how +to interact with the deployed contract using Hardhat! diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_paymasters/_approval_paymaster_flow.md b/content/00.zksync-era/10.guides/20.zksync-101/_paymasters/_approval_paymaster_flow.md index cdbbd2c1..086b99f7 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/_paymasters/_approval_paymaster_flow.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/_paymasters/_approval_paymaster_flow.md @@ -32,9 +32,7 @@ exchange of 1. Run the npm script `compile` to compile the contracts: -```bash [npm] -npm run compile -``` +:display_partial{path="/_partials/commands/_compile"} The script to deploy the `ApprovalFlowPaymaster` contract is located at [`/deploy/4-paymaster/approval/deploy.ts`][deploy-script]. @@ -129,7 +127,7 @@ Contribution successful! 🎉 Great job! You've successfully interacted with the `CrowdfundingCampaign` using a paymaster to cover the transaction fees using the `CROWN` token. -[approval-flow-paymaster-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/4-paymaster/approval/ApprovalFlowPaymaster.sol -[crown-token-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/4-paymaster/approval/CrownToken.sol -[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/4-paymaster/approval/deploy.ts -[interact-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/4-paymaster/approval/interact.ts +[approval-flow-paymaster-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/4-paymaster/approval/ApprovalFlowPaymaster.sol +[crown-token-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/4-paymaster/approval/CrownToken.sol +[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/4-paymaster/approval/deploy.ts +[interact-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/4-paymaster/approval/interact.ts diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_paymasters/_general_paymaster_flow.md b/content/00.zksync-era/10.guides/20.zksync-101/_paymasters/_general_paymaster_flow.md index c73f11e1..d0ee0938 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/_paymasters/_general_paymaster_flow.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/_paymasters/_general_paymaster_flow.md @@ -27,9 +27,7 @@ exclusively callable by the system's bootloader, adding an extra layer of securi Run the npm script `compile` to compile the contracts: -```bash [npm] -npm run compile -``` +:display_partial{path="/_partials/commands/_compile"} The script to deploy the `GaslessPaymaster` is located at [`/deploy/4-paymaster/gasless/deploy.ts][deploy-script]. @@ -96,6 +94,6 @@ Contribution successful! 🎉 Great job! You've successfully interacted with the `CrowdfundingCampaign` using a paymaster to cover the transaction fees. -[gasless-paymaster-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/4-paymaster/gasless/GaslessPaymaster.sol -[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/4-paymaster/gasless/deploy.ts -[interact-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/4-paymaster/gasless/interact.ts +[gasless-paymaster-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/4-paymaster/gasless/GaslessPaymaster.sol +[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/4-paymaster/gasless/deploy.ts +[interact-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/4-paymaster/gasless/interact.ts diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_testing/_era-vm.md b/content/00.zksync-era/10.guides/20.zksync-101/_testing/_era-vm.md new file mode 100644 index 00000000..62ed30c7 --- /dev/null +++ b/content/00.zksync-era/10.guides/20.zksync-101/_testing/_era-vm.md @@ -0,0 +1,43 @@ +--- +title: EraVM - Testing +--- + +:display_partial{path="/_partials/101/testing/_setup"} + +If your local `anvil-zksync` node is running, stop it with the following command: + +```bash +zksync-cli dev stop +``` + +## `hardhat-zksync-node` + +Testing contracts requires a more structured setup. +We'll use `hardhat-zksync-node` which is a part of the `hardhat-zksync` package to run tests against its own implementation +of the in-memory node. + +Within the `hardhat.config.ts`, you'll observe the `zksync` flag set to `true` under the +`hardhat` network, indicating the integration with ZKsync's testing environment. + +```typescript [hardhat.config.ts] +const config: HardhatUserConfig = { + defaultNetwork: "anvilZKsync" + networks: { + ... + hardhat: { + zksync: true, + }, + ... + } + ... +} +``` + +:display_partial{path="/_partials/101/testing/_part2"} + +## Test `CrowdfundingCampaign` + +This section describes testing the `CrowdfundingCampaign.sol` contract. +Let's review the contract at [`test/1-hello-zksync/CrowdfundingCampaign.test.ts`](https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/test/1-hello-zksync/CrowdfundingCampaign.test.ts) + +:display_partial{path="/_partials/101/testing/_run_test"} diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_testing/_evm.md b/content/00.zksync-era/10.guides/20.zksync-101/_testing/_evm.md new file mode 100644 index 00000000..de7c5831 --- /dev/null +++ b/content/00.zksync-era/10.guides/20.zksync-101/_testing/_evm.md @@ -0,0 +1,14 @@ +--- +title: EVM - Testing +--- + +:display_partial{path="/_partials/101/testing/_setup"} + +:display_partial{path="/_partials/101/testing/_part2"} + +## Test `CrowdfundingCampaign` + +This section describes testing the `CrowdfundingCampaign.sol` contract. +Let's review the contract at [`test/1-hello-zksync/CrowdfundingCampaign.test.ts`](https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/evm/test/1-hello-zksync/CrowdfundingCampaign.test.ts) + +:display_partial{path="/_partials/101/testing/_run_test"} diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_beacon_proxy_contract_upgradability.md b/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_beacon_proxy_contract_upgradability.md index 3caedef8..6669ae43 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_beacon_proxy_contract_upgradability.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_beacon_proxy_contract_upgradability.md @@ -54,9 +54,7 @@ the contract so we may upgrade it in later steps. To compile the contracts in the project, run the following command: -```bash [npm] -npm run compile -``` +:display_partial{path="/_partials/commands/_compile"} ## Deploy the beacon and contract @@ -139,9 +137,7 @@ offering adaptability to changing campaign needs. Run the npm script `compile` to compile the contracts: -```bash [npm] -npm run compile -``` +:display_partial{path="/_partials/commands/_compile"} ## Deploy the upgrade to `V2_BeaconCrowdfundingCampaign` @@ -183,7 +179,7 @@ V2_BeaconCrowdfundingCampaign initialized. Transaction Hash: 0x5f3131c77fcac1939 ## Verify upgradeable contracts ::callout{icon="i-heroicons-exclamation-triangle" color="amber"} -Since we are using the in memory anvil-zksync node for our smart contracts, we do not have the feature +Since we are using the in-memory anvil-zksync node for our smart contracts, we do not have the feature available to verify the smart contract. The following explains how you can verify an upgraded smart contract on testnet or mainnet. @@ -212,7 +208,7 @@ Your verification ID is: 10549 Contract successfully verified on ZKsync block explorer! ``` -[beacon-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/3-proxy-contracts/beacon/BeaconCrowdfundingCampaign.sol -[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/3-proxy-contracts/beacon/deploy.ts -[v2-beacon-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/3-proxy-contracts/beacon/V2_BeaconCrowdfundingCampaign.sol -[upgrade-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/3-proxy-contracts/beacon/upgrade.ts +[beacon-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/3-proxy-contracts/beacon/BeaconCrowdfundingCampaign.sol +[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/3-proxy-contracts/beacon/deploy.ts +[v2-beacon-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/3-proxy-contracts/beacon/V2_BeaconCrowdfundingCampaign.sol +[upgrade-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/3-proxy-contracts/beacon/upgrade.ts diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_transparent_proxy_contract_upgradability.md b/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_transparent_proxy_contract_upgradability.md index b6490488..b45394a0 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_transparent_proxy_contract_upgradability.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_transparent_proxy_contract_upgradability.md @@ -56,9 +56,7 @@ the contract so we may upgrade it in later steps. To compile the contracts in the project, run the following command: -```bash [npm] -npm run compile -``` +:display_partial{path="/_partials/commands/_compile"} The deployment script is located at [`/deploy/3-proxy-contracts/transparent/deploy.ts`][deploy-script]. @@ -137,9 +135,7 @@ demonstrates the use of [`modifiers`](https://docs.soliditylang.org/en/latest/co Run the npm script `compile` to compile the contracts: -```bash [npm] -npm run compile -``` +:display_partial{path="/_partials/commands/_compile"} ### Update to `V2_ProxyableCrowdfundingCampaign` @@ -182,7 +178,7 @@ V2CrowdfundingCampaign initialized. Transaction Hash: 0x3a7cbf9d584457bc6b452964 ## Verify upgradable contracts ::callout{icon="i-heroicons-exclamation-triangle" color="amber"} -Since we are using in memory anvil-zksync node for our smart contracts, we do not have the feature +Since we are using in-memory anvil-zksync node for our smart contracts, we do not have the feature available to verify the smart contract. The following explains how you can verify an upgraded smart contract on testnet or mainnet. @@ -214,7 +210,7 @@ Your verification ID is: 10545 Contract successfully verified on ZKsync block explorer! ``` -[proxyable-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/3-proxy-contracts/transparent/ProxyableCrowdfundingCampaign.sol -[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/3-proxy-contracts/transparent/deploy.ts -[v2-proxyable-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/3-proxy-contracts/transparent/V2_ProxyableCrowdfundingCampaign.sol -[upgrade-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/3-proxy-contracts/transparent/upgrade.ts +[proxyable-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/3-proxy-contracts/transparent/ProxyableCrowdfundingCampaign.sol +[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/3-proxy-contracts/transparent/deploy.ts +[v2-proxyable-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/3-proxy-contracts/transparent/V2_ProxyableCrowdfundingCampaign.sol +[upgrade-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/3-proxy-contracts/transparent/upgrade.ts diff --git a/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_uups_contract_upgradability.md b/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_uups_contract_upgradability.md index d446882e..83ace658 100644 --- a/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_uups_contract_upgradability.md +++ b/content/00.zksync-era/10.guides/20.zksync-101/_upgrading/_uups_contract_upgradability.md @@ -58,9 +58,7 @@ the contract so we may upgrade it in later steps. To compile the contracts in the project, run the following command: -```bash [npm] -npm run compile -``` +:display_partial{path="/_partials/commands/_compile"} ## Deploy the updated contract @@ -142,9 +140,7 @@ demonstrates the use of [`modifiers`](https://docs.soliditylang.org/en/latest/co Run the npm script `compile` to compile the contracts: -```bash [npm] -npm run compile -``` +:display_partial{path="/_partials/commands/_compile"} ### Deploy the upgrade to `V2_UUPSCrowdfundingCampaign` @@ -187,7 +183,7 @@ V2_UUPSCrowdfundingCampaign initialized! Transaction Hash: 0xab959f588b64dc6dee1 ## Verify upgradable contracts ::callout{icon="i-heroicons-exclamation-triangle" color="amber"} -Since we are using the in memory anvil-zksync node for our smart contracts, we do not have the feature +Since we are using the in-memory anvil-zksync node for our smart contracts, we do not have the feature available to verify the smart contract. The following explains how you can verify an upgraded smart contract on testnet or mainnet. @@ -211,7 +207,7 @@ Your verification ID is: 10619 Contract successfully verified on ZKsync block explorer! ``` -[uups-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/3-proxy-contracts/uups/UUPSCrowdfundingCampaign.sol -[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/3-proxy-contracts/uups/deploy.ts -[v2-uups-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/contracts/3-proxy-contracts/uups/V2_UUPSCrowdfundingCampaign.sol -[upgrade-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/deploy/3-proxy-contracts/uups/upgrade.ts +[uups-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/3-proxy-contracts/uups/UUPSCrowdfundingCampaign.sol +[deploy-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/3-proxy-contracts/uups/deploy.ts +[v2-uups-crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/3-proxy-contracts/uups/V2_UUPSCrowdfundingCampaign.sol +[upgrade-script]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/deploy/3-proxy-contracts/uups/upgrade.ts diff --git a/content/00.zksync-era/40.tooling/20.hardhat/20.guides/10.getting-started.md b/content/00.zksync-era/40.tooling/20.hardhat/20.guides/10.getting-started.md index a53edc75..c7457360 100644 --- a/content/00.zksync-era/40.tooling/20.hardhat/20.guides/10.getting-started.md +++ b/content/00.zksync-era/40.tooling/20.hardhat/20.guides/10.getting-started.md @@ -107,25 +107,7 @@ Smart contracts belong in the `contracts` folder. Both the Solidity and Vyper te #### 1. To compile the contract, run -::code-group - -```bash [npm] -npm run compile -``` - -```bash [yarn] -yarn compile -``` - -```bash [pnpm] -pnpm compile -``` - -```bash [bun] -bun compile -``` - -:: +:display_partial{path="/_partials/commands/_compile"} You'll see the following output: diff --git a/content/00.zksync-era/60.ecosystem/60.network-faucets.md b/content/00.zksync-era/60.ecosystem/60.network-faucets.md index 6a864191..54e2119e 100644 --- a/content/00.zksync-era/60.ecosystem/60.network-faucets.md +++ b/content/00.zksync-era/60.ecosystem/60.network-faucets.md @@ -10,9 +10,9 @@ To access the testnet funds (Sepolia) you can use one of the following third par | Faucet Provider | Daily Amount of ETH | Requirements | |--------------------------------------------------|---------------------|----------------------------------| | [Chainstack](https://faucet.chainstack.com/zksync-testnet-faucet) | 0.05 ETH | Chainstack API key | -| [thirdweb](https://thirdweb.com/zksync-sepolia-testnet) | 0.1 ETH | Connect your wallet | +| [thirdweb](https://thirdweb.com/zksync-sepolia-testnet) | 0.01 ETH | Connect your wallet | | [LearnWeb3](https://learnweb3.io/faucets/zksync_sepolia/) | 0.01 ETH | GitHub authentication | -| [GetBlock](https://getblock.io/faucet/zksync-sepolia/) | 0.01 ETH | GetBlock account | +| [GetBlock](https://getblock.io/faucet/zksync-sepolia/) | 0.1 ETH | GetBlock account | | [Alchemy](https://www.alchemy.com/faucets/zksync-sepolia) | 0.1 ETH | Alchemy account required | ## Sepolia faucets diff --git a/content/20.zksync-protocol/20.contracts/20.bootloader.md b/content/20.zksync-protocol/20.contracts/20.bootloader.md index 67a554b0..a40e81da 100644 --- a/content/20.zksync-protocol/20.contracts/20.bootloader.md +++ b/content/20.zksync-protocol/20.contracts/20.bootloader.md @@ -220,7 +220,7 @@ Starting from the 487312 word, the actual descriptions of the transactions start The bootloader enforces that: - They are correctly ABI encoded representations of the struct above. -- They are located without any gaps in memory (the first transaction starts at word 653 and each transaction goes right after the next one). +- They are located without any gaps in-memory (the first transaction starts at word 653 and each transaction goes right after the next one). - The contents of the currently processed transaction (and the ones that will be processed later on are untouched). Note, that we do allow overriding data from the already processed transactions as it helps to preserve efficiency by not having to copy the contents of the `Transaction` each time we need to encode a call to the account. diff --git a/content/20.zksync-protocol/40.circuits/20.circuits/80.main-vm.md b/content/20.zksync-protocol/40.circuits/20.circuits/80.main-vm.md index f51fe9cd..cb301e49 100644 --- a/content/20.zksync-protocol/40.circuits/20.circuits/80.main-vm.md +++ b/content/20.zksync-protocol/40.circuits/20.circuits/80.main-vm.md @@ -254,7 +254,7 @@ flag, enforce sponges. There are only 2 outcomes: - we have dst0 write (and may be src0 read), that we taken care above - opcode itself modified memory queue, based on outcome of src0 read in parallel opcodes either - do not use sponges and only rely on src0/dst0 -- can not have src0/dst0 in memory, but use sponges (UMA, near_call, far call, ret) +- can not have src0/dst0 in-memory, but use sponges (UMA, near_call, far call, ret) No longer in the cyclical part `VM` we Setup different queues: diff --git a/content/20.zksync-protocol/70.differences/10.evm-instructions.md b/content/20.zksync-protocol/70.differences/10.evm-instructions.md index e53d3373..4f65ce5a 100644 --- a/content/20.zksync-protocol/70.differences/10.evm-instructions.md +++ b/content/20.zksync-protocol/70.differences/10.evm-instructions.md @@ -105,7 +105,7 @@ few additional checks: a call `returndatacopy(destOffset, offset, size)` will tr Thus, unlike EVM where memory growth occurs before the call itself, on ZKsync Era, the necessary copying of return data happens only after the call has ended, leading to a difference in `msize()` and sometimes ZKsync Era not panicking where -EVM would panic due to the difference in memory growth. +EVM would panic due to the difference in-memory growth. ```solidity success := call(gas(), target, 0, in, insize, out, outsize) // grows to 'min(returndatasize(), out + outsize)' @@ -128,7 +128,7 @@ has quadratic growth for memory payments, on zkEVM the fees are charged linearly The other thing is that our compiler can sometimes optimize unused memory reads/writes. This can lead to different `msize` compared to Ethereum since fewer bytes have been allocated, leading to cases where EVM panics, but zkEVM will not due to -the difference in memory growth. +the difference in-memory growth. ## `CALLDATALOAD`, `CALLDATACOPY` diff --git a/content/_partials/101/factory/_deploy.md b/content/_partials/101/factory/_deploy.md new file mode 100644 index 00000000..3c62f3b4 --- /dev/null +++ b/content/_partials/101/factory/_deploy.md @@ -0,0 +1,33 @@ +--- +title: Deploy the project +--- + +The deploy script: + +- deploys a single `CrowdfundingFactory`. +- saves an instance of the deployed factory to `factoryContract`. + This gives us access to the factory's functionalities. +- The `createCampaign` method is called on this instance to create + and deploy a new crowdfunding campaign contract. + +Run the deployment command. + +::code-group + +```bash [npm] +npm run deploy:crowdfunding-factory +``` + +```bash [yarn] +yarn deploy:crowdfunding-factory +``` + +```bash [pnpm] +pnpm deploy:crowdfunding-factory +``` + +```bash [bun] +bun deploy:crowdfunding-factory +``` + +:: diff --git a/content/_partials/101/factory/_setup.md b/content/_partials/101/factory/_setup.md new file mode 100644 index 00000000..b6bd4166 --- /dev/null +++ b/content/_partials/101/factory/_setup.md @@ -0,0 +1,8 @@ +--- +title: Setup the project +--- + +## Setup the project + +Make sure to go through the setup provided in the previous sections. +You will have downloaded the 101 project through ZKsync CLI `create` and started up a local in-memory node for development. diff --git a/content/_partials/101/factory/_setup2.md b/content/_partials/101/factory/_setup2.md new file mode 100644 index 00000000..5d7ac97f --- /dev/null +++ b/content/_partials/101/factory/_setup2.md @@ -0,0 +1,29 @@ +--- +title: Setup the project - 2 +--- + +The `CrowdfundingFactory.sol`contract will be used to deploy multiple instances of +the `CrowdfundingCampaign.sol` contract from the previous guide. +This contract factory approach streamlines the deployment of crowdfunding campaigns, +making it efficient to launch and manage multiple campaigns. + +The `CrowdfundingFactory` contract automates the creation and oversight of +`CrowdfundingCampaign` contracts, each with their own distinct funding goals. +The factory contract features: + +- **Campaign Creation**: Utilizes the `createCampaign` method to initiate a new +`CrowdfundingCampaign` contract. This function takes a `fundingGoal` as an argument, +deploys a new campaign contract with this goal, and tracks the created campaign in the +`campaigns` array. +- **Campaign Tracking**: The `getCampaigns` method offers a view into all the campaigns +created by the factory, allowing for easy access and management of multiple crowdfunding +initiatives. + +Run the compile script from your project in the terminal: + +:display_partial{path="/_partials/commands/_compile"} + +### Deploy CrowdfundingCampaigns via the CrowdfundingFactory + +This section outlines the steps to deploy the `CrowdfundingCampaign` contract +using our new `CrowdfundingFactory`. diff --git a/content/_partials/101/hello/_campaign.md b/content/_partials/101/hello/_campaign.md new file mode 100644 index 00000000..6c0deefb --- /dev/null +++ b/content/_partials/101/hello/_campaign.md @@ -0,0 +1,20 @@ +--- +title: EraVM - Hello ZKsync +--- + +## Compile the CrowdfundingCampaign.sol contract + +This guide introduces a crowdfunding campaign contract aimed at supporting Zeek's creative ventures. +Let's start by reviewing the starter contract `CrowdfundingCampaign.sol` in the +[`contracts/1-hello-zksync/CrowdfundingCampaign.sol` directory][crowdfunding-campaign-sol]. + +The `CrowdfundingCampaign` contract is designed for a simple crowdfunding campaign. +This contract features: + +- A constructor to initialize the campaign's funding target. +- The `contribute` method to log funds, triggering `ContributionReceived` and `GoalReached` events. +- The `withdrawFunds` method, allowing the owner to collect accumulated funds post-goal achievement. +- The `getTotalFundsRaised` method to return the total amount of funds that's been raised. +- The `getFundingGoal` method to return the goal for the campaign to reach. + +[crowdfunding-campaign-sol]: https://github.com/matter-labs/zksync-contract-templates/blob/main/templates/101/eravm/contracts/1-hello-zksync/CrowdfundingCampaign.sol diff --git a/content/_partials/101/hello/_deploy.md b/content/_partials/101/hello/_deploy.md new file mode 100644 index 00000000..ca7d7c27 --- /dev/null +++ b/content/_partials/101/hello/_deploy.md @@ -0,0 +1,31 @@ +--- +title: Deploy the contract +--- + +**Key Components:** + +- **contractArtifactName:** Identifies the `CrowdfundingCampaign` contract for deployment. +- **constructorArguments:** Sets initialization parameters for the contract. In this case, +the fundraising goal, converted from ether to wei to match Solidity's `uint256` type. + +Execute the deployment command from `package.json`. + +::code-group + +```bash [npm] +npm run deploy:hello-zksync +``` + +```bash [yarn] +yarn deploy:hello-zksync +``` + +```bash [pnpm] +pnpm deploy:hello-zksync +``` + +```bash [bun] +bun deploy:hello-zksync +``` + +:: diff --git a/content/_partials/101/hello/_interact.md b/content/_partials/101/hello/_interact.md new file mode 100644 index 00000000..86dab1e3 --- /dev/null +++ b/content/_partials/101/hello/_interact.md @@ -0,0 +1,8 @@ +--- +title: Interact with the contract +--- + +## Interact with the contract + +Now that our contract is deployed to our local in-memory node, let's interact with it! +We initially set up the crowdfunding campaign with an amount of `.02 ETH` for the goal. diff --git a/content/_partials/101/testing/_part2.md b/content/_partials/101/testing/_part2.md new file mode 100644 index 00000000..62ed968b --- /dev/null +++ b/content/_partials/101/testing/_part2.md @@ -0,0 +1,31 @@ +--- +title: Testing Part 2 +--- + +Your project has npm scripts for testing that set the `--network` to `"hardhat"`. + +Secondly within the `hardhat.config.ts`, you'll observe the importing of +`@nomicfoundation/hardhat-chai-matchers`. This plugin provides Hardhat with an extended +suite of assertion methods tailored for contract testing, significantly improving the testing +toolkit available for your project. + +```typescript +import "@nomicfoundation/hardhat-chai-matchers"; +``` + +--- + +## Compile the `CrowdfundingCampaign` contract + +Now that our setup is complete, it's time to focus on the core of this +guide - testing our `CrowdfundingCampaign.sol` contract. + +Thorough testing involves scrutinizing every function and aspect of our contract, +including potential failure scenarios. In this guide, we'll focus in on the `contribute` +method to ensure it's tested. + +To compile the contracts in your project, run the following command: + +:display_partial{path="/_partials/commands/_compile"} + +--- diff --git a/content/_partials/101/testing/_run_test.md b/content/_partials/101/testing/_run_test.md new file mode 100644 index 00000000..0056fe73 --- /dev/null +++ b/content/_partials/101/testing/_run_test.md @@ -0,0 +1,61 @@ +--- +title: Run the test +--- + +- **Initialization**: Each test case initializes with fresh contract instances in the `beforeEach` + and predefined rich wallet accounts to simulate various contributors and the contract owner. +- **Deployment**: The `CrowdfundingCampaign` contract is deployed using + the `deployContract` utility, setting a specific funding goal for each test scenario. + +**`contribute` Method Tests:** + +- **Zero Contributions**: Verifies that the contract correctly rejects contribution attempts + with zero value, ensuring the integrity of the contribution process. +- **Funds Aggregation**: Tests the contract's ability to accurately aggregate contributions + from multiple addresses and update the `totalFundsRaised` accordingly. +- **Goal Achievement**: Checks for the `GoalReached` event emission upon meeting the funding goal, + confirming the contract's responsiveness to achieving its set target. + +Run the tests with the following command: + +::code-group + +```bash [npm] +npm run test:crowdfunding-campaign +``` + +```bash [yarn] +yarn test:crowdfunding-campaign +``` + +```bash [pnpm] +pnpm test:crowdfunding-campaign +``` + +```bash [bun] +bun test:crowdfunding-campaign +``` + +:: + +Upon completion, the test suite will provide a summary of all executed tests, +indicating their success or failure: + +```bash + CrowdfundingCampaign + contribute + ✔ should reject contributions of 0 + ✔ should aggregate contributions in totalFundsRaised (150ms) + ✔ should emit GoalReached event when funding goal is met (81ms) + withdrawFunds + ✔ should revert if called by a non-owner + ✔ should revert if funding goal hasn't been reached + ✔ should transfer the funds to the owner when funds have been raised (229ms) + getFundingGoal + ✔ should return the correct funding goal + getTotalFundsRaised + ✔ should return 0 when no contributions have been made + + + 8 passing (2s) +``` diff --git a/content/_partials/101/testing/_setup.md b/content/_partials/101/testing/_setup.md new file mode 100644 index 00000000..d84c0245 --- /dev/null +++ b/content/_partials/101/testing/_setup.md @@ -0,0 +1,10 @@ +--- +title: Setup the project +--- + +## Setup the project + +Make sure to go through the setup provided in the initial [Getting started](/zksync-era/guides/zksync-101) section. +You will have downloaded the 101 project through ZKsync CLI `create`. +Since we will use the local `hardhat` network for testing, you do not need to have a +in-memory node running for this section. diff --git a/content/_partials/_compile-solidity-contracts.md b/content/_partials/_compile-solidity-contracts.md index e7b51f54..a66fa199 100644 --- a/content/_partials/_compile-solidity-contracts.md +++ b/content/_partials/_compile-solidity-contracts.md @@ -7,22 +7,4 @@ Smart contracts deployed to ZKsync must be compiled using our custom compiler. To compile the contracts in a project, run the following command: -::code-group - -```bash [npm] -npm run compile -``` - -```bash [yarn] -yarn compile -``` - -```bash [pnpm] -pnpm run compile -``` - -```bash [bun] -bun run compile -``` - -:: +:display_partial{path="/_partials/commands/_compile"} diff --git a/content/_partials/_eravm_vs_evm.md b/content/_partials/_eravm_vs_evm.md new file mode 100644 index 00000000..f0d2c1d9 --- /dev/null +++ b/content/_partials/_eravm_vs_evm.md @@ -0,0 +1,6 @@ +--- +title: EraVm vs. EVM Callout +--- +::callout{icon="i-heroicons-light-bulb"} +Learn more about using [EraVM vs. EVM bytecode](/zksync-protocol/evm-interpreter/overview). +:: diff --git a/content/_partials/commands/_compile.md b/content/_partials/commands/_compile.md new file mode 100644 index 00000000..8a8707ac --- /dev/null +++ b/content/_partials/commands/_compile.md @@ -0,0 +1,23 @@ +--- +title: Compile Command +--- + +::code-group + +```bash [npm] +npm run compile +``` + +```bash [yarn] +yarn compile +``` + +```bash [pnpm] +pnpm compile +``` + +```bash [bun] +bun compile +``` + +:: diff --git a/content/_partials/commands/_hh_compile.md b/content/_partials/commands/_hh_compile.md new file mode 100644 index 00000000..e7c3397c --- /dev/null +++ b/content/_partials/commands/_hh_compile.md @@ -0,0 +1,23 @@ +--- +title: Hardhat Compile Command +--- + +::code-group + +```bash [npm] +npx hardhat compile +``` + +```bash [yarn] +yarn hardhat compile +``` + +```bash [pnpm] +pnpm hardhat compile +``` + +```bash [bun] +bun hardhat compile +``` + +:: diff --git a/content/_partials/remix/deploy/_connect.md b/content/_partials/remix/deploy/_connect.md new file mode 100644 index 00000000..bebf5e19 --- /dev/null +++ b/content/_partials/remix/deploy/_connect.md @@ -0,0 +1,6 @@ +--- +title: Connect +--- + +Make sure your wallet is currently connected to the %%zk_testnet_name%%, as we will use our wallet’s configured +network to deploy our smart contract. diff --git a/content/_partials/_enable-remix-zksync-plugin.md b/content/_partials/remix/deploy/_enable-remix-zksync-plugin.md similarity index 78% rename from content/_partials/_enable-remix-zksync-plugin.md rename to content/_partials/remix/deploy/_enable-remix-zksync-plugin.md index d8e5a12b..1492f85e 100644 --- a/content/_partials/_enable-remix-zksync-plugin.md +++ b/content/_partials/remix/deploy/_enable-remix-zksync-plugin.md @@ -2,7 +2,9 @@ title: Enable ZKsync plugin in Remix --- -To deploy smart contracts to ZKsync via Remix you need to enable the ZKsync plugin. +### Enable the Remix ZKsync plugin + +To deploy EraVM bytecode smart contracts to ZKsync via Remix you need to enable the ZKsync plugin. 1. Visit [the Remix website](https://remix.ethereum.org/) 2. Click on the **“🔌 Plugin Manager”** button in the bottom-left corner diff --git a/content/_partials/remix/deploy/_remix-compile-era.md b/content/_partials/remix/deploy/_remix-compile-era.md new file mode 100644 index 00000000..8bd6dbe7 --- /dev/null +++ b/content/_partials/remix/deploy/_remix-compile-era.md @@ -0,0 +1,9 @@ +--- +title: Remix Compile EraVM +--- + +### Compile the contract + +To compile the contract, open the `ZeeksSecretMessages.sol` file in the editor, go the ZKsync plugin, and click on "Compile ZeeksSecretMessages.sol". +If you get a popup message requesting permissions to +access **`ACCESS TO "WRITEFILE" OF "FILE MANAGER"`,** click on "Accept". diff --git a/content/_partials/remix/deploy/_remix-era-wallet.md b/content/_partials/remix/deploy/_remix-era-wallet.md new file mode 100644 index 00000000..2cae8a14 --- /dev/null +++ b/content/_partials/remix/deploy/_remix-era-wallet.md @@ -0,0 +1,7 @@ +--- +title: Remix Connect Wallet EraVM +--- +In the ZKsync Remix plugin, under the Environment Section, +select “Wallet” and click on “Connect Wallet” as shown below: + +![Connect wallet in Remix](/images/remix-connect-wallet.gif) diff --git a/content/_partials/remix/deploy/_remix-evm-wallet.md b/content/_partials/remix/deploy/_remix-evm-wallet.md new file mode 100644 index 00000000..12b0a95b --- /dev/null +++ b/content/_partials/remix/deploy/_remix-evm-wallet.md @@ -0,0 +1,9 @@ +--- +title: Remix Connect Wallet EraVM +--- + +On the left side menu bar, select the "Deploy & Run Transactions" tab. +Click on the "Environment" dropdown menu, select "Customize this list...". +Then, click the toggle icon to enable an injected wallet provider. + +![Connect wallet in Remix](/images/101-quickstart/remix-connect-evm.gif) diff --git a/content/_partials/remix/deploy/_remix-intro.md b/content/_partials/remix/deploy/_remix-intro.md new file mode 100644 index 00000000..24f049ba --- /dev/null +++ b/content/_partials/remix/deploy/_remix-intro.md @@ -0,0 +1,7 @@ +--- +title: Remix Intro +--- + +The Remix IDE is an open-source web and desktop application that supports Ethereum smart contract development and +deployment, offering tools for writing, testing, debugging, and deploying smart contracts written in Solidity to EVM +compatible protocols. diff --git a/content/_partials/remix/deploy/_remix-template-interact-2.md b/content/_partials/remix/deploy/_remix-template-interact-2.md new file mode 100644 index 00000000..03690231 --- /dev/null +++ b/content/_partials/remix/deploy/_remix-template-interact-2.md @@ -0,0 +1,8 @@ +--- +title: Remix Template Interact 2 +--- + +Write a message in the form, click the “sendMessage” button and confirm the transaction in your wallet. Once processed, +click the `getTotalMessages` and check the response in the terminal, which should be `1`. The `getLastMessage` function +should also return the message you just sent. That means the contract is storing the messages as expected! But how can +we see the replies from Zeek? diff --git a/content/_partials/remix/deploy/_status.md b/content/_partials/remix/deploy/_status.md new file mode 100644 index 00000000..192b2e53 --- /dev/null +++ b/content/_partials/remix/deploy/_status.md @@ -0,0 +1,5 @@ +--- +title: Contract Deploy Status +--- + +The status will be “Processed” on ZKsync Era and “Sending” on Ethereum. [Learn more about the transaction lifecycle on ZKsync](/zksync-protocol/rollup/transaction-lifecycle). diff --git a/content/_partials/remix/deploy/_verification.md b/content/_partials/remix/deploy/_verification.md new file mode 100644 index 00000000..b323b00f --- /dev/null +++ b/content/_partials/remix/deploy/_verification.md @@ -0,0 +1,7 @@ +--- +title: Contract Verification +--- + +When a smart contract is verified in a block explorer, it means that the source code of the contract has been published +and matched to the compiled version on the blockchain enhancing transparency, as users can review the contract’s source +code to understand its functions and intentions. diff --git a/content/_partials/remix/erc20/_deploy_eravm.md b/content/_partials/remix/erc20/_deploy_eravm.md new file mode 100644 index 00000000..698d5906 --- /dev/null +++ b/content/_partials/remix/erc20/_deploy_eravm.md @@ -0,0 +1,35 @@ +--- +title: Deploy ERC20 with Remix EraVM +--- + + +:display-partial{path="/_partials/remix/deploy/_enable-remix-zksync-plugin"} + +:display-partial{path="/_partials/remix/erc20/_template"} + +Once the project is imported, open the `contracts/TestToken.sol` file. + +To compile the contract, click on the ZKsync +plugin on the left menu and then "Compile TestToken.sol". If you get a popup message requesting permissions to access +**`ACCESS TO "WRITEFILE" OF "FILE MANAGER"`,** click on Accept. + +::callout{icon="i-heroicons-light-bulb"} +Behind the scenes, Remix is using the ZKsync Era custom Solidity compiler (named `zksolc` ) to generate ZKEVM compatible +bytecode. +[Learn more about ZKsync custom compilers](/zksync-protocol/compiler/toolchain). +:: + +We will use our wallet’s configured +network to deploy our smart contract. In the ZKsync Remix plugin, under the Environment Section, select “Wallet” and click on +“Connect Wallet” as shown below: + +![Connect wallet in Remix](/images/remix-connect-wallet.gif) + +## Deploy the contract + +To deploy the contract, select the `TestToken.sol` contract on the on the “Deploy” section, check the "Verify contract" checkbox, and +click on “Deploy & Verify”. +Sign the transaction on your wallet and wait a few seconds until the transaction is confirmed. + +Congratulations, your ERC20 token +contract is now deployed on %%zk_testnet_name%%! diff --git a/content/_partials/remix/erc20/_ethers.md b/content/_partials/remix/erc20/_ethers.md new file mode 100644 index 00000000..234999a9 --- /dev/null +++ b/content/_partials/remix/erc20/_ethers.md @@ -0,0 +1,15 @@ +--- +title: Ethers with Remix +--- + +This scripts uses `ethers` to interact with the contract we’ve just deployed. + +::callout{icon="i-heroicons-light-bulb"} +Existing libraries like `ethers` , and `viem` can be used to interact with smart contracts deployed on ZKsync Era. +:: + +Fill the following variables: + +- `TOKEN_CONTRACT_ADDRESS`: the contract address of the ERC20 token we just deployed. +- `RECEIVER_WALLET`: address of a different account that will receive new tokens. +- `TOKEN_AMOUNT`: the amount of tokens we’ll send to the account. diff --git a/content/_partials/remix/erc20/_intro.md b/content/_partials/remix/erc20/_intro.md new file mode 100644 index 00000000..ad4b7d65 --- /dev/null +++ b/content/_partials/remix/erc20/_intro.md @@ -0,0 +1,7 @@ +--- +title: Intro - ERC20 with Remix +--- + +The Remix IDE is an open-source web and desktop application that supports Ethereum smart contract development and +deployment, offering tools for writing, testing, debugging, and deploying smart contracts written in Solidity to EVM +compatible protocols. diff --git a/content/_partials/remix/erc20/_run_script.md b/content/_partials/remix/erc20/_run_script.md new file mode 100644 index 00000000..6f88aac0 --- /dev/null +++ b/content/_partials/remix/erc20/_run_script.md @@ -0,0 +1,9 @@ +--- +title: Run Script - ERC20 with Remix +--- + +To confirm the account has received the tokens, visit the [%%zk_testnet_name%% +explorer](%%zk_testnet_block_explorer_url%%) and search the receiver wallet +address. You’ll see the new token balance in the assets table: + +![ERC20 tokens in account balance](/images/101-erc20/erc20-tokens-minted.png) diff --git a/content/_partials/remix/erc20/_script_code_eravm.md b/content/_partials/remix/erc20/_script_code_eravm.md new file mode 100644 index 00000000..f4fa51e9 --- /dev/null +++ b/content/_partials/remix/erc20/_script_code_eravm.md @@ -0,0 +1,16 @@ +--- +title: Interact EraVM Code - ERC20 with Remix +--- + +```typescript +:code-import{filePath="hardhat-sol/scripts/mint-token.ts:start"} + // Note that the script needs the ABI which is generated from the compilation artifact. + // Make sure contract is compiled for ZKsync and artifacts are generated + const artifactsPath = `browser/artifacts/contracts/TestToken.sol/TestToken.json`; + + const metadata = JSON.parse(await remix.call('fileManager', 'getFile', artifactsPath)); + + const signer = (new ethers.BrowserProvider(web3Provider)).getSigner(0); + +:code-import{filePath="hardhat-sol/scripts/mint-token.ts:end"} +``` diff --git a/content/_partials/remix/erc20/_script_code_evm.md b/content/_partials/remix/erc20/_script_code_evm.md new file mode 100644 index 00000000..e09902ed --- /dev/null +++ b/content/_partials/remix/erc20/_script_code_evm.md @@ -0,0 +1,15 @@ +--- +title: Interact EVM Code - ERC20 with Remix +--- + +```typescript +:code-import{filePath="hardhat-sol/scripts/mint-token.ts:start"} + // Note that the script needs the ABI which is generated from the compilation artifact. + const artifactsPath = `browser/contracts/artifacts/TestToken.json`; + + const metadata = JSON.parse(await remix.call('fileManager', 'getFile', artifactsPath)); + + const signer = (new ethers.BrowserProvider(web3Provider)).getSigner(0); + +:code-import{filePath="hardhat-sol/scripts/mint-token.ts:end"} +``` diff --git a/content/_partials/remix/erc20/_template.md b/content/_partials/remix/erc20/_template.md new file mode 100644 index 00000000..135eea14 --- /dev/null +++ b/content/_partials/remix/erc20/_template.md @@ -0,0 +1,10 @@ +--- +title: Clone Template - Remix +--- + +Clone the template project into Remix by clicking the "Clone" button on the "Home" tab under "Files". +Then enter the repository URL below: + +```bash +https://github.com/zkSync-Community-Hub/zksync-quickstart-remix.git +``` diff --git a/error.vue b/error.vue index 37550b42..72378852 100644 --- a/error.vue +++ b/error.vue @@ -27,8 +27,7 @@ provide('navigation', navigation);