Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduced A Step-by-Step Guide to Building a Decentralized Escrow System on zkSync Article #24

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions cspell-zksync.txt
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ validiums
validium
Validium
sharded
Sepolia

// Used libraries
numberish
Expand Down Expand Up @@ -92,6 +93,7 @@ porco
rosso
insize
MLOAD
lisense

// ETC
gitter
Expand Down Expand Up @@ -127,6 +129,8 @@ ewasm
Evmla
UUPS
Uups
upscaled
unrequired

// crypto events
Edcon
Expand Down
697 changes: 697 additions & 0 deletions tutorials/escrow-system-on-zkSync/TUTORIAL.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions tutorials/escrow-system-on-zkSync/code/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
WALLET_PRIVATE_KEY=
113 changes: 113 additions & 0 deletions tutorials/escrow-system-on-zkSync/code/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.vscode

# hardhat artifacts
artifacts
cache

# zksync artifacts
artifacts-zk
cache-zk

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port
21 changes: 21 additions & 0 deletions tutorials/escrow-system-on-zkSync/code/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Matter Labs

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
51 changes: 51 additions & 0 deletions tutorials/escrow-system-on-zkSync/code/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# zkSync Hardhat project template

This project was scaffolded with [zksync-cli](https://github.com/matter-labs/zksync-cli).

## Project Layout

- `/contracts`: Contains solidity smart contracts.
- `/deploy`: Scripts for contract deployment and interaction.
- `/test`: Test files.
- `hardhat.config.ts`: Configuration settings.

## How to Use

- `npm run compile`: Compiles contracts.
- `npm run deploy`: Deploys using script `/deploy/deploy.ts`.
- `npm run interact`: Interacts with the deployed contract using `/deploy/interact.ts`.
- `npm run test`: Tests the contracts.

Note: Both `npm run deploy` and `npm run interact` are set in the `package.json`. You can also run your files directly, for example: `npx hardhat deploy-zksync --script deploy.ts`

### Environment Settings

To keep private keys safe, this project pulls in environment variables from `.env` files. Primarily, it fetches the wallet's private key.

Rename `.env.example` to `.env` and fill in your private key:

```
WALLET_PRIVATE_KEY=your_private_key_here...
```

### Network Support

`hardhat.config.ts` comes with a list of networks to deploy and test contracts. Add more by adjusting the `networks` section in the `hardhat.config.ts`. To make a network the default, set the `defaultNetwork` to its name. You can also override the default using the `--network` option, like: `hardhat test --network dockerizedNode`.

### Local Tests

Running `npm run test` by default runs the [zkSync In-memory Node](https://era.zksync.io/docs/tools/testing/era-test-node.html) provided by the [@matterlabs/hardhat-zksync-node](https://era.zksync.io/docs/tools/hardhat/hardhat-zksync-node.html) tool.

Important: zkSync In-memory Node currently supports only the L2 node. If contracts also need L1, use another testing environment like Dockerized Node. Refer to [test documentation](https://era.zksync.io/docs/tools/testing/) for details.

## Useful Links

- [Docs](https://era.zksync.io/docs/dev/)
- [Official Site](https://zksync.io/)
- [GitHub](https://github.com/matter-labs)
- [Twitter](https://twitter.com/zksync)
- [Discord](https://join.zksync.dev/)

## License

This project is under the [MIT](./LICENSE) license.
118 changes: 118 additions & 0 deletions tutorials/escrow-system-on-zkSync/code/contracts/Escrow.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;

contract Escrow {
address public purchaser;
address public vendor;
address public intermediary;
uint256 public totalAmount;
bool public isFunded;
bool public isFinished;
uint8 totalAgreements;

event DepositMade(address indexed depositor, uint256 amount);
event PaymentReleased(address indexed recipient, uint256 amount);
event EscrowClosed();

mapping(uint256 => Agreement) public agreements;

modifier onlyPurchaser() {
require(msg.sender == purchaser, "Only the purchaser can call this function");
_;
}

modifier onlyVendor() {
require(msg.sender == vendor, "Only the vendor can call this function");
_;
}

modifier onlyIntermediary() {
require(msg.sender == intermediary, "Only the intermediary can call this function");
_;
}

modifier onlyPurchaserOrIntermediary() {
require(msg.sender == purchaser || msg.sender == intermediary, "Only the purchaser or intermediary can call this function");
_;
}

modifier onlyNotFinished() {
require(!isFinished, "Escrow has already been completed");
_;
}

struct Agreement{
string title;
string description;
uint256 amount;
address purchaser;
address vendor;
}

constructor() {
intermediary = msg.sender;
}

function createAgreement(string memory _title, string memory _description, uint256 _amount) external onlyVendor{
totalAgreements++;
uint8 agreementId = totalAgreements;
agreements[agreementId] = Agreement(_title,_description,_amount,address(0),msg.sender);

}

function enterAgreement(uint8 _agreementId) external onlyPurchaser{
require(_agreementId <= totalAgreements && _agreementId > 0, "agreement not found");
Agreement storage agreement = agreements[_agreementId];
agreement.purchaser = msg.sender;
}

function registerPurchaser() external onlyNotFinished {
require(purchaser == address(0), "Purchaser already registered");
require(msg.sender != vendor, "Address is already registered as a vendor");
purchaser = msg.sender;
}

function registerVendor() external onlyNotFinished {
require(vendor == address(0), "Vendor already registered");
require(msg.sender != purchaser, "Address is already registered as a purchaser");
vendor = msg.sender;
}

function depositFunds(uint8 _agreementId) external onlyPurchaser payable onlyNotFinished {
require(!isFunded, "Funds have already been deposited");
require(_agreementId <= totalAgreements && _agreementId > 0, "agreement not found");
Agreement storage agreement = agreements[_agreementId];
uint budgetedAmount = agreement.amount;
require(msg.value >= budgetedAmount, "Invalid deposit amount");
totalAmount += msg.value;
isFunded = true;
emit DepositMade(purchaser, totalAmount);
}

function releasePayment(uint8 _agreementId) external onlyIntermediary onlyNotFinished payable {
require(isFunded, "Funds must be deposited before releasing");
require(_agreementId <= totalAgreements && _agreementId > 0, "agreement not found");
Agreement storage agreement = agreements[_agreementId];
uint amount = agreement.amount;
(bool success, ) = vendor.call{value :amount}("");
require(success, "Transfer to vendor failed");
isFunded = false;
isFinished = true;
emit PaymentReleased(vendor, totalAmount);
emit EscrowClosed();
}

function refundPayment(uint8 _agreementId) external onlyPurchaserOrIntermediary onlyNotFinished {
require(isFunded, "Funds must be deposited before refunding");
require(_agreementId <= totalAgreements && _agreementId > 0, "agreement not found");
Agreement storage agreement = agreements[_agreementId];
uint amount = agreement.amount;
(bool success,) = purchaser.call{value : amount}("");
require(success , "Refund failed to purchaser");
isFunded = false;
isFinished = true;
emit PaymentReleased(purchaser, totalAmount);
emit EscrowClosed();
}

}
6 changes: 6 additions & 0 deletions tutorials/escrow-system-on-zkSync/code/deploy/deploy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { deployContract } from "./utils";
export default async function () {
const contractArtifactName = "Escrow";
const constructorArguments = [];
await deployContract(contractArtifactName, constructorArguments);
}
36 changes: 36 additions & 0 deletions tutorials/escrow-system-on-zkSync/code/deploy/interact.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import * as hre from "hardhat";
import { getWallet } from "./utils";
import { ethers } from "ethers";

// Address of the contract to interact with
const CONTRACT_ADDRESS = "";
if (!CONTRACT_ADDRESS) throw "⛔️ Provide address of the contract to interact with!";

// An example of a script to interact with the contract
export default async function () {
console.log(`Running script to interact with contract ${CONTRACT_ADDRESS}`);

// Load compiled contract info
const contractArtifact = await hre.artifacts.readArtifact("Greeter");

// Initialize contract instance for interaction
const contract = new ethers.Contract(
CONTRACT_ADDRESS,
contractArtifact.abi,
getWallet() // Interact with the contract on behalf of this wallet
);

// Run contract read function
const response = await contract.greet();
console.log(`Current message is: ${response}`);

// Run contract write function
const transaction = await contract.setGreeting("Hello people!");
console.log(`Transaction hash of setting new message: ${transaction.hash}`);

// Wait until transaction is processed
await transaction.wait();

// Read message after transaction
console.log(`The message now is: ${await contract.greet()}`);
}
Loading