我正在尝试调用我在智能合约中定义的方法。
首先,我创建这个
GetContract
,它接受已编译的合约工件和合约位置。这将创建一个从此函数返回的合约实例。
函数的定义如下 -
const fs = require("fs");
async function GetContract(web3, artifactFilename, contractHash) {
const { abi } = JSON.parse(fs.readFileSync("Contracts/Artifacts/"+artifactFilename+".json"));
// Creating a signing account from a private key
const signer = web3.eth.accounts.privateKeyToAccount(process.env.PRIVATE_KEY);
web3.eth.accounts.wallet.add(signer);
// Creating a Contract instance
const contract = new web3.eth.Contract(
abi,
contractHash,
);
// THIS CALL WORKS HERE, BUT NOT IN MAIN
// contract.methods.set("foo").encodeABI()
return contract
}
module.exports = GetContract
我面临的问题是我可以在函数
contract.methods.set("foo")
中使用创建的合约对象的方法(GetContract()
)。但是一旦我尝试从其他地方(在返回的合约对象上)调用它,它就会抱怨 -
const s = contract.methods.set("foo").encodeABI()
^
TypeError: Cannot read properties of undefined (reading 'set')
at Object.<anonymous>
我没有做任何不同的事情,我像这样从 main 调用它 -
const GetContract = require('./Helpers/GetContract')
const contract = GetContract(web3, "Helloworld", process.env.HELLOWORLD_CONTRACT)
const s = contract.methods.set("foo").encodeABI()
console.log(s)
调试
contract
返回此 -
.
.
.
_methods: {
get: [Function (anonymous)],
'get()': [Function (anonymous)],
'0x6d4ce63c': [Function (anonymous)],
set: [Function (anonymous)],
'set(string)': [Function (anonymous)],
'0x4ed3885e': [Function (anonymous)]
},
.
.
.
所以方法调用肯定存在,但是调试
contract.methods
返回undefined
。
任何人都可以阐明我搞砸的地方吗?
谢谢!
问题似乎在于
GetContract
是一个异步函数。
const fs = require("fs");
function GetContract(web3, artifactFilename, contractHash) {
const { abi } = JSON.parse(fs.readFileSync("Contracts/Artifacts/"+artifactFilename+".json"));
// Creating a signing account from a private key
const signer = web3.eth.accounts.privateKeyToAccount(process.env.PRIVATE_KEY);
web3.eth.accounts.wallet.add(signer);
// Creating a Contract instance
const contract = new web3.eth.Contract(
abi,
contractHash,
);
return contract
}
module.exports = GetContract