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

使用JavaScript调用Near Protocol合约时遭遇弃用错误求助

解决NEAR合约调用的废弃API错误

问题原因

错误提示明确说明旧版Account.viewFunction(contractId, methodName, args, options)参数格式已废弃,需改用传入单个ViewFunctionCallOptions对象的形式。同时你的代码里误用了viewFunctionV1,且错误地将参数转为JSON字符串(NEAR API会自动序列化参数)。

方案一:使用已创建的Contract实例调用(推荐)

你已经初始化了Contract对象,直接调用其定义的view方法即可,这是最简洁的方式:

const nearAPI = require("near-api-js");
async function contractFunctionCall() {
    const {keyStores, KeyPair, connect} = nearAPI;
    const myKeyStore = new keyStores.InMemoryKeyStore();
    const PRIVATE_KEY = "the private key of this dev account";

    const keyPair = KeyPair.fromString(PRIVATE_KEY);
    await myKeyStore.setKey("testnet", "dev-1673623139694-96382653233746", keyPair);

    const connectionConfig = {
        networkId: "testnet",
        keyStore: myKeyStore,
        nodeUrl: "https://rpc.testnet.near.org",
        walletUrl: "https://wallet.testnet.near.org",
        helperUrl: "https://helper.testnet.near.org",
        explorerUrl: "https://explorer.testnet.near.org",
    };
    
    const nearConnection = await connect(connectionConfig);
    const account = await nearConnection.account("dev-1673623139694-96382653233746");

    const contract = new nearAPI.Contract(account, "dev-1673623139694-96382653233746", {
        viewMethods: ["get_charge"],
        changeMethods: ["store_charge"]
    });

    // 直接调用Contract实例上的view方法,传入原始对象参数
    const response = await contract.get_charge({key: "key1"});
    console.log(response);
}
contractFunctionCall();

方案二:修正account.viewFunction的调用格式

如果不想用Contract实例,需按照新API要求传入完整的选项对象:

// 替换原代码中的viewFunctionV1调用部分
const response = await account.viewFunction({
    contractId: "dev-1673623139694-96382653233746",
    methodName: "get_charge",
    args: {key: "key1"} // 直接传对象,无需JSON.stringify
});
console.log(response);

关键注意事项

  • 不要手动序列化参数:NEAR API会自动处理参数的JSON序列化,直接传入JavaScript对象即可。
  • 废弃的API不要用:viewFunctionV1是非标准方法,官方推荐使用viewFunction配合选项对象,或使用Contract实例方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:20:30