我有一个智能契约,它依赖于预先部署的ERC-20智能契约,它总是部署到相同的地址(本地测试网络以及公共测试网络中)。
我想将模拟智能契约的地址重写为与该地址相同的地址,但是文档没有提供任何洞察力。
因此,我正在试验的智能契约示例是文档中的基本示例:
pragma solidity ^0.6.2;
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
}
contract AmIRichAlready {
IERC20 private tokenContract;
uint public richness = 1000000 * 10 ** 18;
constructor (IERC20 _tokenContract) public {
tokenContract = _tokenContract;
}
function check() public view returns (bool) {
uint balance = tokenContract.balanceOf(msg.sender);
return balance > richness;
}
}
测试设置如下:
import { expect, use } from "chai"
import { Contract, utils, Wallet } from "ethers"
import {
deployContract,
deployMockContract,
MockProvider,
solidity,
} from "ethereum-waffle"
import IERC20 from "../build/IERC20.json"
import AmIRichAlready from "../build/AmIRichAlready.json"
use(solidity)
describe("Am I Rich Already", () => {
let mockERC20: Contract
let contract: Contract
let wallet: Wallet
beforeEach(async () => {
;[wallet] = new MockProvider().getWallets()
mockERC20 = await deployMockContract(wallet, IERC20.abi)
contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address])
})
})
因此,我想为mockERC20
分配一个特定的地址,以便在该地址调用方法将由模拟智能契约处理。
我试过挖掘源代码,但到目前为止没有任何进展。有没有人知道这是可能的?
发布于 2022-08-05 05:16:04
有两种方法可以做到这一点:
const myFake = await smock.fake('MyContract', {address: ERC-20 token's address})
。可以使用myFake.functionName.returns(returnValue)
设置模拟合同的返回值。这既适用于外部调用(来自以太),也适用于内部调用(来自其他契约)。我强烈建议学习Smock,而不是手动编写模拟合同,这样可以节省大量的时间。发布于 2023-02-23 07:01:28
“硬帽子”允许用户使用"hardhat_setCode“功能在内部完成此操作。
// Deploy the contract you want to replace with
const yourFake = await ethers.getContractFactory("YourFake")
const yourFakeContract = await yourFake.deploy(// your args here)
// Get the bytecode for that contract using "eth_getCode"
const yourFakeBytecode = await hre.network.provider.send("eth_getCode", [yourFakeContract.address])
// Replace the bytecode at the target contract address with your bytecode
await hre.network.provider.send("hardhat_setCode", [targetAddress, yourFakeBytecode])
注意:在运行此代码之前,要分叉您想要的块链。
https://ethereum.stackexchange.com/questions/133037
复制相似问题