HandsOnChain

利金を入れて受け取る

作るもの

このレッスンを終えると、発行体が決済のコントラクトへ利金を入れ、投資家が利払い日の後に記録日の口数の分の利金を受け取れるようになります。
受け取れるのは1つの回につき1度だけで、発行体の入金が総額に足りない回の受け取りは、コントラクトが拒みます。
発行体が総額より多く入れた時は、多い分を発行体へ返します。

背景

社債の利金は、発行体が利払い日までにお金を用意し、利払い日に持ち主へ払います。
発行体が利息か元本を払えないことを、債務不履行と呼び、デフォルトとも言います。
持ち主にとっては、発行体が今回の利金を用意できたかどうかが大事な知らせになります。

チェーンの上で利金を払うやり方は、大きく分けて2つあります。

払い方 中身 困る所
発行体が全員へ送る 1つの取引で持ち主を順に回り、円トークンを送る 持ち主が増えるほど、取引の手数料が増える。
1人でも凍結されていると、その送金が拒まれて取引の全体が止まる
投資家が受け取りに来る 発行体はコントラクトへ総額を入れ、投資家がそれぞれ自分の分を引き出す 投資家が自分で取引を送る

このコースでは、投資家が受け取りに来るやり方にし、コントラクトに次の決まりを持たせます。

決まり 理由
発行体の入金は総額までにし、多い分は返す コントラクトに残る円を、払う約束の額と同じにする
入金が総額に届くまで、その回は誰も受け取れない 足りないまま先に来た人へ払うと、後から来た人の分が足りなくなる
足りない分は、利払い日の後でも足せる 遅れて入金しても、全員が受け取れるようにする
受け取りは1つの回につき1度だけ 同じ人が2回受け取ると、ほかの人の分がなくなる

入金の額と総額は誰でもコントラクトから読めます。
利払い日を過ぎても入金が総額に届いていなければ、その回が払われていないことを、持ち主も発行体も同じ値で確かめられます。

投資家が受け取りを頼むと、コントラクトは次の順に確かめてから円を送ります。

利金の受け取りを受け付けるか
まだ足りない受け取った0口始まり終わり受け取りを頼む利払い日になった?入金は総額に届いた?この回をもう受け取った?記録日の口数は1口以上?口数の分の利金を送る拒む112233445566なったなったなった届いた届いた届いたまだまだまだ10口

実装

starter/contracts/contracts/BondSettlement.solを開き、closedの後に、回ごとの入金と支払いを持つ変数を足します。

    /// @notice 募集を締めたか
    bool public closed;
    /// @notice 回ごとに、発行体が入れた利金の額 (円トークンの最小単位)
    mapping(uint256 n => uint256 amount) public couponFunded;
    /// @notice 回ごとに、投資家へ払った利金の額
    mapping(uint256 n => uint256 amount) public couponPaid;
    /// @notice 回ごとに、その投資家が受け取ったか
    mapping(uint256 n => mapping(address investor => bool)) public couponClaimed;

couponPaidは、この節では読みません。
決済のコントラクトに残る円が払う約束の額を下回らないことを、節5のinvariantのテストで確かめる時に使います。

イベントとエラーを、それぞれの並びの末尾に足します。

    event CouponFunded(uint256 indexed n, uint256 amount);
    event CouponClaimed(uint256 indexed n, address indexed investor, uint256 amount);
    error OnlyIssuer();
    error NotIssued();
    error BeforePaymentDate(uint256 n, uint64 date);
    error CouponUnfunded(uint256 n, uint256 funded, uint256 due);
    error AlreadyClaimed(uint256 n, address investor);
    error NothingToClaim();
エラー 拒む時
OnlyIssuer 発行体でないアカウントが利金を入れようとした
NotIssued 募集を締めて社債を発行する前に、利金を入れようとした
BeforePaymentDate 利払い日の前に受け取ろうとした
CouponUnfunded 発行体の入金が、その回の総額に届いていない
AlreadyClaimed その回をもう受け取っている
NothingToClaim 記録日に社債を1口も持っていなかった

コンストラクタの後に、発行体だけが呼べる関数に付ける修飾子を足します。

    modifier onlyIssuer() {
        if (msg.sender != issuer) revert OnlyIssuer();
        _;
    }

_;の所で、修飾子を付けた関数の本体が動きます。
発行体でなければ、本体に入る前に取引を拒みます。

前のレッスンで作ったcouponDueの後に、発行体が利金を入れる関数を足します。

    /// @notice 発行体がn回目の利金を入れる。足りない分は後から何度でも足せ、総額を超えた分は発行体へ返す
    function fundCoupon(uint256 n, uint256 amount) external onlyIssuer {
        if (!issued()) revert NotIssued();
        jpy.transferFrom(msg.sender, address(this), amount);
        uint256 due = couponDue(n);
        uint256 room = due > couponFunded[n] ? due - couponFunded[n] : 0;
        uint256 kept = amount < room ? amount : room;
        couponFunded[n] += kept;
        if (amount > kept) jpy.transfer(msg.sender, amount - kept);
        emit CouponFunded(n, kept);
    }
行 意味
jpy.transferFrom(msg.sender, address(this), amount) 発行体が任せた円を、決済のコントラクトへ移す。
発行体は先に円トークンのapproveで額を任せておく
room その回の総額まで、あといくら入れられるか。
もう総額に届いていれば0になる
kept 入れた額とroomの小さい方。
この額だけを入金として数える
jpy.transfer(msg.sender, amount - kept) 総額を超えた分を、同じ取引の中で発行体へ返す

続けて、投資家が利金を受け取る関数を足します。

    /// @notice 利払い日の後に、記録日に持っていた口数の利金を受け取る。入金が総額に足りない回は未払いとして断る
    function claimCoupon(uint256 n) external {
        uint64 date = bond.paymentDate(n);
        if (block.timestamp < date) revert BeforePaymentDate(n, date);
        uint256 due = couponDue(n);
        if (couponFunded[n] < due) revert CouponUnfunded(n, couponFunded[n], due);
        if (couponClaimed[n][msg.sender]) revert AlreadyClaimed(n, msg.sender);
        uint256 units = bond.balanceAt(msg.sender, bond.recordDate(n));
        if (units == 0) revert NothingToClaim();
        couponClaimed[n][msg.sender] = true;
        uint256 amount = couponPerUnit(n) * units * YEN;
        couponPaid[n] += amount;
        jpy.transfer(msg.sender, amount);
        emit CouponClaimed(n, msg.sender, amount);
    }
行 意味
block.timestamp < date 利払い日は日本時間の0時なので、利払い日になった時から受け取れる
couponFunded[n] < due 1円でも足りなければ、その回は誰も受け取れない
bond.balanceAt(msg.sender, bond.recordDate(n)) 今の口数ではなく、記録日になった時の口数を読む
couponClaimed[n][msg.sender] = true 円を送る前に、受け取り済みの印を付ける
couponPerUnit(n) * units * YEN 1口の利金に記録日の口数を掛け、円トークンの最小単位にする

受け取り済みの印は、円を送るより前に付けます。
状態を全て書き換えてから外のコントラクトを呼ぶ順は、Solidityで二重払いを防ぐための定石です。
外のコントラクトから同じ関数がもう一度呼ばれても、2回目はAlreadyClaimedで拒まれます。

テストでは、発行体が円を任せてから利金を入れる手順を何度も使います。
starter/contracts/test/DigitalBond.t.solのDigitalBondBaseの末尾に、この手順をまとめた関数を足します。

    function _fundCoupon(uint256 n, uint256 amount) internal {
        vm.startPrank(issuer);
        jpy.approve(address(settlement), amount);
        settlement.fundCoupon(n, amount);
        vm.stopPrank();
    }

前のレッスンのtest_CouponIsActualOver365RoundedDownの末尾には、総額を入れてaliceが受け取るまでを足します。

        assertEq(settlement.couponDue(0), 396 * ISSUE_AMOUNT * YEN);
        _fundCoupon(0, settlement.couponDue(0));
        vm.warp(PAY_1);
        uint256 before = jpy.balanceOf(alice);
        vm.prank(alice);
        settlement.claimCoupon(0);
        assertEq(jpy.balanceOf(alice), before + 396 * 10 * YEN);
    }

DigitalBondTestの末尾に、記録日の口数で払うことと、入金と受け取りの決まりを確かめるテストを足します。

    function test_CouponUsesRecordDateBalance() public {
        _issueBond();
        _fundCoupon(0, settlement.couponDue(0));
        // 記録日の後にaliceがbobへ4口売っても、第1回の利金は記録日の10口で決まる
        vm.warp(RECORD_1 + 1 days);
        vm.prank(alice);
        bond.transfer(bob, 4);
        vm.warp(PAY_1);
        uint256 aliceBefore = jpy.balanceOf(alice);
        uint256 bobBefore = jpy.balanceOf(bob);
        vm.prank(alice);
        settlement.claimCoupon(0);
        vm.prank(bob);
        settlement.claimCoupon(0);
        assertEq(jpy.balanceOf(alice), aliceBefore + 396 * 10 * YEN);
        assertEq(jpy.balanceOf(bob), bobBefore + 396 * 12 * YEN);
    }

    function test_IssuerGetsBackExcess() public {
        _issueBond();
        uint256 due = settlement.couponDue(0);
        uint256 before = jpy.balanceOf(issuer);
        _fundCoupon(0, due + 500 * YEN);
        assertEq(settlement.couponFunded(0), due);
        assertEq(jpy.balanceOf(issuer), before - due);
        assertEq(jpy.balanceOf(address(settlement)), due);
    }

    function test_RevertWhen_ClaimBeforePaymentDate() public {
        _issueBond();
        _fundCoupon(0, settlement.couponDue(0));
        vm.warp(PAY_1 - 1);
        vm.prank(alice);
        vm.expectRevert(abi.encodeWithSelector(BondSettlement.BeforePaymentDate.selector, 0, PAY_1));
        settlement.claimCoupon(0);
        assertFalse(settlement.couponClaimed(0, alice));
    }

    function test_RevertWhen_ClaimUnfunded() public {
        _issueBond();
        uint256 due = settlement.couponDue(0);
        _fundCoupon(0, due - 1 * YEN);
        vm.warp(PAY_1);
        uint256 before = jpy.balanceOf(alice);
        vm.prank(alice);
        vm.expectRevert(abi.encodeWithSelector(BondSettlement.CouponUnfunded.selector, 0, due - 1 * YEN, due));
        settlement.claimCoupon(0);
        assertEq(jpy.balanceOf(alice), before);
        assertFalse(settlement.couponClaimed(0, alice));
    }

    function test_ClaimAfterLateFunding() public {
        _issueBond();
        uint256 due = settlement.couponDue(0);
        _fundCoupon(0, due - 100 * YEN);
        vm.warp(PAY_1 + 3 days);
        _fundCoupon(0, 100 * YEN);
        uint256 before = jpy.balanceOf(alice);
        vm.prank(alice);
        settlement.claimCoupon(0);
        assertEq(jpy.balanceOf(alice), before + 396 * 10 * YEN);
    }

    function test_RevertWhen_ClaimTwice() public {
        _issueBond();
        _fundCoupon(0, settlement.couponDue(0));
        vm.warp(PAY_1);
        vm.startPrank(alice);
        settlement.claimCoupon(0);
        uint256 before = jpy.balanceOf(alice);
        vm.expectRevert(abi.encodeWithSelector(BondSettlement.AlreadyClaimed.selector, 0, alice));
        settlement.claimCoupon(0);
        vm.stopPrank();
        assertEq(jpy.balanceOf(alice), before);
    }
テスト 確かめること
test_CouponUsesRecordDateBalance 記録日の後に4口を売っても、aliceは記録日の10口分を、bobは記録日の12口分を受け取る
test_IssuerGetsBackExcess 総額より500円多く入れると、入金は総額で止まり、500円が発行体へ戻る
test_RevertWhen_ClaimBeforePaymentDate 利払い日の1秒前は受け取れない
test_RevertWhen_ClaimUnfunded 入金が1円足りないと受け取れず、aliceの円も変わらない
test_ClaimAfterLateFunding 利払い日の3日後に足りない100円を足すと、受け取れるようになる
test_RevertWhen_ClaimTwice 2回目の受け取りは拒まれ、aliceの円は増えない

確かめる

starter/contractsのディレクトリでテストを実行します。

forge test --match-contract DigitalBondTest

次の行が出れば、テストは通っています。

[PASS] test_ClaimAfterLateFunding()
[PASS] test_CouponIsActualOver365RoundedDown()
[PASS] test_CouponUsesRecordDateBalance()
[PASS] test_IssuerGetsBackExcess()
[PASS] test_RevertWhen_ClaimBeforePaymentDate()
[PASS] test_RevertWhen_ClaimTwice()
[PASS] test_RevertWhen_ClaimUnfunded()
Suite result: ok. 18 passed; 0 failed; 0 skipped

claimCouponのcouponClaimed[n][msg.sender] = true;の行を消して実行すると、test_RevertWhen_ClaimTwiceが失敗します。

[FAIL: next call did not revert as expected] test_RevertWhen_ClaimTwice()

受け取り済みの印がないと、aliceは同じ回の利金を何度でも受け取れてしまいます。
確かめたら、消した行を戻しておきます。

次のレッスンで、ローカルノードの時刻を記録日と利払い日へ進め、利金を入れて受け取るまでをブラウザから試せるようにします。