neo-devpack-solidity 0.22.0

Production-focused Solidity-to-NeoVM compilation system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# Neo DevPack for Solidity Comprehensive Development Tooling

A complete toolchain under active development for Neo DevPack for Solidity. Some packages remain experimental, but the core workspace now has build/test/lint/typecheck coverage.

> ⚠️ **Current Status**  
> - `@neo-devpack-solidity/hardhat-solc-neo`: compile/clean/verify tasks work; advanced Hardhat integration is still evolving.  
> - `@neo-devpack-solidity/hardhat-neo-deployer`: builds/signs/sends real Neo N3 deploy transactions (NEF + manifest); still experimental.  
> - The Hardhat plugins currently target Hardhat 2.28.x. Hardhat 3 uses a different plugin/runtime model and needs a dedicated migration before it can be supported.
> - `@neo-devpack-solidity/neo-foundry` (`neo-forge`, `neo-cast`, `neo-anvil`): `init` is real; build/test/deploy flows remain scaffolding.  
> - `@neo-devpack-solidity/abi-router`, `@neo-devpack-solidity/cli-tools`: usable for ABI/CLI composition, but still not full end-to-end deployment frameworks.
> - `@neo-devpack-solidity/templates`, `@neo-devpack-solidity/integration-tests`: now wired into the workspace and covered by the tooling test/lint/typecheck pipeline.

## 🏗️ Architecture Overview

```
Neo DevPack for Solidity Tooling Ecosystem
├── Hardhat Integration
│   ├── @neo-devpack-solidity/hardhat-solc-neo      # Compilation plugin
│   └── @neo-devpack-solidity/hardhat-neo-deployer  # Deployment plugin
├── Foundry Integration  
│   └── @neo-devpack-solidity/neo-foundry           # Foundry-style scaffold + init flow
├── Core Libraries
│   ├── @neo-devpack-solidity/types                 # Shared type definitions
│   ├── @neo-devpack-solidity/abi-router            # ABI compatibility layer
│   └── @neo-devpack-solidity/cli-tools             # Command-line tools
└── Developer Experience
    ├── @neo-devpack-solidity/templates             # Project scaffolding templates
    ├── @neo-devpack-solidity/integration-tests     # Cross-package smoke coverage
    ├── Network configurations              # Neo network presets
    ├── Artifact management                 # Build output handling
    └── Debugging support                   # Development debugging
```

## 🚀 Quick Start

### 1. Hardhat Setup (compile + deploy)

```bash
npm install --save-dev hardhat@^2.28.6
npm install --save-dev @neo-devpack-solidity/hardhat-solc-neo
npm install --save-dev @neo-devpack-solidity/hardhat-neo-deployer

# hardhat.config.ts
import "@neo-devpack-solidity/hardhat-solc-neo";
import "@neo-devpack-solidity/hardhat-neo-deployer";

export default {
  neoSolc: {
    solidity: {
      version: "0.8.34",
      settings: {
        optimizer: { enabled: true, runs: 200 },
        neo: { callt: true }
      }
    }
  },
  neoNetworks: {
    testnet: {
      rpcUrls: ["https://testnet1.neo.coz.io:443"],
      magic: 894710606,
      accounts: [process.env.NEO_WIF || ""] // WIF or private key (hex)
    }
  }
};

# Compile contracts
npx hardhat neo-compile

# Deploy contracts
npx hardhat neo-deploy --contract MyContract --network testnet
```

### 2. Foundry Setup

```bash
npm install -g @neo-devpack-solidity/neo-foundry

# Initialize project
neo-forge init my-neo-project
cd my-neo-project

# neo-foundry.toml configuration
[profile.default]
src = "src"
test = "test" 
script = "script"
out = "out"

# Build and test
# `init` is implemented; build/test remain scaffold-only today.
neo-forge build
neo-forge test
```

### 3. CLI Tools

```bash
npm install -g @neo-devpack-solidity/cli-tools

# Compile contracts directly
solc-neo compile contracts/*.sol --optimize --gas-model hybrid

# Analyze contracts
solc-neo analyze contracts/*.sol --gas-report --size-report

# Verify on-chain NEF/manifest matches your local compilation output
solc-neo verify-contract --address N123... --source Token.sol --contract Token --network testnet
```

## 📦 Package Ecosystem

### Core Packages

#### `@neo-devpack-solidity/types`
Shared TypeScript interfaces and type definitions for all tooling packages.

**Key Types:**
- `NeoDevpackSolidityConfig` - Compiler configuration
- `NeoNetworkConfig` - Network definitions  
- `BuildArtifact` - Compilation artifacts
- `ContractDeployment` - Deployment results
- `NeoRpcProvider` - RPC interface

#### `@neo-devpack-solidity/abi-router` 
ABI-compatible interface layer that bridges Ethereum tooling to Neo contracts. It currently supports static ABIs and best-effort event scanning; transaction signing + deployments are handled by `@neo-devpack-solidity/hardhat-neo-deployer` or native Neo tooling.

**Current capabilities / caveats:**
- ✅ Ethereum-style contract interaction (call/send/estimate).
-`AbiRouter.deployContract({ nef, manifest }, abi)` when you pass in the compiler artifacts manually.
- ✅ Basic event filtering (linear scan via RPC application logs).
- ⚠️ No automatic artifact registry or dynamic ABI decoding yet.
- ⚠️ Large block ranges can be slow because filtering is sequential.

```typescript
import { readFileSync } from 'fs';
import { AbiRouter } from '@neo-devpack-solidity/abi-router';

const router = new AbiRouter(neoRpcProvider);
const artifacts = { nef: readFileSync('Token.nef', 'hex'), manifest: require('./Token.manifest.json') };

// Deploy a NEF/manifest pair compiled by neo-solc
const deployed = await router.deployContract(artifacts, abi);

// Wrap an existing Neo contract with Ethereum-style methods
const contract = router.createContract(deployed.address, abi, signer);
await contract.transfer(recipient, amount);
      const balance = await contract.balanceOf(account);
```

#### `@neo-devpack-solidity/templates`
Project scaffolding helpers for Neo DevPack for Solidity. The package now ships as a real workspace package and can generate current Hardhat-based starter projects that use `neo-compile`, `neo-deploy`, and `neo-verify` instead of stale EVM-only scripts.

#### `@neo-devpack-solidity/integration-tests`
Workspace-level smoke coverage for the package boundary between templates, CLI tools, Neo Foundry, and the ABI router. These tests intentionally validate the behavior the packages support today rather than future placeholder workflows.

### Hardhat Integration

#### `@neo-devpack-solidity/hardhat-solc-neo`
Hardhat plugin for compiling Solidity to NeoVM bytecode. The runtime extension only exposes `hre.neoSolc.compiler` and `hre.neoSolc.artifacts`; other helpers were removed until a real Neo RPC workflow exists.

**Tasks (currently supported):**
- `neo-compile` - Compile contracts
- `neo-clean` - Clean build artifacts  
- `neo-verify` - Verify on-chain NEF/manifest matches local build artifact (updates deployment metadata)

Pair this with `@neo-devpack-solidity/hardhat-neo-deployer` if you want `neo-deploy` tasks inside Hardhat.

**Configuration:**
```typescript
neoSolc: {
  solidity: {
    version: "0.8.34",
    settings: {
      optimizer: { enabled: true, runs: 200 },
      neo: { callt: true }
    }
  }
}
```

#### `@neo-devpack-solidity/hardhat-neo-deployer`
Experimental Hardhat plugin for deploying Neo N3 contracts. It builds/signs/sends `ContractManagement.deploy` transactions using the NEF + manifest embedded in build artifacts.

**Status**
- `neo-deploy` / `neo-deploy-batch`: submit real deployment transactions.
- `neo-deploy-estimate`: uses `invokescript` + `calculatenetworkfee` to estimate fees.
- `neo-accounts` helpers: derive accounts from WIF/private key; no encrypted keystore yet.

### Foundry Integration

#### `@neo-devpack-solidity/neo-foundry`
Foundry-style tooling for Neo. `neo-forge init` now creates a working project layout and config; build/test/transaction flows remain scaffold-only.

**Tools:**
- `neo-forge` - Build/test CLI (prints stub messages today)
- `neo-cast` - Contract interaction tool (WIP)
- `neo-anvil` - Local Neo blockchain stub

**Commands:**
```bash
# Build system (WIP)
neo-forge build --watch
neo-forge test --gas-report
neo-forge clean

# Contract interaction (WIP)
neo-cast call 0x123... balanceOf 0xabc...
neo-cast send 0x123... transfer 0xdef... 100

# Local blockchain (WIP)
neo-anvil --port 40332 --accounts 10
```

## 🌐 Network Configuration

### Predefined Networks

```typescript
// Built-in network configurations
const networks = {
  mainnet: {
    name: "Neo MainNet",
    rpcUrls: ["https://mainnet1.neo.coz.io:443"],
    magic: 860833102,
    nativeTokens: { gas: "0xd2a4...", neo: "0xef40..." }
  },
  testnet: {
    name: "Neo TestNet", 
    rpcUrls: ["https://testnet1.neo.coz.io:443"],
    magic: 894710606,
    testnet: true
  },
  private: {
    name: "Neo Private",
    rpcUrls: ["http://localhost:40332"],
    magic: 12345,
    testnet: true
  }
};
```

### Custom Network Setup

```typescript
// hardhat.config.ts
neoNetworks: {
  "custom-network": {
    name: "Custom Neo Network",
    rpcUrls: ["https://rpc.custom-neo.com"],
    magic: 123456,
    addressVersion: 0x35,
    accounts: ["0x..."] // Private keys or mnemonic
  }
}
```

## 🔧 Development Workflow

### 1. Project Structure

```
my-neo-project/
├── contracts/           # Solidity source files
│   ├── Token.sol
│   └── interfaces/
├── test/               # Test files
│   └── Token.test.ts
├── scripts/            # Deployment scripts
│   └── deploy.ts
├── artifacts/          # Build artifacts
│   └── contracts/
├── deployments/        # Deployment records
│   ├── testnet/
│   └── mainnet/
├── hardhat.config.ts   # Hardhat configuration
└── neo-foundry.toml   # Neo Foundry configuration
```

### 2. Contract Development

```solidity
// contracts/Token.sol
pragma solidity ^0.8.34;

contract MyToken {
    mapping(address => uint256) public balances;
    uint256 public totalSupply;

    constructor(uint256 initialSupply) {
        totalSupply = initialSupply;
        balances[msg.sender] = initialSupply;
    }

    function transfer(address from, address to, uint256 amount, bytes memory data) external returns (bool) {
        data;
        require(from == msg.sender, "from must be caller");
        require(balances[from] >= amount, "insufficient balance");
        balances[from] -= amount;
        balances[to] += amount;
        return true;
    }
}
```

### 3. Testing

```typescript
// test/Token.test.ts
import { expect } from "chai";
import hre from "hardhat";

describe("MyToken build", function () {
  it("emits Neo build artifacts", async function () {
    await hre.run("neo-compile", { force: true, quiet: true });

    const artifact = await hre.neoSolc.artifacts.getBuildArtifact("MyToken");

    expect(artifact).to.not.equal(null);
    expect(artifact?.contract.neo.manifest.name).to.equal("MyToken");
    expect(artifact?.contract.neo.manifest.abi.methods.length).to.be.greaterThan(0);
  });
});
```

### 4. Deployment

```bash
# Compile Neo build artifacts
npx hardhat neo-compile

# Deploy using the Neo deployer plugin
npx hardhat neo-deploy --contract MyToken --args '[1000000]' --network testnet

# Verify deployed NEF + manifest against the local build artifact
npx hardhat neo-verify --contract MyToken --address <contract-address> --constructor-args '[1000000]' --network testnet
```

## 🛠️ Advanced Features

### Artifact Management

The Hardhat Neo compiler plugin exposes artifact helpers through `hre.neoSolc.artifacts`:

```typescript
import hre from "hardhat";

const buildArtifact = await hre.neoSolc.artifacts.getBuildArtifact("MyToken");
const deployment = await hre.neoSolc.artifacts.getDeploymentArtifact("MyToken", "testnet");
const allBuildArtifacts = await hre.neoSolc.artifacts.getAllBuildArtifacts();
const stats = await hre.neoSolc.artifacts.getStatistics();
```

### Debugging Support

There is no published `@neo-devpack-solidity/debugger` package yet. For debugging today:

```bash
# Emit NeoVM assembly for inspection
neo-solc contracts/Token.sol -f assembly -o build/Token.asm

# Run against Neo-Express and inspect invocation logs
neoxp contract invoke <contract-hash> totalSupply
```

### Gas Optimization

Analyze and optimize gas usage:

```bash
# Generate gas reports
neo-forge test --gas-report

# Analyze optimization opportunities
solc-neo analyze contracts/*.sol --gas-report --size-report

# Output format options
solc-neo analyze --output table   # Console table
solc-neo analyze --output json    # JSON format  
solc-neo analyze --output csv     # CSV export
```

## 📚 API Reference

### Compiler Configuration

```typescript
interface NeoDevpackSolidityConfig {
  version?: string;
  optimizer?: {
    enabled: boolean;
    runs: number;
  };
  neo?: {
    gasCostModel?: 'ethereum' | 'neo' | 'hybrid';
    storageOptimization?: boolean;
    eventOptimization?: boolean;
  };
}
```

### Network Configuration

```typescript
interface NeoNetworkConfig {
  name: string;
  rpcUrls: string[];
  magic: number;
  addressVersion: number;
  nativeTokens: {
    gas: NeoToken;
    neo: NeoToken;
  };
}
```

### Contract Interface

```typescript
interface ContractWrapper {
  address: string;
  interface: Interface;
  
  // Read-only calls
  call(method: string, args: any[]): Promise<any>;
  
  // State-changing transactions  
  send(method: string, args: any[]): Promise<TransactionResponse>;
  
  // Gas estimation
  estimateGas(method: string, args: any[]): Promise<bigint>;
  
  // Event handling
  on(event: string, listener: Function): this;
  queryFilter(event: string, filter?: any): Promise<any[]>;
}
```

## 🔍 Troubleshooting

### Common Issues

**Compiler Not Found**
```bash
# Install compiler
npm install -g @neo-devpack-solidity/cli-tools
solc-neo install latest
```

**Network Connection Issues**
```typescript
// Check network configuration
neoNetworks: {
  testnet: {
    rpcUrls: ["https://testnet1.neo.coz.io:443"], // Verify URL
    magic: 894710606, // Correct magic number
    timeout: 30000    // Increase timeout
  }
}
```

**Gas Estimation Failures**
```typescript
// Increase gas limits
const tx = await contract.method({
  gasLimit: "50000000", // 0.5 GAS
  gasPrice: "1000"
});
```

### Debug Mode

Enable debug logging:

```bash
DEBUG=neo-devpack-solidity:* npx hardhat neo-compile
DEBUG=neo-foundry:* neo-forge build
```

## 🤝 Contributing

Contributions welcome! Please see [CONTRIBUTING.md](../CONTRIBUTING.md) for guidelines.

### Development Setup

```bash
git clone https://github.com/r3e-network/neo-devpack-solidity
cd neo-devpack-solidity/tooling
npm install
npm run build
```

### Testing

```bash
npm test                 # Run all tests
npm run test:watch       # Watch mode
npm run test:coverage    # Coverage report
```

## 📄 License

MIT License - see [LICENSE](../LICENSE) for details.

---

**Built for the Neo ecosystem** 🚀