---
title: "Mpcium TypeScript Client"
description: "Client TypeScript để tương tác với dịch vụ Multi-Party Computation (MPC) của Mpcium nhằm tạo, quản lý ví và ký giao dịch trên nhiều blockchain."
url: https://docs.fystack.io/vi/mpcium/client
last_updated: 2026-11-13
---

> ## Documentation index
> Fetch the complete documentation index at: https://docs.fystack.io/llms.txt
> Use it to discover all available pages before exploring further.

# Mpcium TypeScript Client

Client TypeScript để tương tác với dịch vụ Multi-Party Computation (MPC) của Mpcium nhằm tạo, quản lý ví và ký giao dịch trên nhiều blockchain.

### Client ký

_Image: Hình ảnh ký Solana_

### Các node MPCIUM phối hợp để ký giao dịch

_Image: Các node MPCIUM_

## Yêu cầu trước

Quan trọng: Trước khi sử dụng client TypeScript này, bạn cần thiết lập các node MPC của Mpcium. Các node này cung cấp hạ tầng MPC nền tảng mà client kết nối tới.
Vui lòng làm theo hướng dẫn cài đặt và thiết lập để triển khai các node MPC cần thiết. Thông thường, bạn cần chạy nhiều node (ví dụ: 3 node trong cấu hình ngưỡng 2-of-3) trước khi sử dụng client này.

[Hướng dẫn đầy đủ cài đặt và chạy các node MPC](https://docs.fystack.io/vi/mpcium/installation.md)

## Tổng quan

Mpcium là dịch vụ cung cấp quản lý khóa an toàn và ký giao dịch bằng Multi-Party Computation. Thư viện client này cho phép bạn:

- Tạo khóa mật mã mà không làm lộ vật liệu khóa riêng tư
- Ký giao dịch cho nhiều mạng blockchain
- Nhận kết quả các thao tác mật mã thông qua đăng ký sự kiện

## Các loại khóa và blockchain được hỗ trợ

- **ECDSA**: Bitcoin, Ethereum và các chuỗi tương thích EVM khác
- **EdDSA**: Solana, Polkadot, Cardano và các chuỗi dựa trên EdDSA khác

## Cài đặt

```bash
npm install @fystack/mpcium-ts
```

## Ví dụ code có sẵn trên Github

[MPC Client Typescript](https://github.com/fystack/mpcium-client-ts)

## Tạo client

- Người dùng cần tạo `event_initiator.key` thông qua [mpcium-cli](https://github.com/fystack/mpcium/blob/master/INSTALLATION.md) trước khi sử dụng client này

```ts
import { connect } from "nats";
import { MpciumClient } from "@fystack/mpcium-ts";

async function setupClient() {
  // First, establish NATS connection
  const nc = await connect({ servers: "nats://localhost:4222" });

  // Create client with key path
  const mpcClient = await MpciumClient.create({
    nc: nc,
    keyPath: "./event_initiator.key",
  });

  return mpcClient;
}
```

### Client được mã hóa (Khuyến nghị cho môi trường production)

```ts
const mpcClient = await MpciumClient.create({
  nc: nc,
  keyPath: "./event_initiator.key.age",
  password: "your-secure-password", // Stored and load secure vault like KMS, Hashicorp vault
});
```

### Tạo ví

```ts
import { connect } from "nats";
import { MpciumClient } from "@fystack/mpcium-ts";
import fs from "fs";

async function generateWallet() {
  const nc = await connect({ servers: "nats://localhost:4222" });
  const mpcClient = await MpciumClient.create({
    nc: nc,
    keyPath: "./event_initiator.key",
  });

  // Store wallets in a file (for testing only)
  const walletsFile = "./examples/wallets.json";
  const wallets = fs.existsSync(walletsFile)
    ? JSON.parse(fs.readFileSync(walletsFile, "utf8"))
    : {};

  // Subscribe to wallet creation results
  mpcClient.onWalletCreationResult((event) => {
    console.log("Received wallet creation result:", event);

    // Store wallet info with wallet_id as key
    wallets[event.wallet_id] = {
      wallet_id: event.wallet_id,
      ecdsa_pub_key: event.ecdsa_pub_key,
      eddsa_pub_key: event.eddsa_pub_key,
    };

    // Save to file (in production, use a database)
    fs.writeFileSync(walletsFile, JSON.stringify(wallets, null, 2));
    console.log(`Wallet ${event.wallet_id} saved to wallets.json`);
    console.log(
      "NOTE: File storage is for testing only. Use a database in production."
    );
  });

  // Create the wallet
  const walletID = await mpcClient.createWallet();
  console.log(`CreateWallet request sent, wallet ID: ${walletID}`);

  // Wait for result and handle cleanup
  process.on("SIGINT", async () => {
    await mpcClient.cleanup();
    await nc.drain();
    process.exit(0);
  });
}
```

### Ký giao dịch Solana

```ts
import { connect } from "nats";
import { MpciumClient, KeyType } from "@fystack/mpcium-ts";
import {
  Connection,
  Transaction,
  SystemProgram,
  PublicKey,
  LAMPORTS_PER_SOL,
} from "@solana/web3.js";
import fs from "fs";

async function signSolanaTransaction(walletId) {
  const nc = await connect({ servers: "nats://localhost:4222" });
  const mpcClient = await MpciumClient.create({
    nc: nc,
    keyPath: "./event_initiator.key",
  });

  // Get wallet information from wallets.json
  const walletsFile = "./examples/wallets.json";
  const wallets = JSON.parse(fs.readFileSync(walletsFile, "utf8"));
  const wallet = wallets[walletId];

  if (!wallet) {
    throw new Error(`Wallet ${walletId} not found`);
  }

  // Connect to Solana devnet
  const connection = new Connection(
    "https://api.devnet.solana.com",
    "confirmed"
  );

  // Create public key from wallet data
  const publicKeyBuffer = Buffer.from(wallet.eddsa_pub_key, "base64");
  const fromPublicKey = new PublicKey(publicKeyBuffer);

  // Create transaction
  const transaction = new Transaction().add(
    SystemProgram.transfer({
      fromPubkey: fromPublicKey,
      toPubkey: new PublicKey("4LKprD1XvTuBupHqWXoS42XsEBHp7qALo3giDBRCNhAV"),
      lamports: LAMPORTS_PER_SOL * 0.01,
    })
  );

  // Get recent blockhash
  const { blockhash } = await connection.getLatestBlockhash();
  transaction.recentBlockhash = blockhash;
  transaction.feePayer = fromPublicKey;

  // Serialize transaction message
  const serializedTx = transaction.serializeMessage();

  // Listen for signing results
  mpcClient.onSignResult((event) => {
    if (event.result_type === 1) {
      // Success
      const signature = Buffer.from(event.signature, "base64");
      transaction.addSignature(fromPublicKey, signature);

      if (transaction.verifySignatures()) {
        connection
          .sendRawTransaction(transaction.serialize())
          .then((txId) => console.log(`Transaction sent: ${txId}`));
      }
    }
  });

  // Send signing request
  await mpcClient.signTransaction({
    walletId: walletId,
    keyType: KeyType.Ed25519,
    networkInternalCode: "solana:devnet",
    tx: Buffer.from(serializedTx).toString("base64"),
  });
}
```

[Ví dụ đầy đủ: sign-solana.ts](https://github.com/fystack/mpcium-client-ts/blob/master/examples/sign-solana.ts)

## Kiểm thử

### 1. Tạo ví MPC

```
npx ts-node ./examples/generate-wallet.ts
```

```
Connected to NATS at localhost:4222
Subscribed to wallet creation results
CreateWallet request sent for wallet: a99900b2-0ef8-4d7e-8c3f-2ef85abbae4c
CreateWallet sent, awaiting result... walletID: a99900b2-0ef8-4d7e-8c3f-2ef85abbae4c
Received wallet creation result: {
  wallet_id: 'a99900b2-0ef8-4d7e-8c3f-2ef85abbae4c',
  ecdsa_pub_key: '1ftOqTd9z540F7J6bSLJJ8gqn85HlyQKetWB4mACDFBhaodgiNr9ILL5wZ95yWpaqQc77f02rQklUeDSZhLVVA==',
  eddsa_pub_key: 'm0qUKZlxmzgYA9sRh1Q7cQJHT8jEdUQjbic8hQNHG2o='
}
Solana wallet address: BTC9kvDchPvu84iMzLbhYBg5bWma4QHDAFumpF41ErjT
Ethereum wallet address: 0x309bdE4d218e44E4a391f4c43Bf6226156D3255b
Wallet saved to wallets.json with ID: a99900b2-0ef8-4d7e-8c3f-2ef85abbae4c

```

### 2. Chuyển Solana vào ví

- Sử dụng Phantom để chuyển SOL trên devnet vào ví

###

### 3. Ký giao dịch Solana

```
npx ts-node ./examples/sign-solana.ts a99900b2-0ef8-4d7e-8c3f-2ef85abbae4c
```

### 4. Ký giao dịch Ethereum

```
npx ts-node ./examples/sign-eth.ts a99900b2-0ef8-4d7e-8c3f-2ef85abbae4c
```
