HandsOnChain

担保の利金と期限の画面を作る

作るもの

このレッスンを終えると、借り手のページに担保の利金の表が付き、利払い日の後に「受け取る」を押して利金を受け取れます。
ヘッダーの下の帯には「返済の期限へ進める」が付き、チェーンの時刻を返済の期限の1秒後へ進められます。
返していない借り手は、状態の札が「返済の期限を過ぎた」に変わります。
貸し手のページでは、その借り手の担保を猶予を待たずに処分できます。

背景

前の2つのレッスンで、ローンのコントラクトは担保の社債の利金を借り手へ渡し、返済の期限を過ぎた借り手の担保を処分できるようになりました。
このレッスンでは、その2つを画面から試せるようにします。

担保の利金の表は、回ごとに次の値を出します。

列 出す値
回 第1回と第2回
記録日と利払い日 社債トークンが持つ、その回の記録日と利払い日
記録日に預けた口数 ローンのコントラクトのpledgedAtが返す、記録日にこのアカウントが担保として預けていた口数。
記録日の前は-
受け取れる額 ローンのコントラクトのcouponOfが返す額。
記録日の前は-
状態 受け取り済みか、利払い日の前か、発行体の入金が総額に届いたか

記録日の前は、預けた口数がまだ増えたり減ったりします。
そのため、記録日を過ぎるまで口数と額を出しません。

状態の札は、次の順に決めます。

利金の行の状態の札を決める順
受け取ったまだ足りない始まり終わり終わり終わり終わり回の行を描くもう受け取った?利払い日を過ぎた?入金は総額に届いた?入金済みで受け取れる受け取り済み利払い日の前未払い1122334455まだまだまだ過ぎた過ぎた過ぎた届いた

返済の期限は2026-12-15で、第1回の利払い日の2026-07-15より後にあります。
そのため、「返済の期限へ進める」を1回押すと、第1回の利金も受け取れる時刻になります。
第2回の記録日の2027-01-10は期限より後なので、第2回は「利払い日の前」のままです。

期限の1秒後には価格を入れてから3日を過ぎているので、帯に「3日を過ぎた価格」の札が出ます。
担保を処分する前に、帯の価格のボタンで評価会社に価格を入れ直してもらいます。

実装

帯に返済の期限へ進めるボタンを足す

starter/app/src/lib/band.tsのBandStateに、返済の期限を足します。

export type BandState = {
  // 社債1口の今の価格 (円)
  price: number;
  // 請求の猶予の終わり。請求のない時は0
  graceEnd: number;
  // 返済の期限
  dueDate: number;
};

bandButtonsが返す並びの末尾に、返済の期限の1秒後へ進めるボタンを足します。

    // 猶予の終わりちょうどはまだ処分できないので、その1秒後へ進める
    { label: "猶予の終わりへ進める", time: state.graceEnd > 0 && now <= state.graceEnd ? state.graceEnd + 1 : null },
    { label: "返済の期限へ進める", time: now <= state.dueDate ? state.dueDate + 1 : null },
  ];
}
コード 意味
state.dueDate + 1 ローンのコントラクトはblock.timestamp > dueDateの時に処分できるので、期限の1秒後へ進める
now <= state.dueDate 期限を過ぎた後は進める先がないので、nullにしてボタンを押せなくする

BandButtonの型のlabelには、「返済の期限へ進める」が前の節から入っています。
starter/app/src/components/band.tsxでは、帯に渡す値に返済の期限を足します。

  const state = {
    price: Number(loan.price ?? 0n),
    graceEnd: graceEnd ?? 0,
    dueDate: Number(loan.dueDate ?? 0n),
  };

返済の期限を過ぎた状態を出す

starter/app/src/components/loan-status.tsのstatusOfに、返済の期限を受け取る引数を足します。

export function statusOf(position: LoanPosition, now: bigint, dueDate: bigint | undefined): LoanStatus {

担保のない借り手を見た行の次に、期限を過ぎたかを見る行を足します。

  if (position.units === 0n) return { label: "借金が残る", tone: "bad", liquidatable: false };
  if (dueDate !== undefined && now > dueDate) return { label: "返済の期限を過ぎた", tone: "bad", liquidatable: true };
  if (ratio !== undefined && ratio < LIQUIDATE_BPS) return { label: "処分できる", tone: "bad", liquidatable: true };
コード 意味
now > dueDate コントラクトのliquidatableと同じく、期限の時刻ちょうどではなく1秒後から処分できると見る
liquidatable: true 貸し手のページに、この借り手の担保の処分の内訳と「担保を買って処分する」を出す

liquidatableと同じ順に確かめるので、返し終えた借り手と担保のない借り手は、期限を過ぎてもこの札になりません。
starter/app/src/components/borrower-view.tsxとstarter/app/src/components/lender-view.tsxでは、statusOfに返済の期限を渡します。

  const status = position ? statusOf(position, now, loanState.dueDate) : undefined;
  const statuses = loanState.positions.map((position) => ({ position, status: statusOf(position, now, loanState.dueDate) }));

担保の利金を読む

starter/app/src/components/use-loan.tsで、決済のコントラクトのABIを読み込みます。

import { bondSettlementAbi, bondTokenAbi, collateralPriceAbi, jpyTokenAbi, securitiesLoanAbi } from "@contracts/generated/abi";

RawPositionの前に、回ごとの利金の型を足します。

export type Coupon = {
  n: number;
  recordDate: bigint | undefined;
  paymentDate: bigint | undefined;
  // 今のアカウントが記録日に担保として預けていた口数と、受け取れる額と、受け取ったか
  unitsAtRecord: bigint | undefined;
  amount: bigint | undefined;
  claimed: boolean | undefined;
  // 発行体が決済のコントラクトへ入れた額と、入れる総額
  funded: bigint | undefined;
  due: bigint | undefined;
};

useLoanの頭で決済のコントラクトを指し、最初にまとめて読む値に回の数を足します。

  const settlement = { address: contracts.settlement, abi: bondSettlementAbi as Abi };
      allowed: { ...jpy, functionName: "isAllowed", args: [me] },
      couponCount: { ...bond, functionName: "couponCount" },

借り手ごとの担保と借入を作るpositionOfの後に、回ごとの値を読む処理を足します。

  const count = Number((base.couponCount as bigint | undefined) ?? 0n);
  const indexes = Array.from({ length: count }, (_, n) => n);
  const perCoupon = useNamedReads(
    Object.fromEntries(
      indexes.flatMap((n) => [
        [`record:${n}`, { ...bond, functionName: "recordDate", args: [BigInt(n)] }],
        [`payment:${n}`, { ...bond, functionName: "paymentDate", args: [BigInt(n)] }],
        [`amount:${n}`, { ...loan, functionName: "couponOf", args: [BigInt(n), me] }],
        [`claimed:${n}`, { ...loan, functionName: "couponClaimed", args: [BigInt(n), me] }],
        [`funded:${n}`, { ...settlement, functionName: "couponFunded", args: [BigInt(n)] }],
        [`due:${n}`, { ...settlement, functionName: "couponDue", args: [BigInt(n)] }],
      ]),
    ),
    enabled && count > 0,
  );
  // 記録日に預けていた口数は、記録日を読めた後に読む
  const atRecord = useNamedReads(
    Object.fromEntries(
      indexes.map((n) => [`units:${n}`, { ...loan, functionName: "pledgedAt", args: [me, (perCoupon[`record:${n}`] as bigint | undefined) ?? 0n] }]),
    ),
    enabled && count > 0 && indexes.every((n) => perCoupon[`record:${n}`] !== undefined),
  );
  const coupons: Coupon[] = indexes.map((n) => ({
    n,
    recordDate: perCoupon[`record:${n}`] as bigint | undefined,
    paymentDate: perCoupon[`payment:${n}`] as bigint | undefined,
    unitsAtRecord: atRecord[`units:${n}`] as bigint | undefined,
    amount: perCoupon[`amount:${n}`] as bigint | undefined,
    claimed: perCoupon[`claimed:${n}`] as boolean | undefined,
    funded: perCoupon[`funded:${n}`] as bigint | undefined,
    due: perCoupon[`due:${n}`] as bigint | undefined,
  }));

返す値の末尾にcouponsを足します。

    positions: listed.map(positionOf),
    coupons,
  };
}
コード 意味
couponCount 社債トークンが持つ利払いの回の数。
この数だけ回の行を作る
perCoupon 回ごとに、記録日と利払い日と受け取れる額と受け取ったかと、発行体の入金と総額を1回でまとめて読む
atRecord 記録日に預けていた口数を読む。
pledgedAtには記録日を渡すので、perCouponで記録日を読めた後に読む
couponFundedとcouponDue 2作目の決済のコントラクトが持つ、発行体が入れた利金と払う総額

画面は、記録日と利払い日を2回の段に分けて読みます。

利金の表を読む2つの段
画面が持つ値回の数2回記録日2026-07-10と2027-01-10記録日に預けた口数10口借り手のページBorrowerView社債トークンBondTokenローンのコントラクトSecuritiesLoan決済のコントラクトBondSettlement112233couponCount()couponCount()2回2回recordDate(n)とpaymentDate(n)recordDate(n)とpaymentDate(n)couponOf(n, 借り手A)とcouponClaimed(n, 借り手A)couponOf(n, 借り手A)とcouponClaimed(n, 借り手A)couponFunded(n)とcouponDue(n)couponFunded(n)とcouponDue(n)pledgedAt(借り手A, 記録日)10口

担保の利金の表を置く

starter/app/src/components/borrower-view.tsxの「返す」の枠の後に、担保の利金の枠を足します。

      <Card title="担保の利金" description="記録日に担保として預けていた口数の分を、ローンのコントラクトが受け取って借り手へ渡します。">
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>回</th>
                <th>記録日</th>
                <th>利払い日</th>
                <th className="num">記録日に預けた口数</th>
                <th className="num">受け取れる額</th>
                <th>状態</th>
                <th aria-label="操作" />
              </tr>
            </thead>
            <tbody>
              {loanState.coupons.map((coupon) => {
                const recorded = coupon.recordDate !== undefined && now >= coupon.recordDate;
                const paid = coupon.paymentDate !== undefined && now >= coupon.paymentDate;
                const funded = coupon.due !== undefined && coupon.due > 0n && (coupon.funded ?? 0n) >= coupon.due;
                const amount = recorded ? coupon.amount : undefined;
                return (
                  <tr key={coupon.n}>
                    <td>第{coupon.n + 1}回</td>
                    <td>{formatDate(coupon.recordDate)}</td>
                    <td>{formatDate(coupon.paymentDate)}</td>
                    <td className="num">{recorded ? formatUnitsCount(coupon.unitsAtRecord) : "-"}</td>
                    <td className="num">{amount === undefined ? "-" : formatWholeYen(amount)}</td>
                    <td>
                      {coupon.claimed ? (
                        <Badge tone="info">受け取り済み</Badge>
                      ) : !paid ? (
                        <Badge tone="plain">利払い日の前</Badge>
                      ) : funded ? (
                        <Badge tone="good">入金済み</Badge>
                      ) : (
                        <Badge tone="bad">未払い</Badge>
                      )}
                    </td>
                    <td className="num">
                      {paid && !coupon.claimed && (amount ?? 0n) > 0n ? (
                        <button
                          type="button"
                          className="button button-small"
                          disabled={!funded || pending !== undefined}
                          onClick={() =>
                            send(`claim-${coupon.n}`, `第${coupon.n + 1}回の利金を受け取りました`, [
                              { ...loan, functionName: "claimCoupon", args: [BigInt(coupon.n)] },
                            ])
                          }
                        >
                          {pending === `claim-${coupon.n}` ? "受け取っています" : "受け取る"}
                        </button>
                      ) : null}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
コード 意味
recorded チェーンの時刻が記録日になったか。
記録日の前は口数と額を-にする
paid チェーンの時刻が利払い日になったか。
決済のコントラクトは利払い日の前の受け取りを拒む
funded 発行体の入金が総額に届いたか。
届いていない回は、押しても決済のコントラクトがCouponUnfundedで拒むので、ボタンを押せなくする
(amount ?? 0n) > 0n 記録日に1口も預けていなかった回は、受け取るものがないのでボタンを出さない
claimCoupon ローンのコントラクトに受け取りを頼む。
円トークンを任せるapproveは要らない

最後に、starter/app/src/lib/format.tsのreasonsに、利金の受け取りを断られた時の文を足します。

  BeforePaymentDate: "利払い日の後に受け取れます",
  CouponUnfunded: "発行体の利金の入金が足りないため、この回は未払いです",
  AlreadyClaimed: "この回の利金はもう受け取りました",
  NothingToClaim: "記録日に担保として預けていなかったので、この回の利金はありません",

BeforePaymentDateとCouponUnfundedは、ローンのコントラクトが呼んだ決済のコントラクトのエラーです。
use-send.tsは決済のコントラクトのABIでもエラーを読むので、同じ文で出せます。

確かめる

starter/appのディレクトリでpnpm devを実行し直し、ブラウザでページを開きます。

初めに、上の「貸し手」のページへ移り、右上で「銀行」を選びます。
「円を入れる」の欄に1000000を入れて「入れる」を押し、ローンのコントラクトへ100万円を入れます。
次に、上の「借り手」のページへ移り、右上で「借り手A」を選びます。
社債を10口預け、700000円を借ります。
担保の利金の表には第1回と第2回の行が並び、どちらも「利払い日の前」と出ます。

帯の「返済の期限へ進める」を押すと、チェーンの日付が2026-12-15に変わります。
状態の札が「返済の期限を過ぎた」になり、第1回の行には記録日に預けた10口と受け取れる3,960円が出ます。
1口の利金は2作目と同じ396円で、10口分が3,960円です。
第1回の「受け取る」を押すと「第1回の利金を受け取りました」と出て、札が「受け取り済み」に変わります。

返済の期限の後へ進め、借り手Aが担保の社債の第1回の利金3,960円を受け取ったところ
返済の期限の後へ進め、借り手Aが担保の社債の第1回の利金3,960円を受け取ったところ

続けて、期限を過ぎた担保を処分します。
帯には「3日を過ぎた価格」の札が出ているので、「価格を5%上げる」を押し、評価会社に1口105,000円の価格を入れてもらいます。
上の「貸し手」のページへ移り、右上で「借り手B」を選びます。
借り手Aの状態は「返済の期限を過ぎた」で、担保維持率は100%を大きく上回っていても、「借り手Aの担保の処分」の枠が出ます。
買い手が払う額は、10口 × 105,000円から5%を割り引いた997,500円です。
「担保を買って処分する」を押すと、借り手Bが997,500円を払って10口を買います。
払った円は利息と元本の700,000円に充て、残りを借り手Aへ返します。

返済の期限を過ぎた借り手Aの担保を、借り手Bが997,500円で買って処分したところ
返済の期限を過ぎた借り手Aの担保を、借り手Bが997,500円で買って処分したところ

価格を入れ直さずに「担保を買って処分する」を押すと、「最後の価格から3日を過ぎています。
評価会社が価格を入れ直すまで待ってください」と出ます。
期限を過ぎた後も、担保を売る額は3日以内の価格から決めます。

次のレッスンで、ローンと価格のコントラクトをテストネットのFujiへデプロイします。