ks · foundry / trade
@kashscript/trade-sdkv1.0.0-alpha.1The Trade.
Deterministic CREATE2 deploys · EIP-712 multi-sig · ERC-4337 gasless
overview
The Trade Suite is the second artifact. It carries on-chain commerce across five sovereign paradigms — a one-time deal-closure, recurring subscriptions, two-party escrow, English auctions, and milestone-based payouts — all sharing a single EIP-1167 minimal-proxy factory and a hardened EIP-712 signal layer.
Funds enter and leave each clone through a Money-Lock invariant proved by Phase-7-A formal verification. No single party — not the factory owner, not the paymaster verifier, not any single validator — can drain a deployed clone. Settlement is gated by M-of-N validator quorums; a Guardian multi-sig backstop covers the catastrophic case where oracles fail outright.
Hydrate a manifest in TypeScript, predict the CREATE2 address before deployment, and the on-chain Vault enforces the rest. The TradeForge factory deploys + initializes each clone atomically — no front-run gap, no upgrade hatch, no admin keys reaching into deployed trades.
capabilities
- Five paradigms — OTDC, Subscription, Escrow, Auction, Milestone — all on one EIP-1167 factory.
- Money-Lock invariant proved — Phase-7-A formal verification with four sovereignty theorems.
- EIP-712 signal verification — nine cryptographic binding axes; no captured signature has cross-context value.
- Two-tier governance — M-of-N validator quorums plus a Guardian multi-sig override path.
- ERC-4337 sponsorship — `TradePaymaster` covers gas with strict per-trade drainage protection.
- Multi-L2 deploy ceremony — idempotent deploys across Base, Arbitrum, Optimism, Polygon, and 5 more chains.
install
Two routes — pick one.
The direct route is the primary path now that the packages are live on npmjs.org. The CLI route is for framework-aware scaffolding — it pulls the same tarballs.
Add the package directly from npm
One line in your project. Works in any framework that resolves npm packages — Next, Vite, Remix, Expo, Astro, SvelteKit, plain Node, Bun, edge runtimes.
trade + lexicons
$ npm install @kashscript/trade @kashscript/lexiconsScaffold with the kash CLI
kash add trade scans your stack, picks the right entry points, wires the SDK in, and writes a backup. Dry-run by default; --apply commits; kash rollback reverses any edit.
kash add trade --apply
$ npx @kashscript/kstack add trade --applyZero install. npx fetches @kashscript/kstack on demand, runs it, and exits.
setup
Wire it into your stack.
What ends up in node_modules, the peer deps you supply, framework-specific wiring, and the support- inbox-grade troubleshooting list.
packages you'll see in `node_modules`
@kashscript/trade-sdkrequiredHydrator, contracts, deploy ceremony, EIP-712 signal layer.
@kashscript/tradeoptionalHigh-level wrappers + Trust-Score logic (opinionated defaults).
@kashscript/identity-coretransitiveSigner interfaces — already pulled in by every Kash package.
@kashscript/lexiconstransitive`kash.trade.*` envelope shapes for off-chain records.
peer dependencies · install in your project
viem@^2.21.0All chain interaction (PublicClient, WalletClient, ABI encoding) is via viem.requiredzod@^3.23.8Manifest hydration validates with strict Zod schemas.required
outside npm · what else you need
Foundry (`forge`)
Only required if you compile contracts yourself OR run `kash trade forge-deploy` to install the suite on a new chain. Pre-built artifacts ship in the npm tarball.
curl -L https://foundry.paradigm.xyz | bash && foundryupAn L2 JSON-RPC endpoint
Read + write paths both need an RPC URL. Public fallbacks ship for Base, Optimism, Arbitrum, Polygon, Ethereum mainnet/sepolia — use Alchemy/Infura/QuickNode for production.
# pick a provider — Alchemy free tier is enough for dev
framework wiring
Next.js Server Actions
Deploy a trade from a Server Action. Keep the wallet client server-side so the private key never reaches the browser; submit the user's EIP-712 signature from the client and ABI-encode it in the action.
// app/actions/deploy-trade.ts
"use server";
import { TradeManager } from "@kashscript/trade-sdk/core";
import { createPublicClient, createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";
export async function deployTrade(manifest, overlay) {
const account = privateKeyToAccount(process.env.DEPLOYER_KEY as `0x${string}`);
const wallet = createWalletClient({ account, chain: base, transport: http(process.env.RPC_URL!) });
const pub = createPublicClient({ chain: base, transport: http(process.env.RPC_URL!) });
const manager = new TradeManager({
publicClient: pub,
walletClient: wallet,
chainId: base.id,
factoryAddress: process.env.TRADE_FACTORY as `0x${string}`,
});
return await manager.deploy({ manifest, overlay });
}Plain Node / Bun script
The CLI is the fastest path for one-off deploys. For programmatic use, import `TradeManager` directly; everything is async + viem-typed.
# CLI route (recommended for ops)
kash trade forge-deploy --chain 8453 --key 0x... # install the suite
kash trade deploy --manifest ./otdc.json --chain 8453 --factory 0x...
# Programmatic route
import { TradeManager } from "@kashscript/trade-sdk/core";
const trade = await manager.deploy({ manifest, overlay });Hardhat / Foundry tests
Use the published ABIs + bytecode directly: import them from `@kashscript/trade-sdk/contracts` and deploy via your existing test harness.
import { TradeForge, OTDCTrade } from "@kashscript/trade-sdk/contracts";
const factory = await viem.deployContract({ abi: TradeForge.abi, bytecode: TradeForge.bytecode, args: [owner] });
await factory.write.setImplementation([0, otdcImpl]);ERC-4337 (Account Abstraction)
`TradePaymaster` sponsors gas for the first 10k ops/month on a paid Plan. Pass the paymaster address to your bundler client and the deploy/settle txs flow through it transparently.
troubleshooting · the support inbox
▸ `ArtifactsNotBuiltError: Trade-SDK contract artifacts not built` at runtime.
You're importing from `@kashscript/trade-sdk/contracts` against a dev tarball that wasn't compiled. Run `bun run forge:build && bun run artifacts:gen` in the trade-sdk package, OR install the official published version which ships with bytecode populated.
▸ `Deployed address X != predicted Y — manifest tampering detected`.
Something between hydration and on-chain submission rewrote the manifest. Most common cause: the `_onchain` overlay addresses don't match the manifest's anchors. Re-derive the overlay from the same source-of-truth as the manifest.
▸ `no RPC URL available for chain X`.
The chain ID isn't in the public-fallback table. Pass `--rpc <url>` or set `KASH_RPC_URL`. For supported public fallbacks, see `packages/trade-sdk/src/cli/util/client.ts`.
▸ EIP-712 signal verification fails on-chain (`InvalidSigner`).
Re-check the domain separator — the chain ID and verifying-contract address are part of the EIP-712 domain. A signature minted against a different clone (or a different chain) will never verify, by design.
▸ Tx reverts with `MoneyLockViolation`.
Your transfer attempted to route more than the locked principal. The Money-Lock invariant (Phase-7-A formal verification) prohibits any path that nets withdrawal > deposit. Check your BPS recipients sum to ≤ 10_000.
▸ `kash trade forge-deploy` fails on Windows.
Foundry's Windows binary is experimental. Use WSL or run the deploy from a Linux CI runner. Native Windows support is on Foundry's roadmap, not ours.
example
First call.
// ts
import { TradeManager } from "@kashscript/trade-sdk/core";
const manager = new TradeManager({
publicClient, walletClient, chainId: 8453, factoryAddress,
});
// hydrate → predict → forge → init, atomically
const trade = await manager.deploy({ manifest, overlay });
await trade.lockFunds({ amount: 10_000_000n }); // 10 USDC
const status = await trade.getStatus(); // { state: "Locked", ... }
const cancel = trade.onStateChange((e) => console.log(e.currentName));principles
How it's built.
Five paradigms, one factory
OTDC, Subscription, Escrow, Auction, Milestone — all EIP-1167 clones of pre-audited implementations. Forty-five thousand gas per deploy; 97-plus percent savings over fresh contracts.
Cryptographic sovereignty
EIP-712 signal binding to chain, clone, trade, intent, deadline, and signer. No captured signature carries across any axis. Phase-4-A hardening proved nine distinct binding properties.
Two-tier governance
Validators are oracles — fast but trust-bounded. Guardians are humans — slow but rarely captured. The first to reach quorum settles; the Guardian override exists for catastrophic recovery.
No stranded funds
Phase-7-A formal verification proves four sovereignty theorems: conservation, terminal closure, non-bypassable transitions, and no zombie states. Audit-passed under hostile-recipient scenarios.
licensing · commercial
Commercial. Paid Plan required for production.
@kashscript/trade-sdk is licensed under SSLA Schedule B. Local development on the `free` tier is unlimited. A `trial` (14 days, free) or `paid` Plan is required the moment a real user touches it.
Included
- All five paradigms (OTDC, Subscription, Escrow, Auction, Milestone) on a single paid seat.
- Deployment ceremony across nine baked-in L2s (Ethereum, Base, Arbitrum, Optimism, Polygon + testnets).
- ERC-4337 `TradePaymaster` sponsorship — first 10,000 sponsored ops per month included.
- TypeScript bridge (TradeManager + TradeInstance) + CLI (`kash trade deploy / status / sign`).
Not included
- Per-environment seats (staging + production) need separate seats on `paid` — collapse the math via `team`.
- Hosted verifier service for the Paymaster — paid hosted-service add-on (or self-host).
- Indexer + on-chain analytics — Phase-8 add-on, currently invite-only.