You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过私钥/公钥获取NEAR WALLET的AccountID?

通过私钥/公钥获取NEAR账户ID的实现方案

核心原理

NEAR链上的访问密钥与账户是绑定关系,通过NEAR RPC节点提供的view_access_key接口,可以反向查询公钥对应的账户ID。以下代码实现了目标网站的核心逻辑:

完整实现代码

const nearApi = require('near-api-js');

// 配置NEAR网络RPC节点,主网用mainnet,测试网替换为https://rpc.testnet.near.org
const RPC_ENDPOINT = 'https://rpc.mainnet.near.org';

// 从私钥提取公钥
function extractPublicKey(privateKey) {
  const keypair = nearApi.KeyPair.fromString(privateKey);
  return keypair.getPublicKey().toString();
}

// 通过公钥查询绑定的账户ID
async function lookupAccountId(publicKey) {
  const rpcProvider = new nearApi.providers.JsonRpcProvider(RPC_ENDPOINT);
  
  try {
    // 调用NEAR RPC接口查询公钥对应的访问密钥信息
    const accessKeyData = await rpcProvider.viewAccessKey(publicKey);
    return accessKeyData.account_id;
  } catch (err) {
    // 公钥未绑定任何账户时返回null
    if (err.type === 'AccessKeyNotFound') {
      return null;
    }
    throw err;
  }
}

// 示例执行
(async () => {
  // 替换为你的目标私钥
  const targetPrivateKey = '3by8kdJoJHu7uUkKfoaLJ2Dp1q1TigeWMGpHu9UGXsWdREqPcshCM223kWadmrMKpV9AsWG5wL9F9hZzjHSRFXud';
  
  const publicKey = extractPublicKey(targetPrivateKey);
  console.log('提取到的公钥:', publicKey);
  
  const accountId = await lookupAccountId(publicKey);
  if (accountId) {
    console.log('匹配的账户ID:', accountId);
  } else {
    console.log('未找到绑定该公钥的NEAR账户');
  }
})();

使用说明

  1. 安装依赖:执行npm install near-api-js完成依赖包安装
  2. 切换网络:如果需要查询测试网账户,修改RPC_ENDPOINT为测试网节点地址
  3. 错误处理:代码已处理公钥未绑定账户的场景,其他异常会直接抛出便于排查

内容的提问来源于stack exchange,提问作者Eosio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:57:24