」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 Sui TypeScript SDK

如何使用 Sui TypeScript SDK

發佈於2024-11-03
瀏覽:548

Sui 是当下的链,尽管 Move 是在 Sui 上编写智能合约的圣杯,但 TypeScript 支持也很重要。您可以通过 TypeScript 与 Sui 以及生态系统中的大多数 DeFi 应用进行交互和使用。

在本教程中,我将教您如何通过 TypeScript 与 Sui 网络交互。您将学习如何读取区块链的状态,如何从 TypeScript 程序将交易写入链。

Sui 和 TypeScript 入门

唯一的先决条件是您需要基本的 JS/TS 知识才能顺利运行本教程。我将引导您完成其他所有事情。

首先,在终端中创建一个新的 TypeScript 项目并初始化一个新的 Node.js 项目。

mkdir SuiTS
cd SuiTS
npm init -y

如果您还没有安装 TypeScript 作为开发依赖项。

npm install typescript --save-dev
npm install ts-node //runs TS without the need for transpiling

现在,您可以初始化一个新的 TypeScript 项目。此命令将创建一个 tsconfig.json 文件,其中包含您可以为项目自定义的默认选项。

npx tsc --init

打开 tsconfig.json 并粘贴这些配置。

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "types": ["node"],
    "resolveJsonModule": true
  },
  "exclude": ["node_modules"],

  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js"
  }
}

创建一个 src 目录,您将在其中添加 TypeScript 文件。

mkdir src
touch src/index.ts

最后,使用此命令安装 Sui TypeScript SDK。

npm i @mysten/sui.js

一切准备就绪。您可以开始编写与 Sui 区块链交互的 TypeScript 程序。

连接到 Sui 区块链

您必须连接到 Sui 区块链才能与该链交互。

首先,从SDK客户端模块导入getFullnodeUrl和SuiClient。

import { getFullnodeUrl, SuiClient } from '@mysten/sui/client';

现在,根据您想要的连接,您可以使用 getFullnodeUrl 检索 Sui 测试网、主网、本地网或开发网的完整节点 URL;然后,使用 SuiClient 连接到客户端实例。

import { getFullnodeUrl, SuiClient } from '@mysten/sui/client';

const rpcUrl = getFullnodeUrl('mainnet');

const client = new SuiClient({ url: rpcUrl });

要测试您的连接,您可以使用 getLatestSuiSystemState 来检索网络的最新状态。

// index.ts
import { getFullnodeUrl, SuiClient } from '@mysten/sui/client';

const rpcUrl = getFullnodeUrl("mainnet");

const client = new SuiClient({ url: rpcUrl });

async function getNetworkStatus() {
    const currentEpoch = await client.getLatestSuiSystemState();
    console.log(currentEpoch)
}

getNetworkStatus();

现在,将 TypeScript 代码转换为 JavaScript 并使用以下命令运行它:

ts-node index.ts

执行该命令时,您应该会得到与此类似的输出。

How to Use the Sui TypeScript SDK

创建 Sui 钱包

创建钱包是另一种流行的操作,如果您在 Sui Network 上构建,它可能会很方便。

以下是如何生成 Sui 钱包密钥对并从密钥对中检索私钥和公钥。

import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
import { getFullnodeUrl, SuiClient } from '@mysten/sui/client';

const rpcUrl = getFullnodeUrl("mainnet");

const client = new SuiClient({ url: rpcUrl });

// random Keypair
const keypair = new Ed25519Keypair();

const publicKey = keypair.getPublicKey();
const privatekey = keypair.getSecretKey();

console.log(privatekey.toString());
console.log(publicKey.toSuiAddress());

Ed25519Keypair 函数创建一个新的密钥对。 getPublicKey 和 getPrivateKey 方法分别允许您访问公钥和私钥。

这是我用程序生成的私钥和公钥的字符串输出:

suiprivkey1qq9r6rkysny207t5vr7m5025swh7w0wzra9p0553paprhn8zshqsx2rz64r
New Sui Address: 0xbd46d7582ced464ef369114252704b10317436ef70f196a33fcf2c724991fcba

我用 0.25 Sui 为这个钱包提供资金,用于下一组操作。请随时验证并扫描钱包。请勿发送任何资金;这只是一个虚拟钱包。

读取 Sui 钱包余额

您可以在客户端实例上使用 getCoins 函数来检索钱包地址中硬币的详细信息。

import { getFullnodeUrl, SuiClient } from '@mysten/sui/client';

// use getFullnodeUrl to define the Devnet RPC location
const rpcUrl = getFullnodeUrl('mainnet');

// create a client connected to devnet
const client = new SuiClient({ url: rpcUrl });

async function getOwnedCoins() {
    const coins = await client.getCoins({
        owner: '0xbd46d7582ced464ef369114252704b10317436ef70f196a33fcf2c724991fcba',
    });
    console.log(coins);
}

getOwnedCoins();

该函数返回隋币单独的详细信息和详细信息。输出为 MIST,即 Sui 天然气代币。 1 SUI 等于 10 亿 MIST。

How to Use the Sui TypeScript SDK

同样可以使用getAllCoins函数来获取钱包中所有币的列表。

async function getAllCoins() {
    // Get the list of owned coins (tokens) for the given owner address
    const ownedCoins = await client.getAllCoins({ owner: "0xbd46d7582ced464ef369114252704b10317436ef70f196a33fcf2c724991fcba" });

    // Access the coin data
    const coins = ownedCoins.data;

    // Iterate through the coins and print their details
    for (const coin of coins) {
        console.log(`Coin Type: ${coin.coinType}`);
        console.log(`Coin Object ID: ${coin.coinObjectId}`);
        console.log(`Balance: ${coin.balance}`);
        console.log('--------------------');
    }

    // If there is more data, handle pagination
    if (ownedCoins.hasNextPage) {
        console.log('More data available. Fetching next page...');
        // You can handle the next page using ownedCoins.nextCursor if needed
    }
}

getAllCoins();

对于这个例子,我在 Hop Aggregator 上用一些 Sui 换取 $FUD,这是运行程序后的输出。

How to Use the Sui TypeScript SDK

发送硬币或物品

最后,有趣的部分是您将学习在区块链上发送交易。

让我们将一些 $FUD 代币发送到另一个钱包。这适用于 Sui 网络上的任何代币。

import {getFullnodeUrl, SuiClient} from '@mysten/sui/client';
import {Ed25519Keypair} from '@mysten/sui/keypairs/ed25519';
import {Transaction} from '@mysten/sui/transactions';

// Set the RPC URL to connect to the Sui mainnet
const rpcUrl = getFullnodeUrl("mainnet");

const client = new SuiClient({url: rpcUrl});

// Create the keypair using the private key
const keypair = Ed25519Keypair.fromSecretKey("suiprivkey1qq9r6rkysny207t5vr7m5025swh7w0wzra9p0553paprhn8zshqsx2rz64r");

// FUD coin type
const FUD_TYPE = '0x76cb819b01abed502bee8a702b4c2d547532c12f25001c9dea795a5e631c26f1::fud::FUD';

async function sendFUD() {
    const tx = new Transaction();

    // Fetch FUD coins owned by the sender
    const coins = await client.getCoins({owner: keypair.getPublicKey().toSuiAddress(), coinType: FUD_TYPE});

    if (coins.data.length === 0) {
        console.log("No FUD coins found in the wallet.");
        return;
    }

    // Choose the first available FUD coin and split it for the transfer (adjust amount if needed)
    const [coin] = tx.splitCoins(coins.data[0].coinObjectId, [100000000]); 

    tx.transferObjects([coin], '0xb0042cf2c5a16d0a240fc1391d570cd5fe06548f860583f1878c327db70f2a22');

    const result = await client.signAndExecuteTransaction({signer: keypair, transaction: tx});
    await client.waitForTransaction({digest: result.digest});

    console.log("Transaction successful. Digest:", result.digest);
}

sendFUD().then(console.log).catch(console.error);

首先,我检查钱包中是否有一些 $FUD,并将其拆分以进行转账。 tx.transferObjects 将分割币转移到指定地址。

最后需要通过client.signAndExecuteTransaction对交易进行签名,可以通过waitForTransaction等待交易确认交易通过

结论

您已经学会了使用官方 TypeScript SDK 与 Sui 区块链进行交互。您可以利用新获得的知识在 Sui 上进行很多构建,例如构建钱包和机器人。

您可以通过学习如何与 Sui 上的 Move 合约交互来进一步构建更复杂的 dApp

版本聲明 本文轉載於:https://dev.to/goodylili/how-to-use-the-sui-typescript-sdk-2dep?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3