hardhat#ethers TypeScript Examples
The following examples show how to use
hardhat#ethers.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: deploy.ts From pawnft with GNU General Public License v3.0 | 6 votes |
// Hardhat
async function main(): Promise<void> {
// Collect deployer
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// Deploy PawnBank
const PawnBank = await ethers.getContractFactory("PawnBank");
const pawnbank = await PawnBank.deploy();
console.log("Deployed PawnBank address:", pawnbank.address);
}
Example #2
Source File: deploy.ts From BarnBridge-Barn with Apache License 2.0 | 6 votes |
export async function deployDiamond (diamondArtifactName: string, facets: Array<Contract>, owner: string): Promise<Contract> {
const diamondCut = [];
for (const facet of facets) {
diamondCut.push([
facet.address,
diamond.FacetCutAction.Add,
diamond.getSelectors(facet),
]);
}
const diamondFactory: ContractFactory = await ethers.getContractFactory(diamondArtifactName);
const deployedDiamond: Contract = await diamondFactory.deploy(diamondCut, owner);
await deployedDiamond.deployed();
return deployedDiamond;
}
Example #3
Source File: helpers.ts From BarnBridge-YieldFarming with Apache License 2.0 | 6 votes |
//
// export async function getLatestBlockTimestamp(): Promise<number> {
// return parseInt((await getLatestBlock()).timestamp);
// }
export async function setNextBlockTimestamp(timestamp: number): Promise<void> {
const block = await ethers.provider.send("eth_getBlockByNumber", ["latest", false]);
const currentTs = parseInt(block.timestamp);
const diff = timestamp - currentTs;
await ethers.provider.send("evm_increaseTime", [diff]);
}
Example #4
Source File: deploy.ts From aegis with MIT License | 6 votes |
async function main() {
const wethAddress = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2';
const AegisERC20 = await ethers.getContractFactory('AegisERC20');
const aegisERC20 = await AegisERC20.deploy();
await aegisERC20.deployed();
console.log(`Example Aegis ERC20 deployed to ${aegisERC20.address}`);
const SameBlockStrategy = await ethers.getContractFactory('AegisSameBlockStrategy');
const sameBlockStrategy = await SameBlockStrategy.deploy(true, 3600 * 24 * 90); // same block strategy should vest tokens over ~90 days
await sameBlockStrategy.deployed();
const AegisShield = await ethers.getContractFactory('AegisShield');
const aegisShield = await AegisShield.deploy(
[sameBlockStrategy.address], // strategies to use
aegisERC20.address, // address of the token we're protecting
wethAddress, // pair is with wrapped ether
0 // uniswap
);
await aegisShield.deployed();
console.log(`Aegis Shield deployed to ${aegisShield.address}`);
}
Example #5
Source File: calculateEIGasCosts.ts From index-coop-smart-contracts with Apache License 2.0 | 6 votes |
async function getPositionQuotes(
positions: any[],
inputTokenAddress: string,
setAmount: number,
): Promise<any[]> {
const promises = positions.map((position: any) => {
if (
ethers.utils.getAddress(position.component) === ethers.utils.getAddress(inputTokenAddress)
) {
console.log("No swap needed");
return Promise.resolve({ gas: "0", sellAmount: position.unit.mul(setAmount).toString() });
} else {
const params = {
buyToken: position.component,
sellToken: inputTokenAddress,
buyAmount: position.unit.mul(setAmount).toString(),
};
return getQuote(params);
}
});
return await Promise.all(promises);
}
Example #6
Source File: index.ts From nova with GNU Affero General Public License v3.0 | 6 votes |
/** Returns a valid value for a param type. */
export function getValueForParamType(paramType: ParamType) {
const baseType = paramType.baseType;
if (baseType === "array") {
return [];
} else if (baseType === "tuple") {
let obj = {};
for (const subParam of paramType.components) {
obj[subParam.name] = getValueForParamType(subParam);
}
return obj;
} else if (baseType === "address") {
return "0xFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACE";
} else if (baseType === "bool") {
return true;
} else if (baseType.includes("bytes")) {
if (baseType === "bytes") {
return "0x00000000";
}
const numberOfBytes = parseInt(baseType.replace("bytes", ""));
return ethers.utils.hexZeroPad("0x00000000", numberOfBytes);
} else if (baseType.includes("uint")) {
if (baseType === "uint") {
return 1e18;
}
const numberSize = parseInt(baseType.replace("uint", ""));
return Math.min(100000000000, Math.floor(2 ** numberSize / 100));
} else if (baseType.includes("int")) {
if (baseType === "int") {
return 1e18;
}
const numberSize = parseInt(baseType.replace("int", ""));
return Math.min(100000000000, Math.floor(2 ** numberSize / 100));
}
}
Example #7
Source File: fixtures.ts From hypervisor with The Unlicense | 6 votes |
async function uniswapV3Fixture(): Promise<UniswapV3Fixture> {
const factoryFactory = await ethers.getContractFactory('UniswapV3Factory')
const factory = (await factoryFactory.deploy()) as IUniswapV3Factory
const tokenFactory = await ethers.getContractFactory('TestERC20')
const WETH = (await tokenFactory.deploy(BigNumber.from(2).pow(255))) as TestERC20 // TODO: change to real WETH
const routerFactory = await ethers.getContractFactory('SwapRouter')
const router = (await routerFactory.deploy(factory.address, WETH.address)) as ISwapRouter
return { factory, router }
}
Example #8
Source File: helpers.ts From aavegotchi-contracts with MIT License | 6 votes |
export async function fundSigner(
network: any,
address: string,
amount: BigNumberish
) {
await network.provider.request({
method: "hardhat_setBalance",
params: [address, ethers.utils.hexlify(amount)],
});
}
Example #9
Source File: checkFrens.ts From ghst-staking with MIT License | 6 votes |
async function checkFrens() {
const address = "0x46Db73fC5fD98c9dAF2d79f8653398d2D4dcA958";
let stakingFacet = (await ethers.getContractAt(
"StakingFacet",
maticStakingAddress
)) as StakingFacet;
const frensBefore = await stakingFacet.frens(address, { blockTag: 23302659 });
console.log("frens before:", ethers.utils.formatEther(frensBefore));
const frensAfter = await stakingFacet.frens(address, { blockTag: 23302660 });
console.log("frens after:", ethers.utils.formatEther(frensAfter));
const currentBalance = await stakingFacet.frens(address);
console.log("current balance:", ethers.utils.formatEther(currentBalance));
}
Example #10
Source File: deploy.ts From solidity-starter with MIT License | 6 votes |
async function main() {
const factory = await ethers.getContractFactory('Counter')
// If we had constructor arguments, they would be passed into deploy()
const contract = await factory.deploy()
// The address the Contract WILL have once mined
console.log(contract.address)
// The transaction that was sent to the network to deploy the Contract
console.log(contract.deployTransaction.hash)
// The contract is NOT deployed yet; we must wait until it is mined
await contract.deployed()
}
Example #11
Source File: index.ts From airnode with MIT License | 6 votes |
it('shows the need for assertArrayEquals', () => {
expect(ethers.BigNumber.from(123)).to.equal(123);
expect(ethers.BigNumber.from(123)).to.equal('123');
try {
expect(ethers.BigNumber.from([123])).to.equal(['123']);
expect.fail();
// eslint-disable-next-line no-empty
} catch {}
assertArrayEquals([[ethers.BigNumber.from(123)], [ethers.BigNumber.from(456)]], [['123'], [456]]);
});
Example #12
Source File: UnbuttonAaveLinearPool.test.ts From balancer-v2-monorepo with GNU General Public License v3.0 | 6 votes |
async function setupWrappedTokensAndLP(w1Rate: BigNumberish, w2Rate: BigNumberish): Promise<LinearPool> {
const [, owner] = await ethers.getSigners();
const [mainToken, wrappedToken] = await setupWrappedTokens(w1Rate, w2Rate);
const vault = await Vault.create();
const poolContract = await deploy('UnbuttonAaveLinearPool', {
args: [
vault.address,
'Balancer Pool Token',
'BPT',
mainToken.address,
wrappedToken.address,
bn(0),
POOL_SWAP_FEE_PERCENTAGE,
bn(0),
bn(0),
owner.address,
],
});
const pool = await LinearPool.deployedAt(poolContract.address);
return pool;
}
Example #13
Source File: barn-transfer-ownership.ts From BarnBridge-Barn with Apache License 2.0 | 5 votes |
// todo: change address
async function main () {
const barnOwnership= await ethers.getContractAt('OwnershipFacet', _barn);
await barnOwnership.transferOwnership(_gov);
}
Example #14
Source File: CommunityVault.test.ts From BarnBridge-YieldFarming with Apache License 2.0 | 5 votes |
describe("CommunityVault", function () {
let bondToken: ERC20Mock;
let communityVault: CommunityVault;
let creator: Signer, owner: Signer, user: Signer;
let creatorAddr: string, ownerAddr: string, userAddr: string;
const distributedAmount: BigNumber = BigNumber.from(800000).mul(tenPow18);
let snapshotId: any;
before(async () => {
[creator, owner, user] = await ethers.getSigners();
creatorAddr = await creator.getAddress();
ownerAddr = await owner.getAddress();
userAddr = await user.getAddress();
bondToken = (await deployContract("ERC20Mock")) as ERC20Mock;
communityVault = (await deployContract("CommunityVault", [bondToken.address])) as CommunityVault;
});
beforeEach(async function () {
snapshotId = await ethers.provider.send("evm_snapshot", []);
});
afterEach(async function () {
await ethers.provider.send("evm_revert", [snapshotId]);
});
describe("General Contract checks", function () {
it("should be deployed", async function () {
expect(communityVault.address).to.not.equal(0);
expect(bondToken.address).to.not.equal(0);
});
});
describe("Contract Tests", function () {
it("Mint bond tokens in community vault address", async function () {
await bondToken.mint(communityVault.address, distributedAmount);
expect(await bondToken.balanceOf(communityVault.address)).to.be.equal(distributedAmount);
});
it("should fail if no owner tries to set allowance", async function () {
await expect(communityVault.connect(user).setAllowance(userAddr, distributedAmount)).to.be.revertedWith(
"Ownable: caller is not the owner"
);
});
it("should set allowance as owner", async function () {
await bondToken.mint(communityVault.address, distributedAmount);
await communityVault.connect(creator).setAllowance(userAddr, distributedAmount);
expect(await bondToken.allowance(communityVault.address, userAddr)).to.be.equal(distributedAmount);
});
it("should transfer ownership", async function () {
expect(await communityVault.owner()).to.be.equal(creatorAddr);
await expect(communityVault.connect(creator).transferOwnership(ownerAddr)).to.emit(
communityVault, "OwnershipTransferred");
expect(await communityVault.owner()).to.be.equal(ownerAddr);
});
});
describe("Events", function () {
it("setAllowance emits SetAllowance", async function () {
await bondToken.mint(communityVault.address, distributedAmount);
await expect(communityVault.connect(creator).setAllowance(userAddr, distributedAmount))
.to.emit(communityVault, "SetAllowance");
});
});
});
Example #15
Source File: aegisgasstrategy.test.ts From aegis with MIT License | 5 votes |
describe('High gas strategy', function () {
let aegisERC20: AegisERC20;
let aegisShield: AegisShield;
let uniswapRouter: IUniswapV2Router02;
let deployer: SignerWithAddress,
botOwner: SignerWithAddress,
botOwnerAlt: SignerWithAddress,
botBuyer: SignerWithAddress;
const wethAddress = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2';
this.beforeAll('deploy contracts', async function () {
[deployer, botOwner, botOwnerAlt, botBuyer] = await ethers.getSigners();
const AegisERC20 = await ethers.getContractFactory('AegisERC20');
aegisERC20 = await AegisERC20.deploy();
await aegisERC20.deployed();
const GasStrategy = await ethers.getContractFactory('AegisGasStrategy');
const gasStrategy = await GasStrategy.deploy(false, 0); // same block strategy should confiscate tokens and not vest
await gasStrategy.deployed();
const AegisShield = await ethers.getContractFactory('AegisShield');
aegisShield = await AegisShield.deploy(
[gasStrategy.address], // strategies to use
aegisERC20.address, // address of the token we're protecting
wethAddress, // pair is with wrapped ether
0 // uniswap
);
await aegisShield.deployed();
await deployer.sendTransaction({
to: aegisERC20.address,
value: ethers.utils.parseEther('100')
});
uniswapRouter = IUniswapV2Router02__factory.connect('0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', botOwner);
});
it('should blacklist bot buying with high gas price after listing', async function () {
const listingTx = await (await aegisERC20.list(aegisShield.address)).wait();
await uniswapRouter
.connect(botBuyer)
.swapExactETHForTokens(
0,
[wethAddress, aegisERC20.address],
botOwner.address,
Math.floor(Date.now() / 1000) + 1000,
{
value: ethers.utils.parseEther('2'),
gasPrice: listingTx.effectiveGasPrice.mul(20)
}
);
await expect(
aegisERC20.connect(botOwner).transfer(botOwnerAlt.address, ethers.utils.parseEther('1'))
).to.be.revertedWith('AEGIS: You are blacklisted');
});
});
Example #16
Source File: index.ts From index-coop-smart-contracts with Apache License 2.0 | 5 votes |
provider = ethers.provider
Example #17
Source File: index.ts From index-rebalance-utils with Apache License 2.0 | 5 votes |
provider = ethers.provider
Example #18
Source File: L1_NovaApprovalEscrow.test.ts From nova with GNU Affero General Public License v3.0 | 5 votes |
describe("L1_NovaApprovalEscrow", function () {
let signers: SignerWithAddress[];
before(async () => {
signers = await ethers.getSigners();
});
/// Mocks:
let MockERC20: MockERC20;
let MockRecipientAddress: string = "0xfEEDFaCEcaFeBEEFfEEDFACecaFEBeeFfeEdfAce";
// Nova Contracts:
let L1_NovaApprovalEscrow: L1NovaApprovalEscrow;
describe("constructor/setup", function () {
it("should properly deploy mocks", async function () {
MockERC20 = await (await getFactory<MockERC20__factory>("MockERC20")).deploy();
});
it("should properly deploy the execution escrow", async function () {
L1_NovaApprovalEscrow = await (
await getFactory<L1NovaApprovalEscrow__factory>("L1_NovaApprovalEscrow")
).deploy();
});
it("should contain constants that match expected values", async function () {
const [deployer] = signers;
await L1_NovaApprovalEscrow.ESCROW_ADMIN().should.eventually.equal(deployer.address);
});
});
describe("transferApprovedToken", function () {
it("should transfer an arbitrary token to an arbitrary destination", async function () {
const [admin] = signers;
// Approve some tokens to the escrow.
const weiAmount = ethers.utils.parseEther("1337");
await MockERC20.approve(L1_NovaApprovalEscrow.address, weiAmount);
await snapshotGasCost(
L1_NovaApprovalEscrow.transferApprovedToken(
MockERC20.address,
weiAmount,
admin.address,
MockRecipientAddress
)
)
// The correct amount of tokens should be transferred to the recipient.
.should.emit(MockERC20, "Transfer")
.withArgs(admin.address, MockRecipientAddress, weiAmount);
await MockERC20.balanceOf(MockRecipientAddress).should.eventually.equal(weiAmount);
});
it("does not allow calling if not admin", async function () {
const [, nonAdmin] = signers;
await L1_NovaApprovalEscrow.connect(nonAdmin)
.transferApprovedToken(
ethers.constants.AddressZero,
0,
ethers.constants.AddressZero,
ethers.constants.AddressZero
)
.should.be.revertedWith("UNAUTHORIZED");
});
});
});
Example #19
Source File: fixtures.ts From hypervisor with The Unlicense | 5 votes |
async function hypervisorFactoryFixture(factory: IUniswapV3Factory): Promise<HypervisorFactoryFixture> {
const hypervisorFactoryFactory = await ethers.getContractFactory('HypervisorFactory')
const hypervisorFactory = (await hypervisorFactoryFactory.deploy(factory.address)) as HypervisorFactory
return { hypervisorFactory }
}
Example #20
Source File: helpers.ts From aavegotchi-contracts with MIT License | 5 votes |
export async function impersonateSigner(network: any, address: string) {
await network.provider.request({
method: "hardhat_impersonateAccount",
params: [address],
});
return await ethers.getSigner(address);
}
Example #21
Source File: deployFirstEpoch.ts From ghst-staking with MIT License | 5 votes |
async function main() {
const signer = await getDiamondSigner(
ethers,
network,
"0x258cC4C495Aef8D809944aD94C6722ef41216ef3",
false
);
const stakingFacet = (await ethers.getContractAt(
"StakingFacet",
ghstStakingDiamondAddress,
signer
)) as StakingFacet;
let tx = await stakingFacet.addRateManagers([
"0x258cC4C495Aef8D809944aD94C6722ef41216ef3",
]);
await tx.wait();
const pools: PoolObject[] = [
{
_poolAddress: "0x385Eeac5cB85A38A9a07A70c73e0a3271CfB54A7",
_poolReceiptToken: ethers.constants.AddressZero,
_rate: "1",
_poolName: "GHST",
_poolUrl: "",
},
{
_poolAddress: "0x8b1fd78ad67c7da09b682c5392b65ca7caa101b9",
_poolReceiptToken: "0xA02d547512Bb90002807499F05495Fe9C4C3943f",
_rate: "83",
_poolName: "GHST-QUICK",
_poolUrl: "",
},
{
_poolAddress: "0x096c5ccb33cfc5732bcd1f3195c13dbefc4c82f4",
_poolReceiptToken: "0x04439eC4ba8b09acfae0E9b5D75A82cC63b19f09",
_rate: "74000000",
_poolName: "GHST-USDC",
_poolUrl: "",
},
{
_poolAddress: "0xccb9d2100037f1253e6c1682adf7dc9944498aff",
_poolReceiptToken: "0x388E2a3d389F27504212030c2D42Abf0a8188cd1",
_rate: "12000000",
_poolName: "GHST-WETH",
_poolUrl: "",
},
];
tx = await stakingFacet.initiateEpoch(pools, {
gasPrice: gasPrice,
});
console.log("Iniating epoch:", tx.hash);
let receipt = await tx.wait();
if (!receipt.status) {
throw Error(`Updating accounts failed: ${tx.hash}`);
}
console.log("Epoch created");
}