> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sei.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Sei EVM Development with Hardhat

> Learn how to set up Hardhat for Sei EVM development, create and deploy smart contracts, and leverage OpenZeppelin components for secure, standardized implementations.

export const AddSeiButton = ({network = 'mainnet', label = 'Add Sei to MetaMask'}) => {
  const SEI_MAINNET_CHAIN_PARAMS = {
    chainId: '0x531',
    chainName: 'Sei Network',
    rpcUrls: ['https://evm-rpc.sei-apis.com'],
    nativeCurrency: {
      name: 'Sei',
      symbol: 'SEI',
      decimals: 18
    },
    blockExplorerUrls: ['https://seiscan.io']
  };
  const SEI_TESTNET_CHAIN_PARAMS = {
    chainId: '0x530',
    chainName: 'Sei Testnet',
    rpcUrls: ['https://evm-rpc-testnet.sei-apis.com'],
    nativeCurrency: {
      name: 'Sei',
      symbol: 'SEI',
      decimals: 18
    },
    blockExplorerUrls: ['https://testnet.seiscan.io']
  };
  const chainParams = network === 'testnet' ? SEI_TESTNET_CHAIN_PARAMS : SEI_MAINNET_CHAIN_PARAMS;
  const [status, setStatus] = useState(null);
  const [isHovered, setIsHovered] = useState(false);
  const [isBusy, setIsBusy] = useState(false);
  const addOrSwitchSeiNetwork = async params => {
    if (typeof window === 'undefined' || !window.ethereum) {
      throw new Error('MetaMask is not installed');
    }
    const ethereum = window.ethereum;
    try {
      await ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{
          chainId: params.chainId
        }]
      });
    } catch (switchError) {
      if (switchError && switchError.code === 4902) {
        await ethereum.request({
          method: 'wallet_addEthereumChain',
          params: [params]
        });
      } else {
        throw switchError;
      }
    }
  };
  const onClick = async e => {
    e.preventDefault();
    setIsBusy(true);
    setStatus(null);
    try {
      await addOrSwitchSeiNetwork(chainParams);
      setStatus({
        type: 'success',
        message: `${chainParams.chainName} added or switched.`
      });
    } catch (err) {
      const message = err && err.message ? err.message : 'Failed to add or switch network.';
      setStatus({
        type: 'error',
        message
      });
    } finally {
      setIsBusy(false);
    }
  };
  return <span className="inline-flex flex-col items-start gap-1">
      <button type="button" onClick={onClick} disabled={isBusy} onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)} className="inline-flex items-center gap-1 px-3 py-1.5 text-white transition-colors min-w-[160px]" style={{
    backgroundColor: isHovered ? 'var(--sei-maroon-200)' : 'var(--sei-maroon-100)',
    color: '#ffffff',
    fontFamily: 'var(--sei-font-mono)',
    textTransform: 'uppercase',
    letterSpacing: '0.04em',
    fontSize: '10px',
    opacity: isBusy ? 0.7 : 1,
    cursor: isBusy ? 'default' : 'pointer'
  }}>
        {isBusy ? 'Adding…' : label}
      </button>
      {status && <span className={status.type === 'error' ? 'text-red-600 dark:text-red-400' : 'text-green-600 dark:text-green-400'} style={{
    fontSize: '11px'
  }}>
          {status.message}
        </span>}
    </span>;
};

export const SandboxEmbed = props => {
  const {src, kind = 'codesandbox', title, description, height, label} = props || ({});
  const KINDS = {
    codesandbox: {
      name: 'CodeSandbox',
      host: 'codesandbox.io',
      defaultHeight: 500
    },
    remix: {
      name: 'Remix IDE',
      host: 'remix.ethereum.org',
      defaultHeight: 620
    },
    stackblitz: {
      name: 'StackBlitz',
      host: 'stackblitz.com',
      defaultHeight: 500
    }
  };
  const meta = KINDS[kind] || KINDS.codesandbox;
  const parsedHeight = Number(height);
  const frameHeight = Number.isFinite(parsedHeight) && parsedHeight > 0 ? parsedHeight : meta.defaultHeight;
  const allowAttr = 'clipboard-read; clipboard-write';
  const [loaded, setLoaded] = useState(false);
  const [btnHover, setBtnHover] = useState(false);
  const HAIRLINE = 'rgba(128, 128, 128, 0.25)';
  const surfaceStyle = {
    backgroundColor: 'rgba(128, 128, 128, 0.08)'
  };
  const monoStyle = {
    fontFamily: 'var(--sei-font-mono)'
  };
  const cardClass = 'not-prose w-full rounded-lg border overflow-hidden my-4';
  const headerClass = 'flex items-center justify-between gap-3 px-4 py-2.5 border-b';
  const buttonStyle = {
    backgroundColor: btnHover ? 'var(--sei-maroon-200)' : 'var(--sei-maroon-100)',
    color: '#ffffff',
    fontFamily: 'var(--sei-font-mono)',
    textTransform: 'uppercase',
    letterSpacing: '0.04em',
    fontSize: '10px',
    cursor: 'pointer'
  };
  const PlayIcon = () => <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
			<path d="M8 5v14l11-7z" />
		</svg>;
  const ExternalIcon = () => <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
			<path d="M14 5h5v5" />
			<path d="M19 5l-9 9" />
			<path d="M19 14v5a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1h5" />
		</svg>;
  return <div className={cardClass} style={{
    borderColor: HAIRLINE
  }}>
			<div className={headerClass} style={{
    ...surfaceStyle,
    borderBottomColor: HAIRLINE
  }}>
				<div className="flex flex-col min-w-0">
					<span className="text-sm font-medium text-neutral-900 dark:text-white truncate" style={monoStyle}>
						{title || meta.name}
					</span>
					<span className="text-xs text-neutral-500 dark:text-neutral-500">{meta.name}</span>
				</div>
				<div className="flex items-center gap-3 shrink-0">
					{src ? <a href={src} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-xs text-neutral-500 hover:text-neutral-800 dark:text-neutral-400 dark:hover:text-neutral-200 transition-colors">
							Open <ExternalIcon />
						</a> : null}
					{!loaded && src ? <button type="button" onClick={() => setLoaded(true)} onMouseEnter={() => setBtnHover(true)} onMouseLeave={() => setBtnHover(false)} className="inline-flex items-center gap-1.5 px-3 py-1.5 transition-colors" style={buttonStyle}>
							<PlayIcon />
							{label || 'Load editor'}
						</button> : null}
				</div>
			</div>

			{description ? <div className="px-4 pt-3 pb-1 text-sm text-neutral-600 dark:text-neutral-400">{description}</div> : null}

			{!src ? <div className="px-4 py-6 text-sm text-red-600 dark:text-red-400" style={monoStyle}>
					SandboxEmbed: missing required `src`.
				</div> : loaded ? <iframe src={src} title={title || meta.name} className="w-full block border-0" style={{
    height: frameHeight + 'px',
    backgroundColor: 'rgba(128, 128, 128, 0.05)'
  }} allow={allowAttr} loading="lazy" allowFullScreen /> : <button type="button" onClick={() => setLoaded(true)} className="w-full flex flex-col items-center justify-center gap-2 text-neutral-500 dark:text-neutral-400 hover:text-neutral-800 dark:hover:text-neutral-200 transition-colors" style={{
    height: frameHeight + 'px',
    cursor: 'pointer',
    ...surfaceStyle
  }}>
					<PlayIcon />
					<span className="text-sm" style={monoStyle}>Click to load {meta.name}</span>
					<span className="text-xs">Loads {meta.host} in an embedded editor</span>
				</button>}
		</div>;
};

export const RunSnippet = props => {
  const {method = 'eth_blockNumber', params = [], network = 'testnet', endpoint, label, title, description, decode = 'auto'} = props || ({});
  const ENDPOINTS = {
    testnet: 'https://evm-rpc-testnet.sei-apis.com',
    mainnet: 'https://evm-rpc.sei-apis.com'
  };
  const rpcUrl = endpoint || ENDPOINTS[network] || ENDPOINTS.testnet;
  const networkLabel = network === 'mainnet' ? 'pacific-1 · mainnet' : network === 'testnet' ? 'atlantic-2 · testnet' : network;
  const requestBody = {
    jsonrpc: '2.0',
    id: 1,
    method,
    params
  };
  const requestJson = JSON.stringify(requestBody, null, 2);
  const [phase, setPhase] = useState('idle');
  const [result, setResult] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [elapsed, setElapsed] = useState(null);
  const [copied, setCopied] = useState(false);
  const [btnHover, setBtnHover] = useState(false);
  const groupThousands = s => s.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  const hexToDecimal = value => {
    if (typeof value !== 'string' || !(/^0x[0-9a-fA-F]+$/).test(value)) return null;
    if (value.length > 66) return null;
    try {
      return groupThousands(BigInt(value).toString(10));
    } catch (e) {
      return null;
    }
  };
  const run = async () => {
    setPhase('loading');
    setErrorMsg(null);
    setResult(null);
    setElapsed(null);
    const startedAt = typeof performance !== 'undefined' ? performance.now() : null;
    try {
      const response = await fetch(rpcUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      });
      const data = await response.json();
      if (startedAt != null && typeof performance !== 'undefined') {
        setElapsed(Math.round(performance.now() - startedAt));
      }
      if (data && data.error) {
        setErrorMsg(data.error.message || 'RPC returned an error');
        setPhase('error');
        return;
      }
      setResult(data ? data.result : undefined);
      setPhase('success');
    } catch (err) {
      setErrorMsg(err && err.message ? err.message : 'Request failed');
      setPhase('error');
    }
  };
  const resultString = result === undefined ? 'undefined' : JSON.stringify(result, null, 2);
  const decoded = decode !== 'off' && typeof result === 'string' ? hexToDecimal(result) : null;
  const copyResult = () => {
    const flashCopied = () => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    };
    if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(resultString).then(flashCopied, () => {});
      return;
    }
    if (typeof document !== 'undefined') {
      try {
        const ta = document.createElement('textarea');
        ta.value = resultString;
        ta.style.position = 'fixed';
        ta.style.opacity = '0';
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        flashCopied();
      } catch (e) {}
    }
  };
  const HAIRLINE = 'rgba(128, 128, 128, 0.25)';
  const surfaceStyle = {
    backgroundColor: 'rgba(128, 128, 128, 0.08)'
  };
  const monoStyle = {
    fontFamily: 'var(--sei-font-mono)'
  };
  const codeStyle = {
    backgroundColor: 'rgba(128, 128, 128, 0.05)',
    fontFamily: 'var(--sei-font-mono)'
  };
  const cardClass = 'not-prose w-full rounded-lg border overflow-hidden my-4';
  const headerClass = 'flex items-center justify-between gap-3 px-4 py-2.5 border-b';
  const labelClass = 'text-xs uppercase tracking-wide text-neutral-500 dark:text-neutral-500';
  const preClass = 'm-0 px-4 py-3 text-sm overflow-x-auto text-neutral-700 dark:text-neutral-300';
  const buttonStyle = {
    backgroundColor: btnHover ? 'var(--sei-maroon-200)' : 'var(--sei-maroon-100)',
    color: '#ffffff',
    fontFamily: 'var(--sei-font-mono)',
    textTransform: 'uppercase',
    letterSpacing: '0.04em',
    fontSize: '10px',
    opacity: phase === 'loading' ? 0.7 : 1,
    cursor: phase === 'loading' ? 'default' : 'pointer'
  };
  return <div className={cardClass} style={{
    borderColor: HAIRLINE
  }}>
			<div className={headerClass} style={{
    ...surfaceStyle,
    borderBottomColor: HAIRLINE
  }}>
				<div className="flex flex-col min-w-0">
					<span className="text-sm font-medium text-neutral-900 dark:text-white truncate" style={monoStyle}>
						{title || method}
					</span>
					<span className="text-xs text-neutral-500 dark:text-neutral-500">{networkLabel}</span>
				</div>
				<button type="button" onClick={run} disabled={phase === 'loading'} onMouseEnter={() => setBtnHover(true)} onMouseLeave={() => setBtnHover(false)} className="inline-flex items-center gap-1.5 px-3 py-1.5 shrink-0 transition-colors" style={buttonStyle}>
					{phase === 'loading' ? <svg className="animate-spin h-4 w-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
								<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
								<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 0 1 8-8v4a4 4 0 0 0-4 4H4z" />
							</svg> : <svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
								<path d="M8 5v14l11-7z" />
							</svg>}
					{phase === 'loading' ? 'Running…' : label || 'Run'}
				</button>
			</div>

			{description ? <div className="px-4 pt-3 text-sm text-neutral-600 dark:text-neutral-400">{description}</div> : null}

			<div className="px-4 pt-3 pb-1">
				<span className={labelClass}>Request</span>
			</div>
			<pre className={preClass} style={codeStyle}>
				{requestJson}
			</pre>

			{phase === 'success' ? <div className="border-t" style={{
    borderTopColor: HAIRLINE
  }}>
					<div className="flex items-center justify-between px-4 pt-3 pb-1">
						<span className={labelClass}>Response{elapsed != null ? ` · ${elapsed} ms` : ''}</span>
						<button type="button" onClick={copyResult} className="text-xs text-neutral-500 hover:text-neutral-800 dark:text-neutral-400 dark:hover:text-neutral-200 transition-colors">
							{copied ? 'Copied' : 'Copy'}
						</button>
					</div>
					<pre className={preClass} style={codeStyle}>
						{resultString}
					</pre>
					{decoded ? <div className="px-4 pb-3 text-xs text-neutral-500 dark:text-neutral-500" style={monoStyle}>
							= {decoded} (decimal)
						</div> : null}
				</div> : null}

			{phase === 'error' ? <div className="border-t" style={{
    borderTopColor: HAIRLINE
  }}>
					<div className="px-4 pt-3 pb-1">
						<span className={labelClass}>Error</span>
					</div>
					<pre className={`${preClass} text-red-600 dark:text-red-400`} style={codeStyle}>
						{errorMsg}
					</pre>
				</div> : null}
		</div>;
};

This tutorial will guide you through setting up Hardhat for Sei EVM development and using OpenZeppelin contracts to build secure, standardized smart contracts. We'll cover environment setup, contract creation, deployment, and show how to leverage OpenZeppelin's pre-built components.

<Info>Watch the video walkthrough for this topic in the [Video Tutorials](/evm/videos) section.</Info>

<Tip>
  **Deploy to Testnet First**

  It is <strong>highly recommended</strong> that you deploy to <em>testnet (atlantic-2)</em> first and verify everything works as expected before committing to mainnet. Doing so helps you catch bugs early, avoid unnecessary gas costs, and keep your users safe.
</Tip>

## Try it before you install

Setting up the full toolchain takes a few minutes. If you just want to see a contract deploy to Sei, you can do both of these right now in the browser.

First, confirm the RPC endpoints you'll put in `hardhat.config` respond:

<RunSnippet method="eth_chainId" network="testnet" title="eth_chainId · atlantic-2" description="Testnet RPC — decodes to 1328." />

<RunSnippet method="eth_chainId" network="mainnet" title="eth_chainId · pacific-1" description="Mainnet RPC — decodes to 1329." />

Then add Sei testnet to your wallet and deploy a minimal `Counter.sol` from Remix — no Node, no install. In Remix: compile under **Solidity Compiler**, then **Deploy & Run** with **Environment** set to **Injected Provider — MetaMask**.

<AddSeiButton network="testnet" label="Add Sei testnet" />

<SandboxEmbed kind="remix" src="https://remix.ethereum.org/?#activate=solidity,fileManager&code=Ly8gU1BEWC1MaWNlbnNlLUlkZW50aWZpZXI6IE1JVApwcmFnbWEgc29saWRpdHkgXjAuOC4yNDsKCi8vLyBAdGl0bGUgQ291bnRlciDigJQgbWluaW1hbCBjb250cmFjdCB0byBjb21waWxlICYgZGVwbG95IHRvIFNlaSB0ZXN0bmV0Lgpjb250cmFjdCBDb3VudGVyIHsKICAgIHVpbnQyNTYgcHVibGljIGNvdW50OwogICAgZnVuY3Rpb24gaW5jcmVtZW50KCkgZXh0ZXJuYWwgeyBjb3VudCsrOyB9CiAgICBmdW5jdGlvbiBkZWNyZW1lbnQoKSBleHRlcm5hbCB7IGNvdW50LS07IH0KfQ" title="Counter.sol · deploy to Sei testnet" description="Remix IDE with a minimal Counter contract preloaded. Compile in-browser, then deploy to Sei testnet." />

## Table of Contents

* [Try it before you install](#try-it-before-you-install)
* [Prerequisites](#prerequisites)
* [Setting Up Your Development Environment](#setting-up-your-development-environment)
* [Configuring Hardhat for Sei EVM](#configuring-hardhat-for-sei-evm)
* [Using OpenZeppelin Contracts](#using-openzeppelin-contracts)
* [Creating and Deploying an ERC20 Token, ERC721 NFT or an Upgradeable UUPS Token ](#creating-and-deploying-an-erc20-token)
* [Testing Your Smart Contracts](#testing-your-smart-contracts)
* [Deploying to Sei Testnet and Mainnet](#deploying-to-sei-testnet-and-mainnet)

## Prerequisites

Before we begin, ensure you have the following installed:

* [Node.js](https://nodejs.org/) (v18.0.0 or later)
* [npm](https://www.npmjs.com/) (v7.0.0 or later) or [yarn](https://yarnpkg.com/)
* A code editor (VS Code recommended)

## Setting Up Your Development Environment

Let's create a new project and set up Hardhat:

```bash theme={"dark"}
# Create a new directory for your project
mkdir sei-hardhat-project
cd sei-hardhat-project

# Scaffold a Hardhat 3 project (ESM + TypeScript)
npx hardhat --init
```

When prompted, choose **Hardhat 3** and **a TypeScript project using Mocha and Ethers.js**, then follow the prompts. This generates an ESM project (`"type": "module"` in `package.json`) with `@nomicfoundation/hardhat-toolbox-mocha-ethers`, `ethers`, Hardhat Ignition, TypeScript, and a ready-to-use `tsconfig.json`.

Then add the OpenZeppelin contract library:

```bash theme={"dark"}
npm install @openzeppelin/contracts
```

<Tip>
  Prefer a non-interactive setup (CI or scripted environments)? Do the same thing by hand — no prompts:

  ```bash theme={"dark"}
  npm init -y
  npm pkg set type=module
  npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox-mocha-ethers @openzeppelin/contracts typescript @types/node
  ```

  The `@nomicfoundation/hardhat-toolbox-mocha-ethers` bundle pulls in `ethers`, Ignition, Mocha/Chai, and the keystore, network-helpers, verify, and typechain plugins — so this single install covers everything in this guide. If you hit peer-dependency errors, re-run with `--legacy-peer-deps`.
</Tip>

## Configuring Hardhat for Sei EVM

Next, we'll need to configure Hardhat to work with the Sei EVM. Update your `hardhat.config.ts` file:

```typescript title="hardhat.config.ts" theme={"dark"}
import type { HardhatUserConfig } from 'hardhat/config';
import { configVariable } from 'hardhat/config';
import hardhatToolboxMochaEthers from '@nomicfoundation/hardhat-toolbox-mocha-ethers';

const config: HardhatUserConfig = {
  // Hardhat 3 loads plugins from an explicit array — no side-effect `import` statements
  plugins: [hardhatToolboxMochaEthers],
  solidity: {
    version: '0.8.28',
    settings: {
      optimizer: {
        enabled: true,
        runs: 200
      }
    }
  },
  networks: {
    // Sei testnet (atlantic-2)
    seitestnet: {
      type: 'http',
      chainType: 'l1',
      url: 'https://evm-rpc-testnet.sei-apis.com',
      accounts: [configVariable('SEI_PRIVATE_KEY')],
      chainId: 1328
    },
    // Sei mainnet (pacific-1)
    seimainnet: {
      type: 'http',
      chainType: 'l1',
      url: 'https://evm-rpc.sei-apis.com',
      accounts: [configVariable('SEI_PRIVATE_KEY')],
      chainId: 1329
    }
  }
};

export default config;
```

<Note>Hardhat 3 is ESM-first and requires `"type": "module"` in `package.json` (the scaffold sets this for you). Each network needs an explicit `type: 'http'`, and plugins load via the `plugins` array rather than the Hardhat 2 side-effect `import '@nomicfoundation/hardhat-toolbox'`. A local simulated network is provided automatically — no `hardhat`/`localhost` entry required.</Note>

Hardhat 3 reads secrets through `configVariable(...)`, backed by an encrypted keystore — so your key is never stored in a plaintext file. Set it once:

```bash theme={"dark"}
npx hardhat keystore set SEI_PRIVATE_KEY
```

You'll be prompted to paste the private key of the account you deploy from; Hardhat stores it encrypted on your machine. For CI, export a `SEI_PRIVATE_KEY` environment variable instead — `configVariable` falls back to it.

<Warning>Use a dedicated, throwaway deploy key funded with only what you need — never a personal wallet holding real funds.</Warning>

## Using OpenZeppelin Contracts

OpenZeppelin provides a library of secure, tested smart contract components that you can use to build your applications. The `@openzeppelin/contracts` package was already installed during setup, so you're ready to import its contracts directly.

## Creating and Deploying an ERC20 Token, ERC721 NFT or an Upgradeable UUPS Token

<Tabs>
  <Tab title="ERC20">
    Let's create a simple ERC20 token using OpenZeppelin contracts. Create a new file in the `contracts` directory called `SeiToken.sol`:

    ```solidity title="contracts/SeiToken.sol" theme={"dark"}
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.22;

    import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
    import "@openzeppelin/contracts/access/Ownable.sol";

    contract SeiToken is ERC20, Ownable {
        constructor(address initialOwner)
            ERC20("Sei Token", "SEI")
            Ownable(initialOwner)
        {
            // Mint 1 million tokens to the contract deployer (with 18 decimals)
            _mint(msg.sender, 1000000 * 10 ** decimals());
        }

        // Function to mint new tokens (only owner)
        function mint(address to, uint256 amount) public onlyOwner {
            _mint(to, amount);
        }

        // Function to burn tokens
        function burn(uint256 amount) public {
            _burn(msg.sender, amount);
        }
    }
    ```

    Now, create a deployment script in the `ignition/modules` directory called `deploy-sei-token.ts`:

    ```typescript title="ignition/modules/deploy-sei-token.ts" theme={"dark"}
    import { buildModule } from '@nomicfoundation/hardhat-ignition/modules';

    export default buildModule('SeiTokenModule', (m) => {
      const deployer = m.getAccount(0);

      const seiToken = m.contract('SeiToken', [deployer]);

      return { seiToken };
    });
    ```

    To deploy the token to the Sei testnet:

    ```bash theme={"dark"}
    npx hardhat ignition deploy ignition/modules/deploy-sei-token.ts --network seitestnet
    ```
  </Tab>

  <Tab title="ERC721">
    Now, let's create an ERC721 NFT contract. Create a new file `SeiNFT.sol` in the `contracts` directory:

    ```solidity title="contracts/SeiNFT.sol" theme={"dark"}
    // SPDX-License-Identifier: MIT
    // Compatible with OpenZeppelin Contracts ^5.0.0
    pragma solidity ^0.8.22;

    import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
    import {ERC721Burnable} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
    import {ERC721Enumerable} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
    import {ERC721Pausable} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol";
    import {ERC721URIStorage} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
    import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

    contract SeiNFT is ERC721, ERC721Enumerable, ERC721URIStorage, ERC721Pausable, Ownable, ERC721Burnable {
        uint256 private _nextTokenId;

         // Base URI for metadata
        string private _baseTokenURI;

        constructor(address initialOwner, string memory baseTokenURI)
            ERC721("Sei NFT Collection", "SEINFT")
            Ownable(initialOwner)
        {
            _baseTokenURI = baseTokenURI;
        }

        // Function to update the base URI (only owner)
        function setBaseURI(string memory baseTokenURI) public onlyOwner {
            _baseTokenURI = baseTokenURI;
        }

        // Override the baseURI function
        function _baseURI() internal view override returns (string memory) {
            return _baseTokenURI;
        }

        function pause() public onlyOwner {
            _pause();
        }

        function unpause() public onlyOwner {
            _unpause();
        }

        function safeMint(address to, string memory uri)
            public
            onlyOwner
            returns (uint256)
        {
            uint256 tokenId = _nextTokenId++;
            _safeMint(to, tokenId);
            _setTokenURI(tokenId, uri);
            return tokenId;
        }

        // The following functions are overrides required by Solidity.

        function _update(address to, uint256 tokenId, address auth)
            internal
            override(ERC721, ERC721Enumerable, ERC721Pausable)
            returns (address)
        {
            return super._update(to, tokenId, auth);
        }

        function _increaseBalance(address account, uint128 value)
            internal
            override(ERC721, ERC721Enumerable)
        {
            super._increaseBalance(account, value);
        }

        function tokenURI(uint256 tokenId)
            public
            view
            override(ERC721, ERC721URIStorage)
            returns (string memory)
        {
            return super.tokenURI(tokenId);
        }

        function supportsInterface(bytes4 interfaceId)
            public
            view
            override(ERC721, ERC721Enumerable, ERC721URIStorage)
            returns (bool)
        {
            return super.supportsInterface(interfaceId);
        }
    }
    ```

    Create a deployment script `deploy-sei-nft.ts`:

    ```typescript title="scripts/deploy-sei-nft.ts" theme={"dark"}
    import { network } from 'hardhat';

    // Hardhat 3 exposes ethers through a network connection rather than a global import
    const { ethers } = await network.create();

    const [deployer] = await ethers.getSigners();
    console.log('Deploying contracts with the account:', deployer.address);

    // Base URI for your NFT metadata
    const baseURI = 'https://your-metadata-server.com/metadata/';

    const SeiNFT = await ethers.getContractFactory('SeiNFT');
    const seiNFT = await SeiNFT.deploy(deployer.address, baseURI);
    await seiNFT.waitForDeployment();

    console.log('SeiNFT deployed to:', await seiNFT.getAddress());

    // Mint an example NFT
    console.log('Minting an example NFT...');
    const mintTx = await seiNFT.safeMint(deployer.address, '0.json');
    const receipt = await mintTx.wait();
    // _nextTokenId starts at 0, so the first minted token has ID 0.
    // Read the actual ID from the Transfer event:
    const transferEvent = receipt.logs.map((log) => seiNFT.interface.parseLog(log)).find((parsed) => parsed?.name === 'Transfer');
    console.log('NFT minted with ID:', transferEvent?.args.tokenId.toString() ?? 'unknown (no Transfer event in receipt)');
    ```

    Deploy the NFT contract to the Sei testnet:

    ```bash theme={"dark"}
    npx hardhat run scripts/deploy-sei-nft.ts --network seitestnet
    ```
  </Tab>

  <Tab title="Upgradeable UUPS Token">
    Upgradeable contracts allow you to modify the contract's logic after deployment without changing the contract address, which is crucial for fixing bugs or adding new features. The UUPS (Universal Upgradeable Proxy Standard) pattern is a popular way to implement upgradeability.

    For upgradeable contracts, also install the upgradeable variant of the OpenZeppelin library (the `@openzeppelin/contracts` package you installed earlier supplies the ERC1967 proxy):

    ```bash theme={"dark"}
    npm install @openzeppelin/contracts-upgradeable
    ```

    <Note>
      OpenZeppelin's `@openzeppelin/hardhat-upgrades` plugin is built for Hardhat 2 and does not register with Hardhat 3's `plugins` array. So this guide deploys the proxy directly using the ERC1967 standard and upgrades through UUPS `upgradeToAndCall` — no extra plugin, fully Hardhat 3-native. The tradeoff: you don't get the plugin's automatic storage-layout safety checks, so make sure each new version only **appends** state variables. You can validate layouts separately with [`@openzeppelin/upgrades-core`](https://www.npmjs.com/package/@openzeppelin/upgrades-core).
    </Note>

    No `hardhat.config.ts` changes are needed beyond the configuration shown earlier.

    Now, let's create an upgradeable ERC20 token. Create `contracts/UpgradeableSeiToken.sol`:

    ```solidity title="contracts/UpgradeableSeiToken.sol" theme={"dark"}
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.22;

    import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
    import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
    import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
    import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

    contract UpgradeableSeiToken is Initializable, ERC20Upgradeable, OwnableUpgradeable, UUPSUpgradeable {
        /// @custom:oz-upgrades-unsafe-allow constructor
        constructor() {
            _disableInitializers();
        }

        function initialize(address initialOwner) initializer public {
            __ERC20_init("Upgradeable Sei Token", "uSEI");
            __Ownable_init(initialOwner);

            // Mint 1 million tokens to the initializer (deployer)
            _mint(initialOwner, 1000000 * 10 ** decimals());
        }

        // Function to mint new tokens (only owner)
        function mint(address to, uint256 amount) virtual public onlyOwner {
            _mint(to, amount);
        }

        // Required for UUPS upgradeability
        function _authorizeUpgrade(address newImplementation)
            internal
            onlyOwner
            override
        {}

        // OPTIONAL: Add a version identifier (useful for tracking upgrades)
        function version() public virtual pure returns (string memory) {
            return "V1";
        }
    }
    ```

    Note the `Initializable` base, the `initializer` modifier, the `__ERC20_init` / `__Ownable_init` calls, and the `_authorizeUpgrade` override — these are what make the contract safe to run behind a proxy. (OpenZeppelin v5's `UUPSUpgradeable` is stateless, so there is no `__UUPSUpgradeable_init` to call.)

    Add a thin, named ERC1967 proxy so Hardhat emits an artifact you can deploy by name. Create `contracts/SeiTokenProxy.sol`:

    ```solidity title="contracts/SeiTokenProxy.sol" theme={"dark"}
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.22;

    import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";

    contract SeiTokenProxy is ERC1967Proxy {
        constructor(address implementation, bytes memory _data)
            ERC1967Proxy(implementation, _data)
        {}
    }
    ```

    Now create a deployment script `scripts/deploy-upgradeable-token.ts`. It deploys the implementation, then deploys the proxy with the `initialize` call encoded as constructor data so initialization happens atomically:

    ```typescript title="scripts/deploy-upgradeable-token.ts" theme={"dark"}
    import { network } from 'hardhat';

    const { ethers } = await network.create();

    const [deployer] = await ethers.getSigners();
    console.log('Deploying contracts with the account:', deployer.address);

    // 1. Deploy the implementation contract
    const UpgradeableSeiToken = await ethers.getContractFactory('UpgradeableSeiToken');
    const implementation = await UpgradeableSeiToken.deploy();
    await implementation.waitForDeployment();

    // 2. Deploy the ERC1967 proxy, running initialize(deployer) atomically
    const initData = UpgradeableSeiToken.interface.encodeFunctionData('initialize', [deployer.address]);
    const SeiTokenProxy = await ethers.getContractFactory('SeiTokenProxy');
    const proxy = await SeiTokenProxy.deploy(await implementation.getAddress(), initData);
    await proxy.waitForDeployment();

    // 3. Interact with the token through the proxy address from here on
    const token = await ethers.getContractAt('UpgradeableSeiToken', await proxy.getAddress());
    console.log('Proxy deployed to:', await token.getAddress());
    console.log('Implementation:', await implementation.getAddress());
    console.log('Version:', await token.version()); // V1
    ```

    Deploy this to the testnet:

    ```bash theme={"dark"}
    npx hardhat run scripts/deploy-upgradeable-token.ts --network seitestnet
    ```

    **Upgrading the Contract**

    Let's say you want to add a new feature or fix a bug. Create a new version of the contract, `contracts/UpgradeableSeiTokenV2.sol`:

    ```solidity title="contracts/UpgradeableSeiTokenV2.sol" theme={"dark"}
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.22;

    import "./UpgradeableSeiToken.sol"; // Import the V1 contract

    contract UpgradeableSeiTokenV2 is UpgradeableSeiToken {
        // Add a new state variable (ensure it doesn't clash with V1 storage layout)
        uint256 public totalMintedSinceV2;

        // Override the mint function to track new mints
        function mint(address to, uint256 amount) public override onlyOwner {
            super.mint(to, amount);
            totalMintedSinceV2 += amount; // Add V2 logic
        }

        // Override the version function
        function version() public pure override returns (string memory) {
            return "V2";
        }

        // IMPORTANT: V2 does not need its own initializer or constructor for upgrades.
        // The state from V1 is preserved.
    }
    ```

    Now, create an upgrade script `scripts/upgrade-token.ts`. **Replace `PROXY_ADDRESS` with the address printed when you deployed the proxy.**

    ```typescript title="scripts/upgrade-token.ts" theme={"dark"}
    import { network } from 'hardhat';

    const { ethers } = await network.create();

    // !! REPLACE WITH YOUR PROXY ADDRESS from the deploy step !!
    const PROXY_ADDRESS = '0xYOUR_PROXY_CONTRACT_ADDRESS_HERE';

    const [deployer] = await ethers.getSigners();
    console.log('Upgrading contract with the account:', deployer.address);

    // 1. Deploy the new implementation
    const UpgradeableSeiTokenV2 = await ethers.getContractFactory('UpgradeableSeiTokenV2');
    const v2Implementation = await UpgradeableSeiTokenV2.deploy();
    await v2Implementation.waitForDeployment();

    // 2. Point the proxy at the new implementation (UUPS upgrades are owner-gated)
    const token = await ethers.getContractAt('UpgradeableSeiTokenV2', PROXY_ADDRESS);
    await (await token.upgradeToAndCall(await v2Implementation.getAddress(), '0x')).wait();

    console.log('Upgrade complete. Proxy remains at:', PROXY_ADDRESS);
    console.log('New implementation:', await v2Implementation.getAddress());
    console.log('Contract version:', await token.version()); // V2
    ```

    Run the upgrade script:

    ```bash theme={"dark"}
    npx hardhat run scripts/upgrade-token.ts --network seitestnet
    ```

    You have now successfully deployed and upgraded a UUPS contract on the Sei network using Hardhat and OpenZeppelin!
  </Tab>
</Tabs>

## Testing Your Smart Contracts

Hardhat makes it easy to test your contracts before deploying them. Create a test file `test/sei-token-test.ts`:

```typescript title="test/sei-token-test.ts" theme={"dark"}
import { expect } from 'chai';
import { network } from 'hardhat';

describe('SeiToken', function () {
  let ethers;
  let seiToken;
  let owner;
  let addr1;
  let addr2;

  beforeEach(async function () {
    // Hardhat 3 exposes ethers through a network connection
    ({ ethers } = await network.create());

    // Get signers
    [owner, addr1, addr2] = await ethers.getSigners();

    // Deploy the token
    seiToken = await ethers.deployContract('SeiToken', [owner.address]);
  });

  describe('Deployment', function () {
    it('Should set the right owner', async function () {
      expect(await seiToken.owner()).to.equal(owner.address);
    });

    it('Should assign the total supply of tokens to the owner', async function () {
      const ownerBalance = await seiToken.balanceOf(owner.address);
      const totalSupply = await seiToken.totalSupply();
      expect(totalSupply).to.equal(ownerBalance);
    });

    it('Should have correct name and symbol', async function () {
      expect(await seiToken.name()).to.equal('Sei Token');
      expect(await seiToken.symbol()).to.equal('SEI');
    });
  });

  describe('Transactions', function () {
    it('Should transfer tokens between accounts', async function () {
      // Transfer 50 tokens from owner to addr1
      await seiToken.transfer(addr1.address, 50);
      expect(await seiToken.balanceOf(addr1.address)).to.equal(50);

      // Transfer 50 tokens from addr1 to addr2
      await seiToken.connect(addr1).transfer(addr2.address, 50);
      expect(await seiToken.balanceOf(addr2.address)).to.equal(50);
    });

    it("Should fail if sender doesn't have enough tokens", async function () {
      const initialOwnerBalance = await seiToken.balanceOf(owner.address);

      // Try to send 1 token from addr1 (0 tokens) to owner
      await expect(seiToken.connect(addr1).transfer(owner.address, 1)).to.be.reverted;

      // Owner balance shouldn't change
      expect(await seiToken.balanceOf(owner.address)).to.equal(initialOwnerBalance);
    });
  });

  describe('Minting', function () {
    it('Should allow owner to mint new tokens', async function () {
      await seiToken.mint(addr1.address, 1000);
      expect(await seiToken.balanceOf(addr1.address)).to.equal(1000);
    });

    it('Should not allow non-owners to mint', async function () {
      await expect(seiToken.connect(addr1).mint(addr1.address, 1000)).to.be.reverted;
    });
  });
});
```

Run your tests with:

```bash theme={"dark"}
npx hardhat test
```

## Deploying to Sei Testnet and Mainnet

Once you've tested your contracts, you can deploy them to the Sei testnet or mainnet. To deploy, you'll need:

1. SEI tokens in your wallet for gas
2. Your private key stored in the encrypted keystore (`npx hardhat keystore set SEI_PRIVATE_KEY`) — or exported as a `SEI_PRIVATE_KEY` environment variable in CI

Deploy to the testnet:

```bash theme={"dark"}
npx hardhat ignition deploy ignition/modules/deploy-sei-token.ts --network seitestnet
```

Deploy to the mainnet (only when you're ready for production):

```bash theme={"dark"}
npx hardhat ignition deploy ignition/modules/deploy-sei-token.ts --network seimainnet
```
