Chuyển đến nội dung
MZGrid

Trang này chỉ có bằng tiếng Anh. Phiên bản tiếng Anh là bản có giá trị chính thức.

MZGridEscrow

Constants, functions, rules and events of the escrow contract, with a viem example of createJobWithPermit.

MZGridEscrow holds customer deposits and settles jobs. It inherits OpenZeppelin AccessControl and ReentrancyGuard.

Constants

Solidity
uint256 public constant FEE_BPS = 700;          // 7% of the charged amount -> treasury
uint256 public constant LOCK_BPS = 2000;        // 20% of the provider share -> ProviderRegistry
uint256 public constant ACCEPT_WINDOW = 10 minutes;
uint256 public constant TIMEOUT_GRACE = 1 hours;

Types

Solidity
enum JobStatus { None, Funded, Running, Completed, Cancelled, Failed, Reclaimed }

struct Job {
    address client;
    address provider;
    uint128 deposit;
    uint128 pricePerHour;
    uint64  maxDuration;   // seconds
    uint64  fundedAt;
    uint64  startedAt;
    uint64  deadline;
    JobStatus status;
    bytes32 specHash;
}

Functions

createJob

Solidity
function createJob(bytes32 jobId, address provider, uint128 pricePerHour, uint64 maxDuration, bytes32 specHash) external;

Called by the client. Computes deposit = pricePerHour × maxDuration / 3600 and pulls it from the caller with transferFrom (the caller must have approved the escrow for at least deposit). Requires that registry.isActive(provider) and deposit <= registry.jobCap(provider). Stores the job with status Funded and fundedAt = block.timestamp. Emits JobFunded.

createJobWithPermit

Solidity
function createJobWithPermit(
    bytes32 jobId, address provider, uint128 pricePerHour, uint64 maxDuration, bytes32 specHash,
    uint256 permitDeadline, uint8 v, bytes32 r, bytes32 s
) external;

Same as createJob, but first calls permit on MZGToken with the caller's EIP-2612 signature, so no separate approve transaction is needed.

acceptJob

Solidity
function acceptJob(bytes32 jobId) external;

Called by the job's provider while the job is Funded and no later than fundedAt + ACCEPT_WINDOW. Sets status Running, startedAt = now, deadline = now + maxDuration, and calls registry.jobStarted(provider). Emits JobAccepted.

cancelJob

Solidity
function cancelJob(bytes32 jobId) external;

Called by the client while the job is still Funded and block.timestamp > fundedAt + ACCEPT_WINDOW. Refunds the full deposit and sets status Cancelled. Emits JobCancelled.

completeJob

Solidity
function completeJob(bytes32 jobId, uint64 usedSeconds, bytes32 resultHash) external; // ORACLE_ROLE

Called by the coordinator on a Running job. In one transaction:

Văn bản
charged       = min(deposit, pricePerHour × usedSeconds / 3600)
fee           = charged × FEE_BPS / 10000              -> treasury
providerShare = charged − fee
lock          = providerShare × LOCK_BPS / 10000       -> ProviderRegistry.addLock(provider, lock)
liquid        = providerShare − lock                   -> provider
refund        = deposit − charged                      -> client
registry.jobEnded(provider)

Sets status Completed and emits JobCompleted.

failJob

Solidity
function failJob(bytes32 jobId, uint8 reason) external; // ORACLE_ROLE

Called by the coordinator on a Funded or Running job. Refunds the full deposit to the client, calls registry.jobEnded if the job was Running, and sets status Failed. Emits JobFailed. Any slashing is a separate call to ProviderRegistry.slash.

reclaimTimeout

Solidity
function reclaimTimeout(bytes32 jobId) external;

Called by the client on a Running job once block.timestamp > deadline + TIMEOUT_GRACE. Refunds the full deposit and sets status Reclaimed. Emits JobReclaimed. This guarantees customers can always recover funds, even if the coordinator is unavailable.

getJob

Solidity
function getJob(bytes32 jobId) external view returns (Job memory);

Events

Solidity
event JobFunded(bytes32 indexed jobId, address indexed client, address indexed provider, uint256 deposit, uint256 pricePerHour, uint64 maxDuration, bytes32 specHash);
event JobAccepted(bytes32 indexed jobId, uint64 deadline);
event JobCompleted(bytes32 indexed jobId, uint64 usedSeconds, uint256 charged, uint256 fee, uint256 providerLiquid, uint256 providerLocked, uint256 refund, bytes32 resultHash);
event JobCancelled(bytes32 indexed jobId);
event JobFailed(bytes32 indexed jobId, uint8 reason);
event JobReclaimed(bytes32 indexed jobId);

State machine

FromCallWhoConditionTo
NonecreateJob / createJobWithPermitclientprovider active, deposit ≤ job capFunded
FundedacceptJobproviderwithin 10 min of fundingRunning
FundedcancelJobclientmore than 10 min after fundingCancelled
FundedfailJoboracle—Failed
RunningcompleteJoboracle—Completed
RunningfailJoboracle—Failed
RunningreclaimTimeoutclientmore than 1 h after deadlineReclaimed

Example: createJobWithPermit with viem

The values come from the escrow object returned by POST /v1/jobs. The permit domain is the token's EIP-712 domain: name MZGrid, version 1.

TypeScript
import { mzgridEscrowAbi, addresses } from "@mzgrid/sdk";
import { createPublicClient, createWalletClient, http, parseSignature, type Hex } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";

const account = privateKeyToAccount(process.env.WALLET_PRIVATE_KEY as Hex);
const wallet = createWalletClient({ account, chain: base, transport: http() });
const publicClient = createPublicClient({ chain: base, transport: http() });
const { token } = addresses[base.id];

// escrow = (await POST /v1/jobs).escrow
const value = BigInt(escrow.depositWei);
const permitDeadline = BigInt(Math.floor(Date.now() / 1000) + 30 * 60);
const nonce = await publicClient.readContract({
  address: token,
  abi: [{ type: "function", name: "nonces", stateMutability: "view", inputs: [{ name: "owner", type: "address" }], outputs: [{ type: "uint256" }] }],
  functionName: "nonces",
  args: [account.address],
});

const signature = await wallet.signTypedData({
  domain: { name: "MZGrid", version: "1", chainId: base.id, verifyingContract: token },
  types: {
    Permit: [
      { name: "owner", type: "address" },
      { name: "spender", type: "address" },
      { name: "value", type: "uint256" },
      { name: "nonce", type: "uint256" },
      { name: "deadline", type: "uint256" },
    ],
  },
  primaryType: "Permit",
  message: { owner: account.address, spender: escrow.contract, value, nonce, deadline: permitDeadline },
});
const { r, s, v, yParity } = parseSignature(signature);

const hash = await wallet.writeContract({
  address: escrow.contract,
  abi: mzgridEscrowAbi,
  functionName: "createJobWithPermit",
  args: [
    escrow.jobIdBytes32,
    escrow.provider,
    BigInt(escrow.pricePerHourWei),
    BigInt(escrow.maxDurationS),
    escrow.specHash,
    permitDeadline,
    Number(v ?? BigInt(yParity + 27)),
    r,
    s,
  ],
});
await publicClient.waitForTransactionReceipt({ hash });
// then: POST /v1/jobs/:id/funded { txHash: hash }

The equivalent Solidity call from another contract:

Solidity
IMZGridEscrow(escrow).createJobWithPermit(
    jobId, provider, pricePerHour, maxDuration, specHash,
    permitDeadline, v, r, s
);