An open API service indexing awesome lists of open source software.

https://github.com/onmax/nitro-nimiq-core-wasm

Repro for issue in Nitro
https://github.com/onmax/nitro-nimiq-core-wasm

Last synced: 20 days ago
JSON representation

Repro for issue in Nitro

Awesome Lists containing this project

README

          

# Nimiq Core + Nitro on Cloudflare Workers

This project demonstrates how to use `@nimiq/core` (Rust WASM package) with Nitro on Cloudflare Workers.

## Quick Start

```bash
pnpm install
pnpm dev
```

Visit `http://localhost:3000`

## Deploy

```bash
pnpm build
npx wrangler deploy
```

## How It Works

The key to making `@nimiq/core` work on Cloudflare Workers:

1. **Import WASM as ES module** - Cloudflare Workers provides `WebAssembly.Module`
2. **Use `initSync()` instead of `init()`** - Avoids blocked `WebAssembly.instantiate(bytes)`
3. **Mark WASM as external** - Let Cloudflare bundle it properly

### Route (`server/routes/index.ts`)

```typescript
import {PublicKey, initSync} from '@nimiq/core/web'
// @ts-ignore - Import WASM as ES module
import wasmModule from '@nimiq/core/web/main-wasm/index_bg.wasm'

let initialized = false

export default defineLazyEventHandler(async () => {
if (!initialized) {
initSync(wasmModule)
initialized = true
}

return eventHandler(async () => {
const publicKey = '82d80b86d9bf1906832e9f0ba4fa69018792f59190075c396b0e85aeac444e55'
const key = PublicKey.fromHex(publicKey)
return {
success: true,
result: key.toHex(),
note: 'Using initSync with ES module WASM - Cloudflare Workers compatible!'
}
})
})
```

### Configuration

**nitro.config.ts:**
```typescript
export default defineNitroConfig({
preset: "cloudflare-module",
experimental: { wasm: false }, // Disable unwasm
rollupConfig: {
plugins: [{
name: 'nimiq-wasm-external',
resolveId(id) {
if (id.endsWith('.wasm') || id.includes('.wasm?')) {
return { id, external: true }
}
}
}]
}
})
```

## Why This Works

- Cloudflare Workers **blocks** `WebAssembly.instantiate(bytes)` for security
- `initSync()` uses `new WebAssembly.Instance(module)` which is allowed
- ES module imports provide `WebAssembly.Module` instead of raw bytes

## Bundle Size

- **Total**: ~1.2 MB (includes WASM as separate module)
- **Worker code**: 190 KB
- **Deployed**: 456 KB gzipped