”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何使用 Sui TypeScript SDK

如何使用 Sui TypeScript SDK

发布于2024-11-03
浏览:412

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]删除
最新教程 更多>
  • 为什么在我的Linux服务器上安装Archive_Zip后,我找不到“ class \” class \'ziparchive \'错误?
    为什么在我的Linux服务器上安装Archive_Zip后,我找不到“ class \” class \'ziparchive \'错误?
    Class 'ZipArchive' Not Found Error While Installing Archive_Zip on Linux ServerSymptom:When attempting to run a script that utilizes the ZipAr...
    编程 发布于2025-05-06
  • Go语言如何动态发现导出包类型?
    Go语言如何动态发现导出包类型?
    与反射软件包中的有限类型的发现能力相反,本文探索了替代方法,探索了在Runruntime。go import( “ FMT” “去/进口商” ) func main(){ pkg,err:= incorter.default()。导入(“ time”) 如果err...
    编程 发布于2025-05-06
  • 如何在Chrome中居中选择框文本?
    如何在Chrome中居中选择框文本?
    选择框的文本对齐:局部chrome-inly-ly-ly-lyly solument 您可能希望将文本中心集中在选择框中,以获取优化的原因或提高可访问性。但是,在CSS中的选择元素中手动添加一个文本 - 对属性可能无法正常工作。初始尝试 state)</option> < op...
    编程 发布于2025-05-06
  • 为什么不````''{margin:0; }`始终删除CSS中的最高边距?
    为什么不````''{margin:0; }`始终删除CSS中的最高边距?
    在CSS 问题:不正确的代码: 全球范围将所有余量重置为零,如提供的代码所建议的,可能会导致意外的副作用。解决特定的保证金问题是更建议的。 例如,在提供的示例中,将以下代码添加到CSS中,将解决余量问题: body H1 { 保证金顶:-40px; } 此方法更精确,避免了由全局保证金重置引...
    编程 发布于2025-05-06
  • 人脸检测失败原因及解决方案:Error -215
    人脸检测失败原因及解决方案:Error -215
    错误处理:解决“ error:((-215)!empty()in Function Multultiscale中的“ openCV 要解决此问题,必须确保提供给HAAR CASCADE XML文件的路径有效。在提供的代码片段中,级联分类器装有硬编码路径,这可能对您的系统不准确。相反,OPENCV提...
    编程 发布于2025-05-06
  • 在Oracle SQL中如何提取下划线前的子字符串?
    在Oracle SQL中如何提取下划线前的子字符串?
    [ 在oracle sql 解决方案: Explanation:SUBSTR function extracts a substring starting from the specified position (0) and continuing for a specified length.IN...
    编程 发布于2025-05-06
  • 用户本地时间格式及时区偏移显示指南
    用户本地时间格式及时区偏移显示指南
    在用户的语言环境格式中显示日期/时间,并使用时间偏移在向最终用户展示日期和时间时,以其localzone and格式显示它们至关重要。这确保了不同地理位置的清晰度和无缝用户体验。以下是使用JavaScript实现此目的的方法。方法:推荐方法是处理客户端的Javascript中的日期/时间格式化和时...
    编程 发布于2025-05-06
  • 如何干净地删除匿名JavaScript事件处理程序?
    如何干净地删除匿名JavaScript事件处理程序?
    删除匿名事件侦听器将匿名事件侦听器添加到元素中会提供灵活性和简单性,但是当要删除它们时,可以构成挑战,而无需替换元素本身就可以替换一个问题。 element? element.addeventlistener(event,function(){/在这里工作/},false); 要解决此问题,请考虑...
    编程 发布于2025-05-06
  • 如何简化PHP中的JSON解析以获取多维阵列?
    如何简化PHP中的JSON解析以获取多维阵列?
    php 试图在PHP中解析JSON数据的JSON可能具有挑战性,尤其是在处理多维数组时。 To simplify the process, it's recommended to parse the JSON as an array rather than an object.To do...
    编程 发布于2025-05-06
  • 如何从2D数组中提取元素?使用另一数组的索引
    如何从2D数组中提取元素?使用另一数组的索引
    Using NumPy Array as Indices for the 2nd Dimension of Another ArrayTo extract specific elements from a 2D array based on indices provided by a second ...
    编程 发布于2025-05-06
  • 如何在其容器中为DIV创建平滑的左右CSS动画?
    如何在其容器中为DIV创建平滑的左右CSS动画?
    通用CSS动画,用于左右运动 ,我们将探索创建一个通用的CSS动画,以向左和右移动DIV,从而到达其容器的边缘。该动画可以应用于具有绝对定位的任何div,无论其未知长度如何。问题:使用左直接导致瞬时消失 更加流畅的解决方案:混合转换和左 [并实现平稳的,线性的运动,我们介绍了线性的转换。这...
    编程 发布于2025-05-06
  • 如何从PHP中的数组中提取随机元素?
    如何从PHP中的数组中提取随机元素?
    从阵列中的随机选择,可以轻松从数组中获取随机项目。考虑以下数组:; 从此数组中检索一个随机项目,利用array_rand( array_rand()函数从数组返回一个随机键。通过将$项目数组索引使用此键,我们可以从数组中访问一个随机元素。这种方法为选择随机项目提供了一种直接且可靠的方法。
    编程 发布于2025-05-06
  • 为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    The Mystery of "Broken" Two-Phase Template Instantiation in Microsoft Visual C Problem Statement:Users commonly express concerns that Micro...
    编程 发布于2025-05-06
  • 如何使用node-mysql在单个查询中执行多个SQL语句?
    如何使用node-mysql在单个查询中执行多个SQL语句?
    Multi-Statement Query Support in Node-MySQLIn Node.js, the question arises when executing multiple SQL statements in a single query using the node-mys...
    编程 发布于2025-05-06
  • 版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    在时间戳列上使用current_timestamp或MySQL版本中的current_timestamp或在5.6.5 此限制源于遗留实现的关注,这些限制需要对当前的_timestamp功能进行特定的实现。 创建表`foo`( `Productid` int(10)unsigned not n...
    编程 发布于2025-05-06

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3