在 web3js 中,具有空方法的新合约实例



我有一个创建有效solidity文件的函数,它的名字是"makeContract"。我认为一开始最好不要发布整个功能,因为它有 97 行,但如果有人问我发布。它将JSON转换为SOLIDITY文件。其中最重要的是下面。合约变量是一个字符串,其中包含已经稳固的文本。

if (!existsSync(__dirname + '/temp')) await exec('mkdir '+__dirname + '/temp/')
writeFileSync(__dirname + '/temp/'+name+'.sol', contract, 'utf8')

我有另一个函数,我称之为 compileContract 来编译合约,所以它会生成一个 .ABI 文件和另一个 ..BIN。

compileContract: async () => {
const file = readdirSync(__dirname + '/temp').filter(file => file.includes('.sol'))
await exec('solcjs --abi --bin '+ __dirname + '/temp/' + file[0] + ' -o ' + __dirname + '/temp/')
}

我仍然有一个读取 .ABI 文件并以 UTF8 格式返回。

readCompiledContract: (nameContract, extension) =>  {
return readFileSync(__dirname+'/temp/'+readdirSync(__dirname+'/temp/')
.find(file=>file.includes(nameContract+'.'+extension)), 'utf8')
}

我仍然有一个我称之为垃圾收集器的函数,它只是删除临时文件夹,该文件夹用于放置.sol,.abi和.bin文件。

garbageCollector: async () => {
if (existsSync(__dirname + '/temp')) await exec('rm -rf '+__dirname+'/temp')
}

我使用下面的代码使用已经显示的函数创建一个合约实例。评论首先是英文,然后是葡萄牙语。

router.post('/create', async (req, res) => {
const { id, name, data, groupings } = req.body
// create a JSON from attributes received from body
// cria um JSON a partir dos atributos recebidos do body
const contrBody = {
name: name,
data: data,
groupings: groupings
}
try {
// rescues the user searched by ID, selects ethAddress, medicalRegisterAddress and password
// resgata o usuario procurado pelo ID, seleciona ainda ethAddress, medicalRegisterAddress e password
const user = await UserRoot.findById(id).select('+ethAddress medicalRegister password')
// effectively transforms JSON created from body attributes into a solidity file
// transforma efetivamente o JSON criado a partir dos atributos de body em um prontuário médico (arquivo solidity)
await medicalRecordContract.makeContract(contrBody)
// function that compiles the smart contract created, (see file) - no solc was used for nodejs because it has bugs
// função que compila o contrato inteligente criado, (ver arquivo) - não foi usado a solc para nodejs porque apresenta bugs
await medicalRecordContract.compileContract()
// get the ABI through the read function (see file)
// obtem a ABI por meio da função de leitura (ver arquivo)
let abi = medicalRecordContract.readCompiledContract(name, 'abi')
// create a contract by passing ABI as a parameter (see documentation https://web3js.readthedocs.io/en/v1.2.4/web3-eth-contract.html#new-contract)
// cria um contrato passando a ABI como parâmetro (ver a documentação https://web3js.readthedocs.io/en/v1.2.4/web3-eth-contract.html#new-contract)
let contract = new web3.eth.Contract(JSON.parse(abi))
return res.send({ contract: contract }) // <-- HERE <--

如您所见,上面的代码引用了一个 REST API,然后我发布了您在上面的代码中看到的相同帖子,它应该返回一个合约实例。我正在使用失眠程序。由于完整的 JSON 有 390 行,我首先放最后一个,只是让我放完整的代码或特定部分。查找"方法"属性,我用注释标记了它,以便于查找。

"transactionBlockTimeout": 50,
"transactionConfirmationBlocks": 24,
"transactionPollingTimeout": 750,
"defaultAccount": null,
"defaultBlock": "latest",
//below the empty Methods attribute
"methods": {},
"events": {},
"_address": null,
"_jsonInterface": [
{
"constant": true,
"inputs": [],
"name": "getaltura",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function",
"signature": "0xec1e5e46"
},
{
"constant": true,
"inputs": [],
"name": "getcircunferencia",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function",
"signature": "0xd47dae09"
},
{
"constant": true,
"inputs": [],
"name": "getfumante",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "view",
"type": "function",
"signature": "0x5655b1b5"
},
{
"constant": true,
"inputs": [],
"name": "getidade",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function",
"signature": "0xd193ad65"
},
{
"constant": true,
"inputs": [],
"name": "getpeso",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function",
"signature": "0x81cbdaeb"
},
{
"constant": true,
"inputs": [],
"name": "getsaude",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function",
"signature": "0xb68059b2"
},
{
"constant": false,
"inputs": [
{
"internalType": "uint256",
"name": "altura",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "peso",
"type": "uint256"
}
],
"name": "setDados",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function",
"signature": "0xe892da6b"
},
{
"constant": false,
"inputs": [
{
"internalType": "uint256",
"name": "circunferencia",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "idade",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "saude",
"type": "uint256"
},
{
"internalType": "bool",
"name": "fumante",
"type": "bool"
}
],
"name": "setDesempenhoVida",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function",
"signature": "0x79cc1968"
}
]
}
}

如您所见,"方法"属性为空。我想指出的是,合约实例的其余部分显然是正常的,我已经在其他情况下测试了这种执行合约实例的相同方式,并且已经成功了。

这是发起eth.contract实例的智能合约。

pragma solidity ^0.5.11;
contract ProntuarioHistorico2 {
struct Dados {
uint altura;
uint peso;
}

struct DesempenhoVida {
uint circunferencia;
uint idade;
uint saude;
bool fumante;
}
mapping (address => Dados) register_Dados;
mapping (address => DesempenhoVida) register_DesempenhoVida;
function setDados(uint altura, uint peso) public {
register_Dados[msg.sender] = Dados({
altura: altura,
peso: peso
});
}
function getaltura() public view returns(uint) {
return register_Dados[msg.sender].altura;
}
function getpeso() public view returns(uint) {
return register_Dados[msg.sender].peso;
}
function setDesempenhoVida(uint circunferencia, uint idade, uint saude, bool fumante) public {
register_DesempenhoVida[msg.sender] = DesempenhoVida({
circunferencia: circunferencia,
idade: idade,
saude: saude,
fumante: fumante
});
}
function getcircunferencia() public view returns(uint) {
return register_DesempenhoVida[msg.sender].circunferencia;
}
function getidade() public view returns(uint) {
return register_DesempenhoVida[msg.sender].idade;
}
function getsaude() public view returns(uint) {
return register_DesempenhoVida[msg.sender].saude;
}
function getfumante() public view returns(bool) {
return register_DesempenhoVida[msg.sender].fumante;
}

}

我知道这是一个大问题,这可能是艰苦的工作,但我非常感谢任何帮助,如果有人知道如何解决这个问题或我做错了什么,请说出来。

您的代码在我的计算机上运行良好,methods字段已正确构建。尝试升级您的软件包?

我正在使用版本0.5.13solcjs和版本1.2.4的 web3 .

最新更新