npm package: @paulstinchcombe/gasless-nft-tx
Description: Complete library for deploying and managing KAMI NFT contracts with truly gasless transactions using EIP-4337 Account Abstraction. Now compatible with OpenZeppelin Contracts v5.
Author: Paul Stinchcombe | KAMI
Latest version: 0.20.17

# KAMI Gasless NFT Platform

A comprehensive TypeScript library for **truly gasless** KAMI NFT operations where users pay **ZERO gas fees** for all transactions.

## Latest updates

### Alchemy Gas Manager + bundler (v0.20+)

✅ **Production UserOp gas** is sponsored via **Alchemy** (`alchemyBundlerRpcUrl`, `alchemy_requestGasAndPaymasterAndData`, `eth_sendUserOperation` on the same RPC) — not local Kami verifying-key signing.  
✅ **`SponsoredPaymasterSponsorConfig`** carries **`alchemyBundlerRpcUrl`**, optional **`alchemyGasPolicyId`**, **`waitForBundlerReceipt`**.  
✅ **Legacy** on-chain `KamiVerifyingPaymaster` remains for manual use (`pnpm run deploy-paymaster` / `fund-paymaster`).  
✅ **Architecture** (layers, execution paths): [docs/PLATFORM_ARCHITECTURE.md](./docs/PLATFORM_ARCHITECTURE.md).

### OpenZeppelin Contracts v5

✅ **Upgraded to OpenZeppelin Contracts v5** — current OZ patterns across KAMI Solidity  
✅ **Gas optimizations** — manual counter and related changes where applicable  
✅ Details: [OPENZEPPELIN_V5_UPGRADE.md](./docs/OPENZEPPELIN_V5_UPGRADE.md)

## 🎯 What This Platform Does

-   ✅ **100% Gasless for Users** - Users never need ETH for any operation
-   ✅ **Complete NFT Management** - Deploy, mint, rent, sell, and manage NFTs
-   ✅ **Three NFT Standards** - Support for KAMI721C (ERC721), KAMI721AC (ERC721A), and KAMI1155C (ERC1155)
-   ✅ **Platform-Sponsored** - Platform pays all gas costs
-   ✅ **Public RPC compatible** - Platform signing is done locally; works with any RPC that supports `eth_sendRawTransaction` (e.g. drpc.org, 1RPC, Ankr)
-   ✅ **Admin Role Management** - Platform controls contract administration
-   ✅ **Token Payment Integration** - Users pay with ERC20 tokens
-   ✅ **Type-Safe** - Full TypeScript support with comprehensive type definitions

## 🏗️ Architecture

```
┌─────────────────┐    Signs Message    ┌──────────────────┐    Pays All Gas    ┌────────────────────┐
│   User's EOA    ├───────────────────>│  Platform        ├───────────────────>│   KAMI Contract    │
│  (NO ETH)       │                    │  SimpleAccount   │                    │   (executes)       │
└─────────────────┘                    └──────────────────┘                    └────────────────────┘
```

### **Who pays execution gas (three paths)**

| Path | Config | What pays **4337 / inner execution gas** | What pays **ERC-20 mint or platform fees** |
| --- | --- | --- | --- |
| **Direct** | `useEntryPointForExecute` not `true` (default) | SimpleAccount’s **native ETH** for the inner calls; Platform Funding EOA pays the **outer transaction** | Still **ERC-20** inside `execute` / `executeBatch` (e.g. `transferFrom` user → SimpleAccount) |
| **EntryPoint, no Alchemy URL** | `useEntryPointForExecute: true`, no `alchemyBundlerRpcUrl` | SimpleAccount’s **EntryPoint deposit** (`addDeposit` on the account) | ERC-20 as above |
| **EntryPoint + Alchemy** | `useEntryPointForExecute: true` **and** **`alchemyBundlerRpcUrl`** | **Alchemy** Gas Manager (`alchemy_requestGasAndPaymasterAndData` + same RPC `eth_sendUserOperation`) | ERC-20 as above |

Rules that matter in production:

- If **`alchemyBundlerRpcUrl`** is set, **`useEntryPointForExecute` must be `true`** (direct EOA → `execute()` cannot use a paymaster).
- Treat **Alchemy / bundler** errors as authoritative; do not assume a silent fallback to `handleOps` fixes a rejected UserOp.
- **Mint flows:** prefer one **`executeBatch`** for `transferFrom` + `approve` + mint so a single UserOp stays atomic (see `mintToken` when the user has approved the SimpleAccount).

Deep dive: [docs/SIMPLE_ACCOUNT_EXECUTE_AND_ENTRYPOINT.md](./docs/SIMPLE_ACCOUNT_EXECUTE_AND_ENTRYPOINT.md), full checklist and diagrams [docs/PAYMASTER_SPONSORED_USEROPS_PLAN.md](./docs/PAYMASTER_SPONSORED_USEROPS_PLAN.md), architecture table [docs/PLATFORM_ARCHITECTURE.md](./docs/PLATFORM_ARCHITECTURE.md).

### **Solidity layout & build (from source)**

All on-chain KAMI Solidity lives under **`src/KAMI Contracts/`**:

| Folder | Contents |
|--------|----------|
| **`NFTs/`** | `KAMI721C`, `KAMI721AC`, `KAMI1155C`, `libraries/`, and Foundry-copied **`artifacts/`** |
| **`Paymaster/`** | `KAMI-Paymaster.sol` (`KamiVerifyingPaymaster`), `KamiPaymaster.ts`, **`artifacts/`** |
| **`SmartContractWallet/`** | `ContractDeployer.sol`, deploy helpers (`Deployer.sol`, `SimpleDeployer.sol`) |

TypeScript for wallets and ABIs remains in **`src/SmartContractWallet/`** (e.g. `SimpleAccount.ts`, `ContractDeployer.ts`, `simpleAccountUserOp.ts`).

**Compile contracts (requires [Foundry](https://book.getfoundry.sh)):**

```bash
pnpm run compile:contracts   # forge build + copy JSON into src/KAMI Contracts/**/artifacts/
```

**Library build** (`pnpm run build`) copies artifacts and `.sol` sources into **`dist/KAMI Contracts/`** for the published package. If you previously read JSON from `dist/KAMI-NFTs/` or `dist/KAMI Paymaster/`, use **`dist/KAMI Contracts/NFTs/`** and **`dist/KAMI Contracts/Paymaster/`** instead.

The package exports **`ENTRY_POINT_V07_ADDRESS`**, **`buildEntryPointV07PaymasterAndData`**, **`SIMPLE_ACCOUNT_OWNER_DUMMY_SIGNATURE`**, **`getKamiVerifyingPaymasterAbi`**, **`getKamiVerifyingPaymasterBytecode`**, legacy **`buildKamiPaymasterAndData`**, **`computeKamiPaymasterSignDigest`**, **`signPaymasterDigest`**, and related types. See [docs/PLATFORM_ARCHITECTURE.md](./docs/PLATFORM_ARCHITECTURE.md) and [docs/KAMI_NFT_CONTRACTS.md](./docs/KAMI_NFT_CONTRACTS.md).

**Alchemy:** Extend `SponsoredOperationsConfig` / `SponsoredDeploymentConfig` with **`SponsoredPaymasterSponsorConfig`**: **`alchemyBundlerRpcUrl`** (full HTTPS RPC URL for Gas Manager + bundler), optional **`alchemyGasPolicyId`**, **`waitForBundlerReceipt`**. When `alchemyBundlerRpcUrl` is set, **`useEntryPointForExecute` defaults to true** (override with `false` only if you intentionally disable UserOps — invalid with sponsorship). Keep the URL **server-side**. Legacy on-chain Kami paymaster: `pnpm run deploy-paymaster` / `pnpm run fund-paymaster`. Operational detail: [docs/SIMPLE_ACCOUNT_EXECUTE_AND_ENTRYPOINT.md](./docs/SIMPLE_ACCOUNT_EXECUTE_AND_ENTRYPOINT.md); checklist: [docs/PAYMASTER_SPONSORED_USEROPS_PLAN.md](./docs/PAYMASTER_SPONSORED_USEROPS_PLAN.md).

### **Account Roles**

1. **Platform Funding EOA**:

    - Holds the main ETH balance (treasury)
    - Sends ETH to SimpleAccount when needed
    - Sends execute calls to SimpleAccount
    - Distinct from **platformAddress**, which receives fees

2. **Platform SimpleAccount**:

    - Receives ETH from Platform Funding EOA when you use **direct** execute or need native balance for non–UserOp paths
    - For **EntryPoint without Alchemy URL**, inner gas is paid from the account’s **EntryPoint deposit**
    - For **EntryPoint + Alchemy**, inner execution gas is sponsored via Alchemy Gas Manager; ERC-20 flows still execute **as this account** (`msg.sender == SimpleAccount`)
    - Executes contract deployments and NFT calls via `execute` / `executeBatch`

3. **User's EOA**:
    - Signs messages only
    - Never needs ETH
    - Owns the deployed contracts

## 💰 Funding Flow & Requirements

### **Funding Architecture**

The Platform Funding EOA serves as the **funding source** for the Platform SimpleAccount:

```
Platform Funding EOA (Treasury) → Platform SimpleAccount (Operations) → User Operations
```

### **Initial Setup Requirements**

1. **Platform Funding EOA**: Needs ~0.1 ETH for initial setup and ongoing funding
2. **Platform SimpleAccount**: Receives ETH from Platform Funding EOA for operations
3. **User's EOA**: Requires NO ETH (that's the whole point!)

### **Funding Methods**

#### **1. Manual Funding**

```typescript
// Fund SimpleAccount with specific amount
const result = await sponsoredDeployment.fundSimpleAccount(parseEther('0.05'));

if (result.success) {
	console.log(`✅ SimpleAccount funded! Transaction: ${result.transactionHash}`);
} else {
	console.error(`❌ Funding failed: ${result.error}`);
}
```

#### **2. Auto-Funding on Deployment**

The system automatically checks and funds the SimpleAccount when needed:

```typescript
// Deploy contract (will auto-fund if SimpleAccount balance is low)
const result = await sponsoredDeployment.deployKAMI721C({
	contractName: 'My NFT Collection',
	contractSymbol: 'MNC',
	baseTokenURI: 'https://api.example.com/metadata/',
	initialMintPrice: parseEther('0.001'),
	platformCommissionPercentage: 250,
	userSignature: userSignatureData,
});

// System will automatically:
// 1. Check SimpleAccount balance
// 2. If low, fund it from Platform Funding EOA
// 3. Proceed with deployment
```

#### **3. Balance Monitoring**

```typescript
// Check SimpleAccount balance
const simpleAccountBalance = await sponsoredDeployment.getPlatformBalance();
console.log(`SimpleAccount balance: ${formatEther(simpleAccountBalance)} ETH`);

// Check Platform Funding EOA balance
const platformBalance = await publicClient.getBalance({
	address: platformAccount.address,
});
console.log(`Platform Funding EOA balance: ${formatEther(platformBalance)} ETH`);

// Ensure SimpleAccount is funded
const isFunded = await sponsoredDeployment.ensureSimpleAccountFunded();
if (!isFunded) {
	console.log('⚠️ SimpleAccount funding failed');
}
```

### **Funding Flow Example**

```typescript
import { KamiSponsoredDeployment, createUserSignatureData } from '@paulstinchcombe/gasless-nft-tx';
import { parseEther, formatEther } from 'viem';

// Platform configuration
const config = {
	rpcUrl: 'https://sepolia.base.org',
	platformPrivateKey: process.env.PLATFORM_PRIVATE_KEY,
	platformSimpleAccountAddress: process.env.PLATFORM_SIMPLE_ACCOUNT_ADDRESS,
	contractDeployerAddress: process.env.CONTRACT_DEPLOYER_ADDRESS,
	platformAddress: process.env.PLATFORM_ADDRESS,
	paymentToken: process.env.PAYMENT_TOKEN,
};

const sponsoredDeployment = new KamiSponsoredDeployment(config);

async function deployWithFunding() {
	// 1. Check balances
	const simpleAccountBalance = await sponsoredDeployment.getPlatformBalance();
	const platformBalance = await publicClient.getBalance({
		address: config.platformPrivateKey ? privateKeyToAccount(config.platformPrivateKey).address : '0x0',
	});

	console.log(`SimpleAccount balance: ${formatEther(simpleAccountBalance)} ETH`);
	console.log(`Platform Funding EOA balance: ${formatEther(platformBalance)} ETH`);

	// 2. Fund SimpleAccount if needed
	if (simpleAccountBalance < parseEther('0.01')) {
		console.log('🔄 Funding SimpleAccount...');
		const fundResult = await sponsoredDeployment.fundSimpleAccount(parseEther('0.05'));

		if (!fundResult.success) {
			throw new Error(`Funding failed: ${fundResult.error}`);
		}

		console.log(`✅ SimpleAccount funded! Transaction: ${fundResult.transactionHash}`);
	}

	// 3. Deploy contract (will auto-fund if needed)
	const userSignatureData = createUserSignatureData(
		userAddress,
		'My NFT Collection',
		'MNC',
		'https://api.example.com/metadata/',
		parseEther('0.001'),
		250,
		userSignature
	);

	const result = await sponsoredDeployment.deployKAMI721C({
		contractName: 'My NFT Collection',
		contractSymbol: 'MNC',
		baseTokenURI: 'https://api.example.com/metadata/',
		initialMintPrice: parseEther('0.001'),
		platformCommissionPercentage: 250,
		userSignature: userSignatureData,
	});

	if (result.success) {
		console.log(`🎉 Contract deployed: ${result.contractAddress}`);
		console.log(`💰 Gas paid by: Platform`);
		console.log(`💸 User paid: ZERO ETH`);
	} else {
		console.error(`❌ Deployment failed: ${result.error}`);
	}
}
```

### **Cost Management**

#### **Platform Costs**

-   **Contract Deployment**: ~0.015 ETH per contract
-   **Token Minting**: ~0.003 ETH per token
-   **Other Operations**: ~0.001-0.002 ETH per operation

#### **Funding Strategy**

```typescript
// Recommended funding amounts
const FUNDING_AMOUNTS = {
	INITIAL_SETUP: parseEther('0.1'), // Initial SimpleAccount funding
	TOP_UP: parseEther('0.05'), // Regular top-up amount
	MINIMUM_BALANCE: parseEther('0.01'), // Minimum balance threshold
	PLATFORM_EOA_MIN: parseEther('0.02'), // Minimum Platform Funding EOA balance
};

// Auto-funding logic
async function manageFunding() {
	const simpleAccountBalance = await sponsoredDeployment.getPlatformBalance();
	const platformBalance = await publicClient.getBalance({
		address: platformAccount.address,
	});

	// Check if SimpleAccount needs funding
	if (simpleAccountBalance < FUNDING_AMOUNTS.MINIMUM_BALANCE) {
		if (platformBalance >= FUNDING_AMOUNTS.TOP_UP) {
			await sponsoredDeployment.fundSimpleAccount(FUNDING_AMOUNTS.TOP_UP);
		} else {
			console.warn('⚠️ Platform Funding EOA balance too low for funding');
		}
	}
}
```

## 📚 Documentation

### Architecture

- **[PLATFORM_ARCHITECTURE.md](./docs/PLATFORM_ARCHITECTURE.md)** — Layers, execution paths, source map, SimpleAccount semantics.

### 🚀 Quick Start

#### [Comprehensive Guide](./docs/COMPREHENSIVE_GUIDE.md) ⭐ **START HERE**

Complete guide covering everything you need to know:

-   Platform architecture and setup
-   Quick start examples
-   Complete API reference
-   Frontend and backend integration
-   Security considerations
-   Advanced configuration
-   Troubleshooting guide

### 📖 Detailed Guides

#### [API Reference](./docs/API_REFERENCE.md)

Complete API documentation:

-   All classes, methods, and interfaces
-   Parameter and return type definitions
-   Error handling and types
-   Advanced usage examples
-   Performance considerations

#### [Deployment Guide](./docs/DEPLOYMENT_GUIDE.md)

Infrastructure setup and deployment:

-   Platform setup and configuration
-   Contract deployment process
-   Admin role management
-   Cost analysis and monitoring

#### [Operations Guide](./docs/OPERATIONS_GUIDE.md)

All NFT operations and management:

-   Minting, renting, selling, and management operations
-   Frontend and backend integration
-   User signature verification
-   Complete operation examples

#### [Security Guide](./docs/SECURITY_GUIDE.md)

Security best practices and implementation:

-   Private key management
-   Signature security
-   Access control
-   Monitoring and alerting
-   Incident response

#### [SimpleAccount, EntryPoint & paymaster](./docs/SIMPLE_ACCOUNT_EXECUTE_AND_ENTRYPOINT.md)

-   Direct vs UserOp path, **paymaster-funded gas**, **Alchemy bundler** submission
-   **`getHash`** vs EntryPoint `userOpHash` for `KamiVerifyingPaymaster`

#### [Paymaster + ERC-20 integration plan](./docs/PAYMASTER_SPONSORED_USEROPS_PLAN.md)

-   Best practices, firm **definition-of-done** checklist, risks

## 🚀 Quick Start

### Prerequisites

This project uses **pnpm** as the package manager. Make sure you have pnpm installed:

```bash
# Install pnpm globally if you haven't already
npm install -g pnpm

# Or using corepack (recommended)
corepack enable
corepack prepare pnpm@latest --activate
```

### 1. Installation

```bash
pnpm install @paulstinchcombe/gasless-nft-tx
```

### 2. Create Platform Funding EOA (Required)

The Platform Funding EOA is your treasury account that funds all operations:

```bash
# Generate a new private key for the platform
node -e "console.log('0x' + require('crypto').randomBytes(32).toString('hex'))"

# Set as environment variable
export PRIVATE_KEY=0x[GENERATED_PRIVATE_KEY]

# Fund this account with ETH (~0.1 ETH recommended)
# Send ETH from your main account to the Platform Funding EOA address
```

### 3. Deploy Infrastructure (One-Time Setup)

```bash
# Deploy all infrastructure needed for sponsored transactions
npx tsx setup-sponsored-infrastructure.ts
```

This will deploy:

-   SimpleAccountFactory
-   Platform SimpleAccount (funded with ETH)
-   ContractDeployer helper
-   KAMI Libraries

### 4. Environment Configuration

Create a `.env` file with the addresses from the setup:

```bash
# Platform Configuration (from setup)
PLATFORM_PRIVATE_KEY="0x..." # Platform Funding EOA's private key (has ETH)
PLATFORM_SIMPLE_ACCOUNT_ADDRESS="0x..." # Platform's SimpleAccount (has ETH)
CONTRACT_DEPLOYER_ADDRESS="0x..." # ContractDeployer address
PLATFORM_ADDRESS="0x..." # Platform address (for receiving ERC20 commissions)
PAYMENT_TOKEN="0x..." # Payment token address (USDC, etc.)

# Network Configuration
RPC_URL="https://sepolia.base.org"

# Optional: ERC-4337 UserOps without Alchemy (SimpleAccount EntryPoint deposit pays gas)
# useEntryPointForExecute: true in app config; omit ALCHEMY_BUNDLER_RPC_URL

# Recommended: Alchemy Gas Manager + bundler (server-side — never expose in NEXT_PUBLIC_* )
# ALCHEMY_BUNDLER_RPC_URL="https://..."     # full chain RPC URL (Gas Manager + bundler enabled)
# ALCHEMY_GAS_POLICY_ID="..."                 # optional Gas Manager policy id
# PAYMASTER_WAIT_FOR_BUNDLER_RECEIPT=true|false

# Legacy on-chain KamiVerifyingPaymaster (manual / archival)
# pnpm run deploy-paymaster / fund-paymaster
```

### 5. Platform Setup

```typescript
import { KamiSponsoredOperations, KamiSponsoredDeployment } from '@paulstinchcombe/gasless-nft-tx';

// Platform configuration
const config = {
	rpcUrl: 'https://sepolia.base.org',
	platformPrivateKey: process.env.PLATFORM_PRIVATE_KEY, // Platform's key (has ETH)
	platformSimpleAccountAddress: process.env.PLATFORM_SIMPLE_ACCOUNT_ADDRESS, // Platform's SA (has ETH)
	contractDeployerAddress: process.env.CONTRACT_DEPLOYER_ADDRESS,
	platformAddress: process.env.PLATFORM_ADDRESS,
	paymentToken: process.env.PAYMENT_TOKEN,
};

// Create handlers
const sponsoredDeployment = new KamiSponsoredDeployment(config);
const sponsoredOps = new KamiSponsoredOperations(config);
```

### 6. Deploy Contract (Sponsored)

```typescript
// User signs message for deployment (no ETH needed)
const userSignature = createUserSignatureData(
	userAddress,
	"Paul's NFT Collection",
	'PNC',
	'https://api.example.com/metadata/',
	parseEther('0.001'),
	250, // 2.5% platform commission
	userSignature
);

// Platform deploys contract with sponsored gas
const result = await sponsoredDeployment.deployKAMI721C({
	contractName: "Paul's NFT Collection",
	contractSymbol: 'PNC',
	baseTokenURI: 'https://api.example.com/metadata/',
	initialMintPrice: parseEther('0.001'),
	platformCommissionPercentage: 250,
	userSignature,
});

console.log('Contract deployed:', result.contractAddress);
console.log('Gas paid by: Platform');
console.log('User paid: ZERO ETH');
```

### 7. Mint Token (Sponsored)

```typescript
// User signs message for minting (no ETH needed)
const mintSignature = createSponsoredOperationSignature(
	userAddress,
	'mint',
	contractAddress,
	{
		recipient: userAddress,
		tokenPrice: parseEther('0.001'),
		uri: 'https://api.example.com/metadata/1',
		mintRoyalties: [
			{ receiver: userAddress, percentage: 500 },
			{ receiver: platformAddress, percentage: 250 },
		],
	},
	userSignature
);

// Platform mints token with sponsored gas
const result = await sponsoredOps.mintToken(
	contractAddress,
	'KAMI721C',
	{
		recipient: userAddress,
		tokenPrice: parseEther('0.001'),
		uri: 'https://api.example.com/metadata/1',
		mintRoyalties: [
			{ receiver: userAddress, percentage: 500 },
			{ receiver: platformAddress, percentage: 250 },
		],
	},
	mintSignature
);

console.log('Token minted:', result.data?.tokenId);
console.log('Gas paid by: Platform');
console.log('User paid: ZERO ETH');
```

## 📋 Supported Operations

### **Deployment Operations**

-   ✅ **Deploy KAMI721C** - ERC721 with Creator features
-   ✅ **Deploy KAMI721AC** - ERC721A with batch minting
-   ✅ **Deploy KAMI1155C** - ERC1155 multi-token

### **Minting Operations**

-   ✅ **Mint tokens** with custom prices and royalties
-   ✅ **Batch minting** for KAMI721AC
-   ✅ **Multi-token minting** for KAMI1155C

### **Rental Operations**

-   ✅ **Rent tokens** for specific durations
-   ✅ **Extend rentals** with additional payment
-   ✅ **End rentals** when duration expires

### **Sales Operations**

-   ✅ **Sell tokens** to other users
-   ✅ **Transfer ownership** with payment

### **Management Operations**

-   ✅ **Set token prices** individually
-   ✅ **Set token URIs** for metadata
-   ✅ **Set token royalties** and recipients
-   ✅ **Contract administration** (pause/unpause)

## 💰 Cost Analysis

### **User Costs**

-   **Gas Fees**: **ZERO ETH** ✅
-   **Transaction Fees**: **ZERO ETH** ✅
-   **All Operations**: **ZERO ETH** ✅

### **Platform Costs**

-   **Contract Deployment**: ~0.015 ETH per contract
-   **Token Minting**: ~0.003 ETH per token
-   **Other Operations**: ~0.001-0.002 ETH per operation

## 🔧 Environment Setup

### **Required Environment Variables**

Create a `.env` file with the following variables:

```bash
# Platform Configuration (Required)
PLATFORM_PRIVATE_KEY="0x..." # Platform Funding EOA's private key (has ETH for funding)
PLATFORM_SIMPLE_ACCOUNT_ADDRESS="0x..." # Platform's SimpleAccount (receives ETH)
CONTRACT_DEPLOYER_ADDRESS="0x..." # ContractDeployer helper address
PLATFORM_ADDRESS="0x..." # Platform address (for receiving ERC20 commissions)
PAYMENT_TOKEN="0x..." # Payment token address (USDC, etc.)

# Network Configuration
RPC_URL="https://sepolia.base.org" # RPC endpoint
```

### **Account Setup Process**

1. **Generate Platform Funding EOA**:

    ```bash
    # Generate private key
    node -e "console.log('0x' + require('crypto').randomBytes(32).toString('hex'))"

    # Set environment variable
    export PRIVATE_KEY=0x[GENERATED_PRIVATE_KEY]
    ```

2. **Fund Platform Funding EOA**:

    - Send ~0.1 ETH to the Platform Funding EOA address
    - This account will fund the SimpleAccount for operations

3. **Deploy Infrastructure**:

    ```bash
    pnpm exec tsx setup-sponsored-infrastructure.ts
    ```

4. **Update Environment Variables**:
    - Copy the addresses from the setup output
    - Update your `.env` file with the new addresses

### **Balance Requirements**

| Account                    | Purpose          | Minimum Balance | Recommended |
| -------------------------- | ---------------- | --------------- | ----------- |
| **Platform Funding EOA**   | Treasury/Funding | 0.02 ETH        | 0.1 ETH     |
| **Platform SimpleAccount** | Operations       | 0.01 ETH        | 0.05 ETH    |
| **User's EOA**             | Signatures Only  | 0 ETH           | 0 ETH       |

### **Funding Management**

```typescript
// Check balances
const simpleAccountBalance = await sponsoredDeployment.getPlatformBalance();
const platformBalance = await publicClient.getBalance({
	address: platformAccount.address,
});

console.log(`SimpleAccount: ${formatEther(simpleAccountBalance)} ETH`);
console.log(`Platform Funding EOA: ${formatEther(platformBalance)} ETH`);

// Auto-fund if needed
if (simpleAccountBalance < parseEther('0.01')) {
	await sponsoredDeployment.fundSimpleAccount(parseEther('0.05'));
}
```

## 📚 Documentation

-   [Sponsored Deployment Guide](docs/SPONSORED_DEPLOYMENT_GUIDE.md) - Complete deployment guide
-   [Sponsored Operations Guide](docs/SPONSORED_OPERATIONS_GUIDE.md) - Complete operations guide
-   [Migration Guide](docs/MIGRATION_GUIDE.md) - Migrate from old gasless to sponsored
-   [Examples](examples/README.md) - Working examples and frontend integration

## 🚀 Examples

### Infrastructure Setup

```bash
# Deploy all infrastructure (one-time setup)
pnpm exec tsx setup-sponsored-infrastructure.ts

# Deploy individual components
pnpm exec tsx deploy-simpleaccount.ts
pnpm exec tsx deploy-contract-deployer.ts
pnpm exec tsx deploy-kami-libraries.ts
```

### Backend Examples

```bash
# Deploy contracts with sponsored gas
pnpm exec tsx examples/sponsored-deployment-example.ts

# Perform all operations with sponsored gas
pnpm exec tsx examples/sponsored-operations-example.ts
```

### Frontend Examples

```typescript
// User signs message for any operation
const { userAddress, signature, nonce } = await requestUserSignatureForOperation(
	'mint',
	contractAddress,
	{
		recipient: userAddress,
		tokenPrice: parseEther('0.001'),
		uri: 'https://api.example.com/metadata/1',
		mintRoyalties: [
			{ receiver: userAddress, percentage: 500 },
			{ receiver: platformAddress, percentage: 250 },
		],
	},
	userAddress
);
```

## 🛡️ Security

-   **Signature Verification**: All user signatures are verified
-   **Replay Protection**: Nonce and timestamp prevent replay attacks
-   **Parameter Validation**: All operation parameters are validated
-   **Platform Security**: Platform private keys are kept secure

## 🛠️ Troubleshooting

### **Common Funding Issues**

#### **1. "Insufficient balance" Error**

```
Error: The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account.
```

**Solution**: Check which account has insufficient balance:

```typescript
// Check Platform Funding EOA balance
const platformBalance = await publicClient.getBalance({
	address: platformAccount.address,
});

// Check SimpleAccount balance
const simpleAccountBalance = await sponsoredDeployment.getPlatformBalance();

console.log(`Platform Funding EOA: ${formatEther(platformBalance)} ETH`);
console.log(`SimpleAccount: ${formatEther(simpleAccountBalance)} ETH`);
```

#### **2. "Function constructor not found on ABI" Error**

```
Error: Function "constructor" not found on ABI.
```

**Solution**: This was fixed in v0.8.1. Update to the latest version:

```bash
pnpm install @paulstinchcombe/gasless-nft-tx@latest
```

#### **3. Transaction Sent from Wrong Account**

```
from: 0xeaA30cdd68C6002e0ebA0Bed2374223561D0785E  # User's address (wrong!)
```

**Solution**: Check your `PLATFORM_PRIVATE_KEY` environment variable:

```bash
# This should be the Platform Funding EOA's private key, NOT the user's
export PLATFORM_PRIVATE_KEY=0x[PLATFORM_PRIVATE_KEY]
```

#### **4. SimpleAccount Balance Too Low**

```
Error: Insufficient SimpleAccount balance: 0.005 ETH (minimum required: 0.01 ETH)
```

**Solution**: Fund the SimpleAccount:

```typescript
// Manual funding
await sponsoredDeployment.fundSimpleAccount(parseEther('0.05'));

// Or let the system auto-fund
const result = await sponsoredDeployment.deployKAMI721C(params);
// System will auto-fund if needed
```

### **Debugging Steps**

1. **Check Account Addresses**:

    ```typescript
    console.log(`Platform Funding EOA: ${platformAccount.address}`);
    console.log(`SimpleAccount: ${config.platformSimpleAccountAddress}`);
    console.log(`User Address: ${userSignature.userAddress}`);
    ```

2. **Check Balances**:

    ```typescript
    const balances = await Promise.all([
    	publicClient.getBalance({ address: platformAccount.address }),
    	sponsoredDeployment.getPlatformBalance(),
    ]);

    console.log(`Platform Funding EOA: ${formatEther(balances[0])} ETH`);
    console.log(`SimpleAccount: ${formatEther(balances[1])} ETH`);
    ```

3. **Test Funding**:
    ```typescript
    const fundResult = await sponsoredDeployment.fundSimpleAccount(parseEther('0.01'));
    console.log(`Funding result:`, fundResult);
    ```

### **Environment Variable Checklist**

-   [ ] `PLATFORM_PRIVATE_KEY` - Platform Funding EOA's private key (has ETH)
-   [ ] `PLATFORM_SIMPLE_ACCOUNT_ADDRESS` - Platform's SimpleAccount address
-   [ ] `CONTRACT_DEPLOYER_ADDRESS` - ContractDeployer address
-   [ ] `PLATFORM_ADDRESS` - Platform address (for ERC20 commissions)
-   [ ] `PAYMENT_TOKEN` - Payment token address
-   [ ] `RPC_URL` - RPC endpoint URL

## 🎯 Benefits

1. **True Gasless Experience**: Users never need ETH
2. **Complete Operation Coverage**: All KAMI functions supported
3. **Platform Control**: Platform manages all gas costs
4. **User Ownership**: Operations affect user's contracts
5. **Scalable**: One platform SimpleAccount serves all users
6. **Cost Effective**: Platform pays only for actual operations

## 🔧 API Reference

### Sponsored Deployment

```typescript
// Deploy KAMI721C
const result = await sponsoredDeployment.deployKAMI721C(params);

// Deploy KAMI721AC
const result = await sponsoredDeployment.deployKAMI721AC(params);

// Deploy KAMI1155C
const result = await sponsoredDeployment.deployKAMI1155C(params);
```

### Sponsored Operations

```typescript
// Mint token
const result = await sponsoredOps.mintToken(contractAddress, contractType, params, signature);

// Rent token
const result = await sponsoredOps.rentToken(contractAddress, contractType, params, signature);

// Sell token
const result = await sponsoredOps.sellToken(contractAddress, contractType, params, signature);

// Set price
const result = await sponsoredOps.setPrice(contractAddress, contractType, params, signature);

// Set URI
const result = await sponsoredOps.setTokenURI(contractAddress, contractType, params, signature);

// Set royalties
const result = await sponsoredOps.setTokenRoyalties(contractAddress, contractType, params, signature);

// Pause contract
const result = await sponsoredOps.pauseContract(contractAddress, contractType, signature);

// Unpause contract
const result = await sponsoredOps.unpauseContract(contractAddress, contractType, signature);
```

## 🚀 Getting Started

1. **Install pnpm**: `npm install -g pnpm` or use `corepack enable`
2. **Install the library**: `pnpm install @paulstinchcombe/gasless-nft-tx`
3. **Set up environment**: Create `.env` file with platform configuration
4. **Deploy infrastructure**: Deploy ContractDeployer and libraries (one-time setup)
5. **Start using**: Deploy contracts and perform operations with sponsored gas!

## 📄 License

MIT License - see LICENSE file for details.

## 🤝 Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests.

## 📞 Support

For support and questions:

-   Create an issue on GitHub
-   Check the documentation
-   Review the examples

---

**🎉 Enjoy truly gasless NFT operations with the Sponsored KAMI NFT Transactions Library!**