Web3js
Truffle 測試錯誤:無法創建 Vault 實例;地址沒有程式碼
我正在嘗試使用 Ganache 在 Truffle 中進行一個簡單的測試,在其中我從智能合約實例中呼叫一個函式。該組件將創建一個 Vault 並將其地址返回給我。
我的松露測試執行以下操作:
const VaultFactory = artifacts.require("./VaultFactory"); const Vault = artifacts.require("./Vault"); contract('VaultFactory', async () => { it("Should create a new Vault", async () => { let VaultFactoryInstance = await VaultFactory.deploy(); let VaultAddress = await VaultFactoryInstance.CreateVaultContract.call(); let VaultInstance = await Vault.at(VaultAddress); }); });
VaultFactory.sol
創建 Vault的程式碼執行以下操作(Vault 的建構子為空):function CreateVaultContract () public returns(address) { Vault newVault = new Vault(); emit VaultCreation(msg.sender, newVault, VaultState.Created); return address(newVault); }
我得到的
VaultAdress
不是空的,但是,當我嘗試獲取時VaultInstance
,它給了我以下錯誤:Uncaught Error: Cannot create instance of Vault; no code at address 0xed41bb9a56dad9b9d0901400f0a8de72d3cf1854
我試著做 a
web3.eth.getCode(VaultAddress);
看看我是否有任何程式碼,但它返回 me0x0
。因此,我的
VaultFactory
契約似乎已部署,並且看起來像是創建了一個Vault
. 但由於某種原因,我無法獲得它的實例。知道為什麼嗎?
我終於設法得到了一個可行的解決方案(儘管我不確定它是否是最好的)。
const VaultFactory = artifacts.require("./VaultFactory"); const Vault = artifacts.require("./Vault"); contract('VaultFactory', async () => { it("Should create a new Vault", async () => { let VaultFactoryInstance = await VaultFactory.deploy(); let VaultReceipt = await VaultFactoryInstance.CreateVaultContract(); //This returns the address of the newly created Vault let VaultAddress = VaultReceipt.logs[0].address; let VaultInstance = await Vault.at(VaultAddress); }); });
這樣,我可以獲取我的 Vault 地址並獲取它的實例。然後我嘗試呼叫一個函式,它完美地工作!
讓 VaultAddress = 等待 VaultFactoryInstance.CreateVaultContract.call();
應該:
讓 VaultAddress = 等待 VaultFactoryInstance.CreateVaultContract();