Deposit collateral
This commit is contained in:
parent
7bcf3fe92c
commit
6e0aded775
|
@ -0,0 +1,22 @@
|
|||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
|
||||
contract Collateral {
|
||||
IERC20 private immutable token;
|
||||
mapping(address => uint256) private balances;
|
||||
|
||||
constructor(IERC20 _token) {
|
||||
token = _token;
|
||||
}
|
||||
|
||||
function balanceOf(address account) public view returns (uint256) {
|
||||
return balances[account];
|
||||
}
|
||||
|
||||
function deposit(uint256 amount) public {
|
||||
token.transferFrom(msg.sender, address(this), amount);
|
||||
balances[msg.sender] += amount;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
const { expect } = require("chai")
|
||||
|
||||
describe("Collateral", function () {
|
||||
let collateral, token
|
||||
let account0, account1
|
||||
|
||||
beforeEach(async function () {
|
||||
let Collateral = await ethers.getContractFactory("Collateral")
|
||||
let TestToken = await ethers.getContractFactory("TestToken")
|
||||
token = await TestToken.deploy()
|
||||
collateral = await Collateral.deploy(token.address)
|
||||
;[account0, account1] = await ethers.getSigners()
|
||||
await token.mint(account0.address, 1000)
|
||||
await token.mint(account1.address, 1000)
|
||||
})
|
||||
|
||||
it("assigns zero collateral by default", async function () {
|
||||
expect(await collateral.balanceOf(account0.address)).to.equal(0)
|
||||
expect(await collateral.balanceOf(account1.address)).to.equal(0)
|
||||
})
|
||||
|
||||
describe("depositing", function () {
|
||||
beforeEach(async function () {
|
||||
await token.connect(account0).approve(collateral.address, 100)
|
||||
await token.connect(account1).approve(collateral.address, 100)
|
||||
})
|
||||
|
||||
it("updates the amount of collateral", async function () {
|
||||
await collateral.connect(account0).deposit(40)
|
||||
await collateral.connect(account1).deposit(2)
|
||||
expect(await collateral.balanceOf(account0.address)).to.equal(40)
|
||||
expect(await collateral.balanceOf(account1.address)).to.equal(2)
|
||||
})
|
||||
|
||||
it("transfers tokens to the contract", async function () {
|
||||
let before = await token.balanceOf(collateral.address)
|
||||
await collateral.deposit(42)
|
||||
let after = await token.balanceOf(collateral.address)
|
||||
expect(after - before).to.equal(42)
|
||||
})
|
||||
|
||||
it("fails when token transfer fails", async function () {
|
||||
let allowed = await token.allowance(account0.address, collateral.address)
|
||||
let invalidAmount = allowed.toNumber() + 1
|
||||
await expect(collateral.deposit(invalidAmount)).to.be.revertedWith(
|
||||
"ERC20: transfer amount exceeds allowance"
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
Loading…
Reference in New Issue