npm package: @mayflower-fi/evm-gen
Description: Low-level TypeScript bindings for exchange contracts
Author: Mayflower Finance
Latest version: 0.0.5

# @mayflower-fi/evm-gen

TypeScript SDK for interacting with Mayflower Finance smart contracts. This package provides type-safe, low-level TypeScript bindings generated from the contract ABIs using TypeChain.

## What's Included

This SDK contains:
- **TypeChain-generated TypeScript bindings** for all Mayflower contracts
- **Factory classes** for deploying contracts (if you have bytecode)
- **Type definitions** for all contract methods, events, and structs
- **Full ABI information** embedded in the TypeScript files

## Installation

```bash
npm install @mayflower-fi/evm-gen ethers@^6
# or
yarn add @mayflower-fi/evm-gen ethers@^6
# or
pnpm add @mayflower-fi/evm-gen ethers@^6
```

Note: This package requires `ethers` v6.x as a peer dependency.

## Usage

### Basic Contract Interaction

```typescript
import { ethers } from 'ethers';
import { 
  IMarket__factory,
  IMarketGroup__factory,
  ITenant__factory 
} from '@mayflower-fi/evm-gen';

// Connect to a provider
const provider = new ethers.JsonRpcProvider('https://your-rpc-url');
const signer = await provider.getSigner();

// Connect to deployed contracts using factory classes
const marketAddress = '0x...';
const market = IMarket__factory.connect(marketAddress, signer);

// Now you have full TypeScript support for all methods
const supply = await market.derivativeSupply();
const floorPrice = await market.floorPrice();

// Execute transactions with type safety
const tx = await market.buyWithExactBaseIn(
  ethers.parseUnits('100', 6), // baseAmountIn
  ethers.parseUnits('50', 18),  // minTokenOut
  await signer.getAddress()     // recipient
);
```

### Working with Events

```typescript
import { IMarket__factory } from '@mayflower-fi/evm-gen';
import type { TokensBoughtEvent } from '@mayflower-fi/evm-gen/contracts/interfaces/IMarket';

const market = IMarket__factory.connect(marketAddress, provider);

// Listen to events with type safety
market.on('TokensBought', (buyer, baseAmount, tokenAmount, fee, event) => {
  console.log(`Buyer: ${buyer}`);
  console.log(`Base Amount: ${baseAmount.toString()}`);
  console.log(`Token Amount: ${tokenAmount.toString()}`);
  console.log(`Fee: ${fee.toString()}`);
});

// Query past events
const filter = market.filters.TokensBought();
const events = await market.queryFilter(filter, fromBlock, toBlock);
```

### Type Imports

All TypeScript types are available for import:

```typescript
import type {
  IMarket,
  IMarketGroup,
  ITenant,
  LinearMarketImplementation,
  MarketGroupImplementation
} from '@mayflower-fi/evm-gen';

// Struct types
import type { 
  IMarket.StructsStruct 
} from '@mayflower-fi/evm-gen/contracts/interfaces/IMarket';

// Event types
import type {
  TokensBoughtEvent,
  TokensSoldEvent,
  BorrowedEvent
} from '@mayflower-fi/evm-gen/contracts/interfaces/IMarket';
```

### Factory Pattern Usage

If you have deployment privileges or are working with a local testnet:

```typescript
import { MarketFactory__factory } from '@mayflower-fi/evm-gen';

// Deploy a new MarketFactory (requires bytecode)
const marketFactory = await new MarketFactory__factory(signer).deploy(
  implementationAddress
);
await marketFactory.waitForDeployment();

// Or connect to existing factory
const factory = MarketFactory__factory.connect(factoryAddress, signer);
```

## Contract Architecture

The SDK mirrors the smart contract architecture:

### Core Contracts
- **TenantFactory** - Creates and manages tenants
- **TenantImplementation** - Tenant logic (cloned)
- **MarketGroupFactory** - Creates market groups
- **MarketGroupImplementation** - Market group logic (cloned)
- **MarketFactory** - Creates markets
- **LinearMarketImplementation** - Market logic with linear bonding curves

### Interfaces
All contracts implement well-defined interfaces:
- `ITenantFactory` - Tenant factory operations
- `ITenant` - Tenant management
- `IMarketGroupFactory` - Market group factory operations
- `IMarketGroup` - Market group management
- `IMarketFactory` - Market factory operations
- `IMarket` - Market trading and position management

## Fee Precision

Fee rates in the contracts use **micro-basis points** for precision:
- 1 micro-basis point = 0.0001%
- 10,000 = 1%
- 2,500 = 0.25%
- 100 = 0.01%
- 1 = 0.0001%

All fee rates are stored as `uint32` values with a maximum of 1,000,000 (100%).

## Common Patterns

### Reading Contract State

```typescript
// Get market information
const baseToken = await market.baseToken();
const derivativeToken = await market.derivativeToken();
const liquidity = await market.liquidity();
const reserves = await market.reserves();

// Get user position
const [collateral, debt] = await market.getPosition(userAddress);

// Get fee rates (returns uint32 in micro-basis points)
const buyFeeRate = await marketGroup.buyFeeRate();
const actualFeePercent = buyFeeRate / 10000; // Convert to percentage
```

### Executing Trades

```typescript
// Approve base token first
const baseToken = IERC20__factory.connect(baseTokenAddress, signer);
await baseToken.approve(marketAddress, amount);

// Buy derivative tokens
const tx = await market.buyWithExactBaseIn(
  amount,
  minTokensOut,
  recipientAddress
);
const receipt = await tx.wait();

// Decode events from receipt
const events = receipt.logs
  .map(log => {
    try {
      return market.interface.parseLog(log);
    } catch {
      return null;
    }
  })
  .filter(Boolean);
```

### Managing Positions

```typescript
// Deposit collateral
await derivativeToken.approve(marketAddress, collateralAmount);
await market.depositCollateral(collateralAmount);

// Borrow against collateral
await market.borrow(borrowAmount);

// Repay debt
await baseToken.approve(marketAddress, repayAmount);
await market.repay(repayAmount);

// Withdraw collateral
await market.withdrawCollateral(withdrawAmount);
```

## Advanced Usage

### Using with Hardhat

```typescript
import { ethers } from 'hardhat';
import { IMarket__factory } from '@mayflower-fi/evm-gen';

describe('Market Tests', () => {
  it('should interact with market', async () => {
    const [signer] = await ethers.getSigners();
    const market = IMarket__factory.connect(marketAddress, signer);
    
    // Your test code here
  });
});
```

### Type Guards

```typescript
import { IMarket } from '@mayflower-fi/evm-gen';

function isMarketContract(contract: any): contract is IMarket {
  return (
    'buyWithExactBaseIn' in contract &&
    'sellWithExactTokenIn' in contract &&
    'depositCollateral' in contract
  );
}
```

## Package Structure

```
@mayflower-fi/evm-gen/
├── dist/                   # Compiled JavaScript output
│   ├── index.js           # Main entry point
│   ├── index.d.ts         # TypeScript declarations
│   └── typechain/         # Generated contract bindings
├── src/                    # TypeScript source
│   ├── index.ts           # Main exports
│   └── typechain/         # TypeChain generated files
│       ├── contracts/     # Contract interfaces and types
│       ├── factories/     # Contract factory classes
│       └── common.ts      # Common types
└── package.json
```

## Development

This package is automatically generated from the Solidity contracts using TypeChain. When contracts are updated:

1. Contracts are compiled: `pnpm compile`
2. TypeChain generates TypeScript bindings
3. Bindings are copied to this package
4. Package is built: `pnpm build`

To regenerate the SDK after contract changes:
```bash
# From project root
pnpm build:all
```

## Related Packages

- **@mayflower-fi/solidity-interfaces** - Solidity interface files and deployment helpers
- **@mayflower-fi/evm-program** - Core smart contracts (private)

## License

MIT

## Support

For issues or questions, please contact Mayflower Finance.