使用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
相关产品推荐
相关产品推荐

