AgentSkillsCN

compact-core:typescript-integration

当您在TypeScript中实现见证函数、将Compact类型映射至TypeScript(Field→bigint、Bytes→Uint8Array)、部署合约、从TypeScript调用电路、读取链上状态,或使用JavaScript SDK构建Midnight DApp时,可选用此功能。

SKILL.md
--- frontmatter
name: compact-core:typescript-integration
description: Use when implementing witness functions in TypeScript, mapping Compact types to TypeScript (Field→bigint, Bytes→Uint8Array), deploying contracts, calling circuits from TypeScript, reading ledger state, or building Midnight DApps with the JavaScript SDK.

TypeScript Integration

Complete guide to integrating Midnight Compact contracts with TypeScript applications.

Type Mapping Quick Reference

Compact TypeTypeScript TypeNotes
FieldbigintZK field element
Uint<N>bigintAny bit width maps to bigint
BooleanbooleanDirect mapping
Bytes<N>Uint8ArrayFixed-length byte array
Opaque<'string'>stringUTF-8 string data
Opaque<'Uint8Array'>Uint8ArrayBinary data
struct{ field: Type, ... }Object with typed fields
enumDiscriminated union{ tag: 'Variant', value: T }
Vector<T, N>T[]Array of mapped type

Witness Implementation Pattern

typescript
import { WitnessContext } from '@midnight-ntwrk/midnight-js-types';

// Compact declaration: witness get_secret(): Field;
const witnesses = {
  get_secret: ({ privateState }: WitnessContext<PrivateState>): bigint => {
    return privateState.secret;
  }
};

Contract Interaction Flow

code
1. Compile Compact → Generated TypeScript types
2. Deploy contract → Get contract address
3. Create provider → Connect to Midnight node
4. Build witnesses → Implement private data access
5. Call circuits → Execute transactions
6. Read state → Query ledger values

Quick Examples

Calling a Circuit

typescript
import { Contract } from './contract';

const result = await contract.callTx.transfer({
  to: recipientAddress,
  amount: 1000n
}, witnesses);

Reading Ledger State

typescript
const balance = await contract.state.balances.get(userAddress);
// balance: bigint | undefined

Deploying a Contract

typescript
import { deployContract } from '@midnight-ntwrk/midnight-js-contracts';

const { contract, address } = await deployContract(provider, {
  privateStateKey: 'my-contract',
  initialPrivateState: { secret: 42n },
  witnesses
});

References

For detailed documentation on each topic:

Examples

Working TypeScript examples: