name: mvx_sdk_js_contracts description: MultiversX TypeScript/JavaScript SDK 的智能合约操作。
MultiversX SDK-JS 智能合约操作
本技能涵盖 ABI 加载、部署、调用、查询和解析。
ABI 加载
import { Abi } from "@multiversx/sdk-core";
import { promises } from "fs";
// 从文件
const abiJson = await promises.readFile("contract.abi.json", "utf8");
const abi = Abi.create(JSON.parse(abiJson));
// 从 URL
const response = await axios.get("https://example.com/contract.abi.json");
const abi = Abi.create(response.data);
// 手动构建
const abi = Abi.create({
endpoints: [{
name: "add",
inputs: [{ type: "BigUint" }],
outputs: [{ type: "BigUint" }]
}]
});
智能合约控制器
const controller = entrypoint.createSmartContractController(abi);
部署
const bytecode = await promises.readFile("contract.wasm");
const tx = await controller.createTransactionForDeploy(account, nonce, {
bytecode: bytecode,
gasLimit: 60_000_000n,
arguments: [42] // 构造函数参数(使用 ABI 的普通值)
});
const txHash = await entrypoint.sendTransaction(tx);
const outcome = await controller.awaitCompletedDeploy(txHash);
const contractAddress = outcome[0].contractAddress;
合约调用
// 使用 ABI - 使用普通值
const tx = await controller.createTransactionForExecute(account, nonce, {
contract: contractAddress,
function: "add",
arguments: [42],
gasLimit: 5_000_000n
});
// 不使用 ABI - 使用 TypedValue
import { U32Value, BigUintValue } from "@multiversx/sdk-core";
const tx = await controller.createTransactionForExecute(account, nonce, {
contract: contractAddress,
function: "add",
arguments: [new U32Value(42)],
gasLimit: 5_000_000n
});
转账与执行(发送代币到智能合约)
const tx = await controller.createTransactionForExecute(account, nonce, {
contract: contractAddress,
function: "deposit",
arguments: [],
gasLimit: 10_000_000n,
nativeTransferAmount: 1_000_000_000_000_000_000n, // 1 EGLD
tokenTransfers: [
TokenTransfer.fungibleFromBigInteger("TOKEN-abc123", 1000n)
]
});
VM 查询(只读)
const controller = entrypoint.createSmartContractController(abi);
const result = await controller.queryContract({
contract: contractAddress,
function: "getSum",
arguments: []
});
// 解析输出(使用 ABI)
const sum = result[0]; // 自动类型化
升级
const newBytecode = await promises.readFile("contract_v2.wasm");
const tx = await controller.createTransactionForUpgrade(account, nonce, {
contract: contractAddress,
bytecode: newBytecode,
gasLimit: 60_000_000n,
arguments: []
});
RelayedV3 合约调用
const tx = await controller.createTransactionForExecute(account, nonce, {
contract: contractAddress,
function: "endpoint",
arguments: [],
gasLimit: 5_050_000n, // 为 relayed 增加 50,000
relayer: relayerAddress
});
tx.relayerSignature = await relayer.signTransaction(tx);
最佳实践
- 始终使用 ABI:当可用时,以确保类型安全
- 气体估计:开始时设置高值,后续优化
- 先模拟:在实际调用前使用
simulateTransaction() - 解析结果:使用
awaitCompletedExecute()获取返回值