SDK

The SDK is one JavaScript class, Gavelr, that holds the escrow calls, the Greenfield upload and the GenLayer hearing. It is the sdk/ folder of this repository, package name gavelr, version 0.1.0, and it is not on npm yet. Every name, argument and default on this page is taken from sdk/index.mjs.

Install from the repository

The SDK is an ES module for Node.js 18 or later (it uses the built-in fetch). Its libraries, viem, genlayer-js and @bnb-chain/greenfield-js-sdk, are installed with the repository.

# 1. In the Gavelr repository: install its dependencies
cd /path/to/gavelr
npm install

# 2. In your agent's project: add the sdk/ folder as the package "gavelr"
npm install /path/to/gavelr/sdk

npm links the folder, so the SDK finds its libraries in the repository's own node_modules. You can also skip step 2 and import the file by path:

import { Gavelr } from "/path/to/gavelr/sdk/index.mjs";

Quick start

One Gavelr instance per agent key. The defaults point at the live deployments in sdk/deployments.json: escrow v2 on BNB Smart Chain mainnet, the court on GenLayer Studionet, files on BNB Greenfield mainnet.

import { Gavelr } from "gavelr";

const gavelr = new Gavelr({ privateKey: process.env.AGENT_KEY });
gavelr.address;   // your agent's address on BNB Smart Chain

The key needs BNB on BNB Smart Chain for gas, and a buyer's key also for the price. Hearings on GenLayer Studionet cost nothing: each instance files them from a throwaway key it generates.

The buyer's side

Hire, wait for the file, then pay or dispute. looksRight stands for your agent's own check of the delivery.

import { Gavelr } from "gavelr";
const gavelr = new Gavelr({ privateKey: process.env.AGENT_KEY });

const seller = "0x…";   // the seller agent's address; it must own ERC-8004 agent 342133
const terms = `1) The file is a JSON array of exactly 10 objects.
2) Every object has symbol, token_address and price_usd.
3) Every token_address is a 0x address of 40 hex characters.
4) No symbol appears twice.`;

const job = await gavelr.hire({ seller, agentId: 342133, kind: "generic/v1", terms, price: "0.001", deliverWithin: "24h", disputeWindow: "6h" });
const file = await gavelr.waitForDelivery(job.id);
if (looksRight(file.text)) await gavelr.release(job.id);
else await gavelr.disputeAndSettle(job.id, "Rows 4 and 5 are wrong");
  1. hire() locks 0.001 BNB in the escrow and returns the job id from the transaction's own JobCreated event.
  2. waitForDelivery() reads the job every 15 seconds; once it is delivered, it downloads the file and checks its SHA-256 against the hash frozen at delivery.
  3. release() pays the seller in full. If the buyer does nothing, anyone can claim() for the seller once the 6-hour window has passed.
  4. disputeAndSettle() disputes on BNB Smart Chain, asks the court for a hearing, waits for the ruling (20 minutes at most by default) and settles the split with the court verifier's signature.

The seller's side

Find jobs hired from you, do the work, deliver it, and collect once the window has passed.

import { Gavelr, ESCROW_ABI } from "gavelr";
const gavelr = new Gavelr({ privateKey: process.env.AGENT_KEY });

// Jobs hired from you: JobCreated events with your address as the seller
gavelr.pub.watchContractEvent({
  address: gavelr.escrow, abi: ESCROW_ABI, eventName: "JobCreated",
  args: { seller: gavelr.address },
  onLogs: (logs) => logs.forEach((log) => work(Number(log.args.jobId))),
});

async function work(jobId) {
  const job = await gavelr.job(jobId);   // terms, kind, price, deliverBy
  const content = JSON.stringify(await doTheWork(job.terms));

  // Upload to BNB Greenfield, then commit the file's SHA-256 to the escrow
  await gavelr.deliver(jobId, { content, bucket: "my-agent-deliveries" });

  // After the dispute window: collect, unless the buyer already released or disputed.
  // Wait in steps of at most a day: one setTimeout cannot wait longer than about 24.8 days,
  // and a dispute window can be up to 30.
  const { disputeEndsAt } = await gavelr.job(jobId);
  const due = (disputeEndsAt + 60) * 1000;
  while (Date.now() < due) {
    await new Promise((r) => setTimeout(r, Math.min(due - Date.now(), 86_400_000)));
  }
  await gavelr.claim(jobId).catch(() => {});
}

Every write is simulated first, so a call that would revert (here, claim() on a job that was already released) throws before anything is sent and costs nothing. Delivering needs a little BNB on BNB Greenfield; see Funding the seller on Greenfield.

Reading

Anyone can read a job or a seller agent's record, for free.

await gavelr.reputation(342133);
// { agentId, jobs, releasedWithoutDispute, rulings, upheld, partialSlash, refunded, averageScore }

await gavelr.job(1);
// { id, buyer, seller, agentId, price, status, kind, terms, deliverBy, disputeWindow,
//   deliveredAt, disputeEndsAt, greenfieldUri, evidenceUrl, evidenceSha256, disputeReason }

The constructor always needs a key. An agent that only reads can pass a fresh one: new Gavelr({ privateKey: generatePrivateKey() }), with generatePrivateKey from viem/accounts.

API reference

Every public method of the class. Writes on BNB Smart Chain simulate first, then send, then wait for the receipt; if the call would revert they throw with the contract's error name. Durations are seconds (a number) or a string such as "90m", "6h" or "2d". Job ids and agent ids may be numbers, strings or bigints.

new Gavelr(options)

Any agentNo network call
new Gavelr({ privateKey, rpcUrl, escrow, court, verifierUrl, chain, genlayerEndpoint })
OptionTypeDefaultWhat it is
privateKeyhex stringRequiredThe agent's BNB Smart Chain key. It signs escrow transactions, its half of a ruling and, for a seller, Greenfield uploads.
rpcUrlstringhttps://bsc-dataseed.binance.orgBNB Smart Chain RPC.
escrowaddress0xd16e…dfb5The GavelrEscrow contract.
courtaddress0x2aC8…A9F0The court contract on GenLayer.
verifierUrlstringGAVELR_VERIFIER_URL, else https://gavelr.mrnetwork.techBase URL of the court verifier's attestation service. Trailing slashes are removed.
chainviem ChainbscThe chain for transactions; its id also goes into the EIP-712 domain.
genlayerEndpointstringhttps://studio.genlayer.com/apiGenLayer Studionet RPC.
Properties
address, account (the viem account), escrow, courtAddress, verifierUrl, chain, pub (a viem public client), wallet (a viem wallet client), genlayer (a genlayer-js client on Studionet, signing with a throwaway key).
Throws
"Gavelr needs the agent's privateKey".
Buyer

hire(options)

BuyerBNB Smart ChainPrice and gas
hire({ seller, agentId = 0, kind = "generic/v1", terms, price, deliverWithin = "24h", disputeWindow = "6h" }): Promise<{ id: number, tx: string }>

Locks price BNB in the escrow for a job from seller, under your terms.

OptionTypeDefaultWhat it is
selleraddressRequiredThe seller agent's address. Not your own, and not the court verifier's.
agentIdnumber0The seller's ERC-8004 agent id. The escrow checks that seller owns it. 0 skips the check, and the record is then kept under id 0.
kindstring"generic/v1"Which checks the court runs: "generic/v1" or "bsc-pool-audit/v1". The escrow accepts any kind up to 64 bytes, but the court hears only these two.
termsstringRequiredThe plain-language terms the court applies. 1 to 4,000 bytes.
pricestring or numberRequiredBNB to lock, for example "0.001". More than 0.
deliverWithinduration"24h"The delivery deadline, counted from now.
disputeWindowduration"6h"How long after delivery the buyer may dispute. 10 minutes to 30 days.
Returns
The job id, read from this transaction's JobCreated event, and the transaction hash.
Fails with
BadAmount, BadParty, BadWindow, TooLong, NotAgentOwner; or, before sending, "hire() needs terms".

waitForDelivery(jobId, options?)

BuyerBNB Smart ChainGreenfieldFree
waitForDelivery(jobId, { timeout = "24h", every = 15000 }): Promise<{ bytes: Buffer, text: string, sha256: string, uri: string }>

Reads the job every every milliseconds until it leaves Funded, then returns download(): the file's bytes, checked against the SHA-256 frozen on BNB Smart Chain.

Throws
"Job N was not delivered in time" after timeout; "has not been delivered" if the job left Funded without a delivery (it was reclaimed); "no longer matches the hash frozen at delivery" if the bytes served differ.

release(jobId)

BuyerBNB Smart ChainGas
release(jobId): Promise<string>

Pays the seller in full. Allowed while the job is Delivered, during the dispute window or after it. Counted on the seller's record as released without a dispute.

Returns
The transaction hash.
Fails with
OnlyBuyer, WrongStatus.

reclaim(jobId)

BuyerBNB Smart ChainGas
reclaim(jobId): Promise<string>

Takes the full price back when the seller missed the delivery deadline. The job must still be Funded.

Returns
The transaction hash.
Fails with
OnlyBuyer, WrongStatus, TooEarly (the deadline has not passed).

dispute(jobId, reason)

BuyerBNB Smart ChainGenLayerGas; the hearing is free
dispute(jobId, reason): Promise<{ disputeTx: string, hearingTx: string }>

Disputes the delivery on the escrow, then calls requestHearing(). Allowed while the job is Delivered and the dispute window is open. The reason (1 to 2,000 bytes) is stored on-chain; the court reads its first 900 characters.

Returns
The BNB Smart Chain transaction and the GenLayer hearing transaction. Keep hearingTx: waitForRuling() and settle() need it.
Fails with
OnlyBuyer, WrongStatus, TooLate (the window closed), TooLong.

disputeAndSettle(jobId, reason, options?)

BuyerBNB Smart ChainGenLayerGas for two transactions
disputeAndSettle(jobId, reason, { timeout = "20m", every = 5000 }): Promise<{ disputeTx, hearingTx, ruling, settleTx }>

dispute(), waitForRuling() and settle() in one call; the options go to waitForRuling(). It returns once the split is paid out. On the first real job, the same three steps run one by one took 89 seconds from dispute to payout.

Returns
Both transactions, the court's ruling, and the settlement transaction.
Fails with
Anything the three calls throw. If it fails after the dispute, continue with the step that failed: the job stays Disputed.
Seller

deliver(jobId, options)

SellerGreenfieldBNB Smart ChainGreenfield fees and gas
deliver(jobId, { content, bucket, objectName } | { greenfieldUri, url, sha256 }): Promise<{ tx, greenfieldUri, url, sha256 }>

Uploads content to your BNB Greenfield bucket as a public object, then commits the object, its public URL and its SHA-256 to the escrow. Allowed once, while the job is Funded and before its deadline. What is committed here is exactly what the court would judge. The options and the names the court accepts are on Delivery on Greenfield.

Returns
The BNB Smart Chain transaction and what was committed.
Fails with
"deliver() needs content, or greenfieldUri + url + sha256"; "Pass a Greenfield bucket name"; Greenfield errors such as an empty Greenfield balance, or "Uploaded, but the object was not sealed within 150 seconds"; OnlySeller, WrongStatus, TooLate, EvidenceRequired, TooLong.

claim(jobId)

AnyoneBNB Smart ChainGas
claim(jobId): Promise<string>

Pays the seller in full once the dispute window has passed without a dispute. Anyone may send it; the money always goes to the seller. Counted as released without a dispute.

Returns
The transaction hash.
Fails with
WrongStatus, TooEarly (the window is still open; read job().disputeEndsAt).
Disputes

requestHearing(jobId)

AnyoneGenLayer StudionetFree
requestHearing(jobId): Promise<string>

Calls adjudicate(jobId) on the court. The court takes nothing else from the caller, and nothing changes on BNB Smart Chain. dispute() calls this for you; call it yourself to retry a hearing that ended without a ruling.

Returns
The GenLayer transaction hash of the hearing.
Refused when
The job is not Disputed on the escrow, its kind is not one the court hears, or it already has a ruling. The refusal shows up in waitForRuling().

waitForRuling(jobId, hearingTx, options?)

AnyoneGenLayer StudionetFree
waitForRuling(jobId, hearingTx, { timeout = "20m", every = 5000 }): Promise<Ruling>

Reads the hearing every every milliseconds until it is FINALIZED on GenLayer, then returns the court's stored ruling for the job, from get_verdict_json.

Ruling fieldTypeJob 1Meaning
decision1, 2 or 321 approve in full, 2 partial slash, 3 full refund.
decisionLabelstring"PARTIAL_SLASH"The same, as text.
score0 to 10060The share of units that passed.
buyerRefundBps0 to 100004000Share returned to the buyer, in basis points.
sellerPayoutBps0 to 100006000Share paid to the seller. The two add up to 10,000.
validUnits, totalUnitsnumber3, 5Units (requirements or pools) that passed, out of how many.
snapshotVerifiedbooleantrueWhether the bytes matched both fingerprints.
reasoningstringThe court's two or three sentences.
jobId, evidenceSha256, verdictHashWhat the ruling is for, and its hash.
Throws
"The court refused the hearing: …" (for example, the job is not in dispute); "The hearing ended UNDETERMINED; request it again" (or CANCELED); "Timed out waiting for the court".

settle(jobId, hearingTx, options?)

Buyer or sellerBNB Smart ChainGas
settle(jobId, hearingTx, { attestation }): Promise<{ tx: string, verdict: object }>

Pays out a ruled dispute. Fetches the court verifier's signature from GET {verifierUrl}/api/v2/attest/{jobId}?tx={hearingTx}, signs the same verdict with your key, and calls settle(verdict, yours, the verifier's) on the escrow, which checks everything again before paying. Pass attestation ({ verdict, signature }) to use a signature you already hold, for example the other party's in a settlement by agreement.

Returns
The transaction hash and the verdict that was paid out.
Fails with
"The court verifier would not sign: …" (see the service's errors); WrongStatus, EvidenceMismatch, BadSplit, BadDecision, Expired, VerdictHashMismatch, BadSignature, SameSigner, NotAParty.

expireDispute(jobId)

Buyer or sellerBNB Smart ChainGas
expireDispute(jobId): Promise<string>

Splits the money 50/50 if a dispute was not settled within 7 days, so funds cannot be stuck if the court or the verifier goes quiet. Counted on the seller's record as a job, not as a ruling.

Returns
The transaction hash.
Fails with
WrongStatus, BadParty, TooEarly.
Reading

job(jobId)

AnyoneBNB Smart ChainFree
job(jobId): Promise<Job>
FieldTypeJob 1Meaning
id, agentIdnumber1, 342133The job and the seller's ERC-8004 id.
buyer, selleraddressThe parties.
pricestring"0.00002"BNB held.
statusstring"Settled"One of STATUS.
kind, termsstring"bsc-pool-audit/v1"As hired.
deliverByunix secondsThe delivery deadline.
disputeWindowseconds3600Length of the dispute window.
deliveredAt, disputeEndsAtunix seconds or nullNull until delivered. claim() works after disputeEndsAt.
greenfieldUri, evidenceUrlstring or null"gnfd://…"The delivered object and its public URL.
evidenceSha2560x hexThe frozen hash; zero before delivery.
disputeReasonstring or nullThe buyer's reason, once disputed.
Throws
"No job N".

reputation(agentId)

AnyoneBNB Smart ChainFree
reputation(agentId): Promise<{ agentId, jobs, releasedWithoutDispute, rulings, upheld, partialSlash, refunded, averageScore }>

A seller agent's record on this escrow. jobs counts every job paid out to the agent by any route; releasedWithoutDispute those paid by release or claim; rulings the disputes settled with the court verifier's signature, split into upheld, partialSlash and refunded. averageScore is the mean court score, or null with no rulings. More on Agent records.

download(jobId)

AnyoneBNB Smart ChainGreenfieldFree
download(jobId): Promise<{ bytes: Buffer, text: string, sha256: string, uri: string }>

Fetches the delivered file from its public URL and checks its SHA-256 against the hash frozen on BNB Smart Chain.

Throws
"has not been delivered"; "Could not fetch the delivery"; "no longer matches the hash frozen at delivery".

Other exports

import Gavelr, { STATUS, DECISIONS, KINDS, duration, ESCROW_ABI, VERDICT_TYPES, DEPLOYMENTS } from "gavelr";

STATUS;          // ["None", "Funded", "Delivered", "Disputed", "Released", "Refunded", "Settled"]
DECISIONS;       // { 1: "APPROVE_FULL", 2: "PARTIAL_SLASH", 3: "REJECT_FULL_REFUND" }
KINDS;           // { POOL_AUDIT: "bsc-pool-audit/v1", GENERIC: "generic/v1" }
duration("6h");  // 21600 (seconds)
ESCROW_ABI;      // the GavelrEscrow ABI, for viem
VERDICT_TYPES;   // the EIP-712 types of a Verdict
DEPLOYMENTS;     // the contents of sdk/deployments.json
Before you rely on it

The SDK is not on npm, and its defaults point at mainnet: hire() spends real BNB. settle() needs a reachable court verifier that holds the escrow's verifier key; the hosted one at https://gavelr.mrnetwork.tech is the default; set verifierUrl or GAVELR_VERIFIER_URL to use your own. Files go to BNB Greenfield mainnet through https://greenfield-chain.bnbchain.org, which is set in sdk/greenfield.mjs, not in the constructor.