Solidity
從 NodeJS 應用程序中的另一個契約導入契約
我在我的 NodeJS 應用程序中使用一個函式來部署契約。使用者輸入他希望部署的合約,應用程序就會部署它。應用程序的結構是
. ├── app │ ├── models │ │ └── user.js │ └── routes.js ├── cert.pem ├── config │ ├── auth.js │ ├── database.js │ └── passport.js ├── contracts │ ├── Registry.sol │ ├── TrustEntity.sol │ └── User.sol ├── key.pem ├── modules │ ├── contracts.js │ └── helpers.js
TrustEntity.sol 是
pragma solidity ^0.4.11; import "./User.sol"; contract TrustEntity { address owner; address registry; address[] pendingRequests; function pushPending(address requester) { pendingRequests.push(requester); } }
和 User.sol 是
pragma solidity ^0.4.11; import "./TrustEntity.sol"; contract User { // State variables TrustEntity trustEntity; address owner = msg.sender; bool verified = false; uint creationTime = now; uint level = 0; address[] public pendingRequests; // Set trustEntity's deployed contract address function User(address _trustEntity) { trustEntity = TrustEntity(_trustEntity); } function requestValidation() { trustEntity.pushPending(owner); } }
最後,部署函式的相關部分是
function deploy(contractName, publicAddress, _gas) { // Get the contract code from contracts const input = fs.readFileSync('contracts/' + contractName + '.sol').toString(); const output = solc.compile(input); // The trailing ':' is needed otherwise it crashes const bytecode = output.contracts[':' + contractName].bytecode; const abi = JSON.parse(output.contracts[':' + contractName].interface); console.log(abi[0].inputs[0]); const contract = web3.eth.contract(abi); console.log("Contract:" + contract); const contractInstance = contract.new({ . . . }
當我嘗試它時,返回以下錯誤
{ contracts: {}, errors: [ ':2:1: ParserError: Source "User.sol" not found: File not supplied initially.\nimport "./User.sol";\n^------------------^\n' ], sourceList: [ '' ], sources: {} } TypeError: Cannot read property 'bytecode' of undefined
即使文件說(如預期的那樣)
.
指的是目前目錄。具體來說,他們說:“要從x
與目前文件相同的目錄導入文件,請使用import "./x" as x;
”。此外,它在 Remix 中執行良好,所以我不確定錯誤在哪裡。
您需要將每個合約作為字元串導入,然後將它們全部傳遞給solidity https://github.com/ethereum/solc-js#from-version-016
這對我有用:
fs.readFile(fullFileName, 'utf8', (err, data) => { const compiled = solc.compile(data); const bytecode = compiled.contracts[':' + name].bytecode const abi = JSON.parse(compiled.contracts[':' + name].interface) ... const contractData = '0x' + bytecode const rawTx = { nonce: nonceHex, gasPrice: gasPriceHex, gasLimit: gasLimitHex, data: contractData, from: mainAccount }; const tx = new EthTx(rawTx) tx.sign(new Buffer(pKey, 'hex')) const txHex = tx.serialize().toString('hex') web3.eth.sendSignedTransaction(`0x${txHex}`).on('receipt', (receipt) => { ...