Contract-Development
使用 openzeppelin-test-environment 測試可升級合約
openzeppelin-test-environment
是一個相當新的包,它沒有說明如何初始化可升級合約https://github.com/OpenZeppelin/openzeppelin-test-environment
只是上面連結中的一個基本範例:
const { accounts, contract } = require('@openzeppelin/test-environment'); const [ owner ] = accounts; const { expect } = require('chai'); const MyContract = contract.fromArtifact('MyContract'); // Loads a compiled contract describe('MyContract', function () { it('deployer is owner', async function () { const myContract = await MyContract.new({ from: owner }); expect(await myContract.owner()).to.equal(owner); }); });
如何添加沒有建構子但
initialize
方法的可升級合約?
怎麼用
deployProxy
?// migrations/NN_deploy_upgradeable_box.js const { deployProxy } = require('@openzeppelin/truffle-upgrades'); const Box = artifacts.require('Box'); module.exports = async function (deployer) { const instance = await deployProxy(Box, [42], { deployer }); console.log('Deployed', instance.address); };
要初始化合約,您必須按照OpenZeppelin-upgrades 官方文件中的說明進行部署。
如果你使用的是安全帽,你應該有:
const { accounts, contract } = require('@openzeppelin/test-environment'); const [ owner ] = accounts; const { expect } = require('chai'); const { ethers, upgrades } = require("hardhat"); describe('MyContract', function () { it('deployer is owner', async function () { const myContract = await ethers.getContractFactory('MyContract'); const mycontract = await upgrades.deployProxy(myContract, [{ from: owner}]); expect(await mycontract.owner()).to.equal(owner); }); });
如果您使用的是Truffle,您應該擁有:
const { accounts, contract } = require('@openzeppelin/test-environment'); const [ owner ] = accounts; const { expect } = require('chai'); const { deployProxy } = require('@openzeppelin/truffle-upgrades'); describe('MyContract', function () { it('deployer is owner', async function () { const myContract = artifacts.require('MyContract'); const mycontract = await deployProxy(myContract, [{ from: owner}]); expect(await mycontract.owner()).to.equal(owner); }); });