关于 near-kit
near-kit 是通过类 fetch API 与 NEAR Protocol 交互的 TypeScript 库,适用于开发 NEAR 应用。它涵盖只读查询、签名交易、类型安全合约接口、钱包集成和沙盒测试。
主要功能
- 01只读查询合约与账户
- 02签名调用、转账和交易
- 03类型安全的合约接口
- 04密钥库与密钥工具
- 05钱包和 React 集成
- 06沙盒测试支持
适用场景
- 01读取合约状态和账户余额
- 02发送 NEAR 并组合交易操作
- 03构建类型安全的合约集成
- 04使用 NEAR 沙盒测试应用
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ near/ agent-skills --skill near-kit安装后在 Claude Code 中输入/near-kit确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/keys-and-testing.mdreact.mdtransactions.mdwallets.md详细介绍
near-kit
一个用于 NEAR Protocol 的 TypeScript 库,提供直观、类似 fetch 的 API。
快速开始
import { Near } from "near-kit";
// Read-only (no key needed)
const near = new Near({ network: "testnet" });
const data = await near.view("contract.near", "get_data", { key: "value" });
// With signing capability
const near = new Near({
network: "testnet",
privateKey: "ed25519:...",
defaultSignerId: "alice.testnet",
});
await near.call("contract.near", "method", { arg: "value" });
await near.send("bob.testnet", "1 NEAR");
导入速查表
// Core
import { Near } from "near-kit";
// Keys
import { generateKey, parseSeedPhrase, generateSeedPhrase } from "near-kit";
import { RotatingKeyStore, InMemoryKeyStore } from "near-kit";
import { FileKeyStore } from "near-kit/keys/file";
import { NativeKeyStore } from "near-kit/keys/native";
// Wallet adapters
import { fromHotConnect, fromWalletSelector } from "near-kit";
// NEP-413 verification
import { verifyNep413Signature } from "near-kit";
// Utilities
import { Amount, Gas, isValidAccountId } from "near-kit";
核心操作
查看方法(只读,免费)
const result = await near.view("contract.near", "get_data", { key: "value" });
const balance = await near.getBalance("alice.near");
const exists = await near.accountExists("alice.near");
调用方法(需要签名)
await near.call(
"contract.near",
"method",
{ arg: "value" },
{ gas: "30 Tgas", attachedDeposit: "1 NEAR" },
);
发送 NEAR 代币
await near.send("bob.near", "5 NEAR");
类型安全的合约
import type { Contract } from "near-kit";
type MyContract = Contract<{
view: {
get_balance: (args: { account_id: string }) => Promise<string>;
};
call: {
transfer: (args: { to: string; amount: string }) => Promise<void>;
};
}>;
const contract = near.contract<MyContract>("token.near");
// View (no options needed)
await contract.view.get_balance({ account_id: "alice.near" });
// Call (options as second arg)
await contract.call.transfer(
{ to: "bob.near", amount: "10" },
{ attachedDeposit: "1 yocto" },
);
无类型的合约代理:
const guestbook = near.contract("guestbook.near-examples.testnet");
const total = await guestbook.view.total_messages();
const result = await guestbook.call.add_message(
{ text: "Hello!" },
{ gas: "30 Tgas" },
);
事务构建器
在单个原子事务中串联多个操作:
const result = await near
.transaction("alice.near")
.functionCall("counter.near", "increment", {}, { gas: "30 Tgas" })
.transfer("counter.near", "0.001 NEAR")
.send();
有关所有事务操作和元事务,请参阅 references/transactions.md
配置
后端/脚本
// Direct private key
const near = new Near({
network: "testnet",
privateKey: "ed25519:...",
defaultSignerId: "alice.testnet",
});
// File-based keystore
import { FileKeyStore } from "near-kit/keys/file";
const near = new Near({
network: "testnet",
keyStore: new FileKeyStore("~/.near-credentials", "testnet"),
});
// High-throughput with rotating keys
import { RotatingKeyStore } from "near-kit";
const near = new Near({
network: "mainnet",
keyStore: new RotatingKeyStore({
"bot.near": ["ed25519:key1...", "ed25519:key2...", "ed25519:key3..."],
}),
});
有关所有密钥存储和实用工具,请参阅 references/keys-and-testing.md
浏览器钱包
import { NearConnector } from "@hot-labs/near-connect";
import { Near, fromHotConnect } from "near-kit";
const connector = new NearConnector({ network: "mainnet" });
connector.on("wallet:signIn", async (event) => {
const near = new Near({
network: "mainnet",
wallet: fromHotConnect(connector),
});
await near.call("contract.near", "method", { arg: "value" });
});
connector.connect();
有关 HOT Connect 和 Wallet Selector 集成,请参阅 references/wallets.md
React 绑定(@near-kit/react)
import { NearProvider, useNear, useView, useCall } from "@near-kit/react";
function App() {
return (
<NearProvider config={{ network: "testnet" }}>
<Counter />
</NearProvider>
);
}
function Counter() {
const { data: count, isLoading } = useView<{}, number>({
contractId: "counter.testnet",
method: "get_count",
});
const { mutate: increment, isPending } = useCall({
contractId: "counter.testnet",
method: "increment",
});
if (isLoading) return <div>Loading...</div>;
return (
<button onClick={() => increment({})} disabled={isPending}>
Count: {count}
</button>
);
}
有关所有 React 钩子、React Query/SWR 集成和 SSR 模式,请参阅 references/react.md
使用 Sandbox 测试
import { Near } from "near-kit";
import { Sandbox } from "near-kit/sandbox";
const sandbox = await Sandbox.start();
const near = new Near({ network: sandbox });
const testAccount = `test-${Date.now()}.${sandbox.rootAccount.id}`;
await near
.transaction(sandbox.rootAccount.id)
.createAccount(testAccount)
.transfer(testAccount, "10 NEAR")
.send();
await sandbox.stop();
有关 Sandbox 模式和 Vitest 集成,请参阅 references/keys-and-testing.md
错误处理
import {
InsufficientBalanceError,
FunctionCallError,
NetworkError,
TimeoutError,
} from "near-kit";
try {
await near.call("contract.near", "method", {});
} catch (error) {
if (error instanceof InsufficientBalanceError) {
console.log(`Need ${error.required}, have ${error.available}`);
} else if (error instanceof FunctionCallError) {
console.log(`Panic: ${error.panic}`, `Logs: ${error.logs}`);
}
}
单位格式化
所有金额均接受人类可读的格式:
"10 NEAR"; // 10 NEAR
"10"; // 10 NEAR
10; // 10 NEAR
("30 Tgas"); // 30 trillion gas units
编程式格式化:
import { Amount, Gas } from "near-kit";
Amount.NEAR(0.1);
Amount.yocto(1000n);
Amount.parse("5 NEAR");
Gas.parse("30 Tgas");
密钥实用工具
import {
generateKey,
generateSeedPhrase,
parseSeedPhrase,
isValidAccountId,
} from "near-kit";
// Generate new keypair
const key = generateKey();
// key.publicKey, key.secretKey
// generateSeedPhrase() returns a string (just the phrase)
const seedPhrase = generateSeedPhrase();
// "word1 word2 word3 ... word12"
// parseSeedPhrase() returns a KeyPair-like object
const keyPair = parseSeedPhrase("word1 word2 ... word12");
// keyPair.publicKey, keyPair.secretKey
// Validation
isValidAccountId("alice.near"); // true
NEP-413 验证
import { Near, verifyNep413Signature } from "near-kit";
const near = new Near({ network: "testnet" });
const isValid = await verifyNep413Signature(
signedMessage,
{ message: "log me in", recipient: "myapp.com", nonce: challengeBuffer },
{ near, maxAge: Infinity },
);
参考资料
有关特定主题的详细文档:
- React 绑定 - Provider、钩子、React Query/SWR、SSR/Next.js
- 钱包集成 - HOT Connect、Wallet Selector、通用模式
- 事务构建器 - 所有操作、元事务(NEP-366)
- 密钥和测试 - 密钥存储、实用工具、Sandbox、NEP-413 签名
上游与来源
- near-kit 是一个社区库 — r-near/near-kit(npm:
near-kit、@near-kit/react;当前版本为 ^0.20.x) - 官方文档未涵盖 near-kit;在依赖此处列出的确切签名之前,请对照仓库 README 验证新 API
- 有关纯 near-api-js 和 RPC 的详情,请参阅官方文档:docs.near.org/tools/near-api
- 对于新应用,Wallet Selector 已由 near-connect connector 取代 — 请参阅 references/wallets.md
评论
支持 Markdown