了解 PTB,以及如何使用 SDK 发起交易
如果你是初学者,强烈建议看下前几节内容:
入门 Sui Move 开发:2. 常用命令、编写并发布 Hello World 合约
入门 Sui Move 开发:3. Sui Move 语法和设计模式
入门 Sui Move 开发:4. Sui Move 中集合、对象、泛型、动态字段
入门 Sui Move 开发:5. 发布同质化代币 — NFT
PTB
全称:Programmable Transaction Blocks
,用来执行交易,交易里可以包含多个操作。
原子操作,如果在交易里有多个操作,一个失败则全部都会执行失败。
可以使用命令行或 SDK
两种方式来使用 PTB
。
通过执行 sui client ptb -h
命令,查看所有 PTB
提供的方法。
Usage: sui client ptb [OPTIONS]
Options:
--assign <NAME> <VALUE>
Assign a value to a variable name to use later in the PTB.
--dry-run
Perform a dry run of the PTB instead of executing it.
--dev-inspect
Perform a dev-inspect of the PTB instead of executing it.
--gas-coin <ID>
The object ID of the gas coin to use. If not specified, it will try to use the first gas coin that it finds that has at least the requested
gas-budget balance.
--gas-budget <MIST>
An optional gas budget for this PTB (in MIST). If gas budget is not provided, the tool will first perform a dry run to estimate the gas cost,
and then it will execute the transaction. Please note that this incurs a small cost in performance due to the additional dry run call.
--make-move-vec <TYPE> <[VALUES]>
Given n-values of the same type, it constructs a vector. For non objects or an empty vector, the type tag must be specified.
--merge-coins <INTO_COIN> <[COIN OBJECTS]>
Merge N coins into the provided coin.
--move-call <PACKAGE::MODULE::FUNCTION> <TYPE_ARGS> <FUNCTION_ARGS>
Make a move call to a function.
--split-coins <COIN> <[AMOUNT]>
Split the coin into N coins as per the given array of amounts.
--transfer-objects <[OBJECTS]> <TO>
Transfer objects to the specified address.
--publish <MOVE_PACKAGE_PATH>
Publish the Move package. It takes as input the folder where the package exists.
--upgrade <MOVE_PACKAGE_PATH>
Upgrade the Move package. It takes as input the folder where the package exists.
--preview
Preview the list of PTB transactions instead of executing them.
--serialize-unsigned-transaction
Instead of executing the transaction, serialize the bcs bytes of the unsigned transaction data using base64 encoding.
--serialize-signed-transaction
Instead of executing the transaction, serialize the bcs bytes of the signed transaction data using base64 encoding.
--summary
Show only a short summary (digest, execution status, gas cost). Do not use this flag when you need all the transaction data and the execution
effects.
--warn-shadows
Enable shadow warning when the same variable name is declared multiple times. Off by default.
--json
Return command outputs in json format.
-h, --help
Print help (see more with '--help')
mkdir sdk_demo // 创建目录
cd sdk_demo // 切换当前命令执行目录
npm init // 初始化 npm,type 选择 module,其他默认
npm i @mysten/sui // 安装 sui sdk
import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
const wallet = Ed25519Keypair.generate(); // 只有私钥,无助记词
// 钱包地址
console.log(`toSuiAddress = ${wallet.toSuiAddress()}`);
// 钱包私钥
const secretKey = wallet.getSecretKey();
console.log(`getSecretKey = ${secretKey}`);
const addressFromPrivatekey = Ed25519Keypair.fromSecretKey(secretKey);
const addressFromMnemonic = Ed25519Keypair.deriveKeypair(mnemonicStr);
使用 SuiClient
对象来和 RCP
进行交互,内置了大多数 RPC
函数。
// 创建一个 SuiClient 实例对象
import { getFullnodeUrl, SuiClient } from "@mysten/sui/client";
const suiClient = new SuiClient({
url: getFullnodeUrl('testnet'), // url 参数定义要访问的是什么网络
});
如果内置函数不满足,可以通过 cal
方法发起请求。
suiClient.call("method_name", [params]);
在内置方法中有一些方法支持分页请求。这些方法的返回值包含:
// 请求第一页,设置只返回 2 条,方便测试
let allCoins = await suiClient.getAllCoins({
owner: MY_ADDRESS,
limit: 2,
});
// 如果有下一页数据,继续发起请求
let allCoins_2 = allCoins.hasNextPage && await suiClient.getAllCoins({
owner: MY_ADDRESS,
cursor: allCoins.nextCursor,
});
构建一个给某地址发送 Sui
的交易。
import { Transaction } from "@mysten/sui/transactions";
// 创建一个交易对象
const tx = new Transaction();
// 拆分出来固定数量的 sui
const coin = tx.splitCoins(tx.gas, [1000]);
// 转账对象,参数:需要发送的对象,接收地址
tx.transferObjects([coin], 'to_address');
构建一个给两个地址发送 Sui
的交易,和上面类似,只需要
const tx = new Transaction();
// 构建交易 发送 sui
// 拆分多个数量的 coin
const coins = tx.splitCoins(tx.gas, [45000, 60000]);
// 转账对象,参数:需要发送的对象,接收地址
tx.transferObjects([coins[0]], ADDRESS_A8);
tx.transferObjects([coins[1]], "0x511d2365b6d2e38cdfb095f2ef7273e92d960643d9fd59b6b2d16344bae8c8e2");
上面定义好了交易的内容,接下来调用 signAndExecuteTransaction
方法实现签名并执行交易。
// 执行交易
const result = await suiClient.signAndExecuteTransaction({
transaction: tx,
signer: wallet,
requestType: 'WaitForLocalExecution',
options: {
showEffects: true,
}
});
console.log("result === ");
console.log(result);
交易已经发送了,需要查询交易的结果。就需要 waitForTransaction
方法来查询交易的结果,参数是执行交易返回的 digest
的值。
// 查询交易结果,参数交易的 hash
const transaction = await suiClient.waitForTransaction({
// digest: result.digest, // tx 的hash
digest: "CzDX7QfFYQKwBeVc9PaTUWJTefvUNv8WziDX1ExHEDGs",
options: {
showEffects: true,
}
});
console.log("transaction === ");
console.log(transaction);
tx.gas
Sui coin splitCoins(coin, [amount])
拆分币种mergeCoins(coinA, coinB)
将 coinB
合并到 coinA
中transferObjects(objects, address)
转账对象到指定地址moveCall({target, arguments, typeArguments})
调用合约的方法
例子:tx.moveCall({ target: '0x2::devnet_nft::mint', arguments: \[tx.pure.string(name), tx.pure.string(description), tx.pure.string(image)] })
使用 交易意图 发送代币
tx.transferObjects(
[
coinWithBalance({ balance: 1000 }), // 发送 sui
coinWithBalance({ balance: 120000, type: '0xd172ea4643dfe46a4130a75dfcd50cf042fe794cc5e14fa746b48bd702e1edfb::greyhaofaucet::GREYHAOFAUCET' }), // type 为发送的 coin 的 type
],
to_address, //接收地址
);
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!