Solidity
使用 web3.js 1.2.6 呼叫視圖函式
我正在嘗試呼叫僅查看功能,不確定這是否是正確的程序。在結果中獲得成功,但結果格式不同。這是錯的嗎?
const NODE_ADDRESS = config.web3Provider; const sourceCode = fs.readFileSync('path_to_contract', 'utf8').toString(); const compiledCode = compiler.compile(sourceCode, 1).contracts[':ContractName'] const abi = JSON.parse(compiledCode.interface); async function send(web3, transaction) { while (true) { try { const options = { to: transaction._parent._address, data: transaction.encodeABI(), gas: 210000, gasPrice: 10000000000, }; const receipt = await web3.eth.call(options); return receipt; } catch (error) { return error } } } async function run() { try { const web3 = new Web3(NODE_ADDRESS); const contract = new web3.eth.Contract(abi, contractAddr); const transaction = contract.methods.getBuyerInfo(); const receipt = await send(web3, transaction); console.log(JSON.stringify(receipt, null, 4)); if (web3.currentProvider.constructor.name == "WebsocketProvider") web3.currentProvider.connection.close(); if (receipt) { next(null, receipt) } } catch (error) { next(error, null) } } run();
結果 :-
{ "status": 1, "message": "Success", "data": "0x0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000f61343ef22bbccc7221dcda85c5a69219ea00c2b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c50756e656574204b756d61720000000000000000000000000000000000000000" }
這行得通!
const contractAddr = "0x......" const sourceCode = fs.readFileSync('path_to_contract', 'utf8').toString(); const compiledCode = compiler.compile(sourceCode, 1).contracts[':ContractName'] const abi = JSON.parse(compiledCode.interface); const contractInstance = new web3.eth.Contract(abi , contractAddr); contractInstance.methods.functionName().call((err, result) => { if (err){ next(err, null) } else { next (null, result) } })
call
不返回收據而是函式的實際值,因為它在節點上本地執行。但是返回的對像是一個承諾,所以你需要
await
它。