Git Product home page Git Product logo

tokengate's Introduction

Token Gate

NPM version License Downloads

js module for token gating on ethereum

Usage

Exported methods

// unsecure client-side method to check if an address meets a token threshold.
// example usage: enable/disable a button based on a connected wallet's address.
async unsecureClientSideTokenGate({
  balanceOfThreshold, // {number} balance of tokens that define token gate threshold
  contractAddress, // {string} erc20, erc721, or erc1155 contract address
  signerOrProvider, // {Provider} wallet web3 provider
  userAddress, // {string} user address
});

// sign an arbitrary message with a connected wallet
async clientSideSignMessage({
  messageToSign, // {string} text message to be signed by user's connected wallet
  signer, // {Signer} wallet web3 signer
});

// THIS IS NOT DEFINED YET. IT WILL ERROR IF YOU TRY TO USE IT.
async clientSideSignTypedData({});

// server-side code for a secure client-side/server-side token gate flow.
// takes a message signed by a client, recovers the address, and checks
// if that address meets a token threshold.
async secureServerSideTokenGate({
  address, // {string} address to compare to address recovered from signedMessage
  balanceOfThreshold, // {number} balance of tokens that define token gate threshold
  contractAddress, // {string} erc20, erc721, or erc1155 contract address
  message, // {string} clear text message that was signed by user's wallet
  provider, // {Provider} server-side web3 provider
  signedMessage, // {string} signed message by user's wallet
});

Client-side / Server-side example for erc20/721/777

////////////////////////////////////////////////////////////////////
//////////////////////// client-side react /////////////////////////
////////////////////////////////////////////////////////////////////
import axios from "axios";
import { useEffect, useState } from "react";
import { clientSideSignMessage, unsecureClientSideTokenGate } from "tokengate";

const balanceOfThreshold = 1; /* require 1 blitmap nft */
const contractAddress =
  "0x8d04a8c79ceb0889bdd12acdf3fa9d207ed3ff63"; /* blitmap */

// this must match the message that is signed on the server-side.
// ideally the server-side issues this message as a challange.
const message = "sign this secret message";

function TokenGateButton({ signer }) {
  const [isAllowed, setIsAllowed] = useState<boolean>(false);

  useEffect(() => {
    const asyncEffect = async () => {
      const userAddress = await signer.getAddress();
      const _isAllowed = await unsecureClientSideTokenGate({
        balanceOfThreshold,
        contractAddress,
        signerOrProvider: signer,
        userAddress,
      });

      setIsAllowed(_isAllowed);
    };

    asyncEffect();
  }, [signer]);

  const onClick = async () => {
    const userAddress = await signer.getAddress();
    const signedMessage = await clientSideSignMessage({
      messageToSign: message,
      signer,
    });

    try {
      const resp = await axios.post("/api/token-gate", {
        address: userAddress,
        signedMessage,
      });
      setIsAllowed(resp.data.isAllowed);
    } catch (e) {
      console.error("something went wrong");
      setIsAllowed(false);
    }
  };

  return (
    <button disabled={!isAllowed} onClick={onClick}>
      Access token gated content
    </button>
  );
}

////////////////////////////////////////////////////////////////////
///////////////////////// server-side api //////////////////////////
////////////////////////////////////////////////////////////////////
import { ethers } from "ethers";
import { secureServerSideTokenGate } from "tokengate";

const balanceOfThreshold = 1; /* require 1 blitmap nft */
const contractAddress =
  "0x8d04a8c79ceb0889bdd12acdf3fa9d207ed3ff63"; /* blitmap */

// this must match the message that is signed on the client-side.
// ideally the backend issues this message as a challange including a
// human-readable message, nonce, timestamp, domain and chain information.
const message = "sign this secret message";

app.post("/api/token-gate", (req, res) => {
  // optional `networkId` param so that you can use other networks.
  // defaults to `1` which is mainnet
  const { address, networkId = 1, signedMessage } = req.body;

  // create a web3 provider
  const provider = new ethers.providers.InfuraProvider(networkId);

  const isAllowed = await secureServerSideTokenGate({
    address,
    balanceOfThreshold,
    contractAddress,
    message,
    provider,
    signedMessage,
  });

  // handle the success/failure case however you want

  return res.json({ isAllowed });
});

Client-side / Server-side example for erc1555

// the balanceOf method for erc1155 has a different api than other tokens. it allows you to
// check the balance of a particular user for a particular token id. for tokengate, you must
// provide two new arguments: `tokenId`, and `tokenStandard`.
// `tokenId` will be the number id of the token you are checking the balance of
// `tokenStandard` will be `erc1155`

// client-side
// pass `tokenId` and `tokenStandard` when doing a client-side token gate check
const _isAllowed = await unsecureClientSideTokenGate({
  balanceOfThreshold,
  contractAddress,
  signerOrProvider: signer,
  tokenId: 2,
  tokenStandard: "erc1155",
  userAddress,
});

// server-side
// pass `tokenId` and `tokenStandard` to your api handler
const isAllowed = await secureServerSideTokenGate({
  address,
  balanceOfThreshold,
  contractAddress,
  message,
  provider,
  signedMessage,
  tokenId: 2,
  tokenStandard: "erc1155",
});

tokengate's People

Contributors

marcusmolchany avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

Forkers

dr-data

tokengate's Issues

feedback on v1

looking for feedback on v1. all feedback is appreciated.

if you have specific opinions on the following things let me know:

other things that are on my mind:

  • docs or utilities for a secure challenge flow. challenge message should include: nonce, timestamp, human-readable message, domain and chain information.
  • add /examples dir and replit with working examples
  • better api for erc20/721/777 vs erc1155
  • look into Sign-in with Ethereum and EIP-4361
  • support signTypedData()
  • support batchBalanceOf for erc1155
  • allowing for a web3.js provider to be appropriately wrapped by ethers (https://docs.ethers.io/v5/api/providers/other/#Web3Provider)
  • confirming that wallets other than metamask and wallet connect work appropriately
  • separating the signature verification step, and the token gating steps
  • making the token gating step compose multiple token gates. the default token gate utility would be to check for a .balanceOf() for a giving token address

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.