npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@kay-is/warp-contracts-plugin-zod

v0.1.0

Published

Use Zod validation inside Warp Contracts.

Downloads

16

Readme

SmartWeave Extension for Zod

A Warp plugin that extends the global SmartWeave object with Zod parsers created from custom Zod schemas.

Features

  • Use Zod schemas to validate contract inputs.
  • Infer TypeScript types from your Zod schemas for auto-completion in your contract and frontend code.
  • Parse inputs inside your contract via the global SmartWeave object.
  • Get ContractError if the input is invalid.
  • Save space in your contract code by moving the schema definitions to a separate file and moving Zod to a plugin.

Install

$ npm i @kay-is/warp-contracts-plugin-zod

or

$ yarn add @kay-is/warp-contracts-plugin-zod

Schemas and Types Setup

Define your Zod schemas in a separate file.

// types.ts
import { z } from 'zod';
import { arweaveAddr, arweaveTxId, SmartweaveExtensionZod, ParsedSchemas } from '@kay-is/warp-contracts-plugin-zod';

// Define schemas with Zod
const comment = z.object({
  id: arweaveTxId,
  user: arweaveAddr,
  text: z.string()
});

const addCommentInput = z.object({
  function: z.literal('addComment'),
  user: arweaveAddr,
  text: z.string()
});

// Export the schemas so the extension can inject them into the contract at evaluation time.
export const schemas = {
  comment,
  addCommentInput
};

// Get types of the schemas for the global SmartWeave object
export type Schemas = typeof schemas;
export type SmartWeaveExtensionZodWithSchemas = SmartWeaveExtensionZod<Schemas>;

// Create basic contract types
export type State = {
  comments: Comment[];
};

export type Action = {
  caller: arweaveAddr;
  input: unknown;
};

export type HandlerResult = { state: State } | { result: any };

export type ContractCoreTypes = {
  state: State;
  action: Action;
  handlerResult: HandlerResult;
};

// Merge the schema return types with the contract types
export type ContractTypes = ContractCoreTypes & ParsedSchemas<Schemas>;

Usage Inside a Contract

In the contract file, you can import the SmartWeaveExtensionZod type to get auto-completion for the parser functions.

Note: Import the types.ts file with import type to avoid importing the schema code!

// contract.ts
import type { SmartWeaveGlobal } from 'smartweave/lib/smartweave-global';
import type { ContractTypes, Schemas, SmartWeaveExtensionZodWithSchemas } from './types';

// Merge the standard SmartWeave types with the extenion type that includes the
// schema types for auto-completion.
declare global {
  const SmartWeave: SmartWeaveGlobal & SmartWeaveExtensionZodWithSchemas;
}

export function handle(state: ContractTypes['state'], action: ContractTypes['action']): ContractTypes['handlerResult'] {
  const { parse } = SmartWeave.extension.zod;

  if (input.function === 'addComment') {
    const addCommentInput = parse.addCommentInput(action.input);
    // addCommentInput has type { function: 'addComment', user: string, text: string }
    return addComment(state, addCommentInput, action.caller);
  }

  // ...
}

function addComment(
  state: ContractTypes['state'],
  input: ContractTypes['addCommentInput'],
  caller: string
): ContractTypes['handlerResult'] {
  // ...
}

Usage Inside a Frontend

Import the your types.ts file into your frontend code to get the same types and schemas as in your contract code.

Create the contract with the ZodExtension class to load the schemas into the extension.

Note: Import the types.ts file with import to get the schemas in the frontend!

// frontend.ts
import { WarpFactory } from 'warp-contracts';
import { ZodExtension } from '@kay-is/warp-contracts-plugin-zod';
import { ContractTypes, schemas } from './types';

const warpFactory = WarpFactory.forMainnet().use(new ZodExtension(schemas));
const contract = warpFactory.contract<ContractTypes['state']>('<CONTRACT_ID>');
const result = await contract.readState();

export function App() {
  const [state, setState] = React.useState<ContractTypes['state']>(result.cachedValue.state);

  const addComment = async () => {
    // Throws a Zod validation error if the input is invalid
    // returns the parsed input with the right type if it's valid
    const input = schemas.addUserInput.parse({
      function: 'addComment',
      user: "X".repeat(43),
      text: 'Hello World!'
    });

    await contract.connect(<JWK>).writeInteraction(input);
    const result = await contract.readState();

    setState(result.cachedValue.state);
  }

  return (
    <div>
      <button onClick={addComment} >Create User</button>
      <pre>{JSON.stringify(state, null, 2)}</pre>
    </div>
  );
}