liquidate.js
1 import { E } from '@endo/eventual-send'; 2 import { AmountMath } from '@agoric/ertp'; 3 4 import { 5 offerTo, 6 swapExact 7 } from '@agoric/zoe/src/contractSupport/zoeHelpers.js'; 8 import { getGive, getWant } from '../../../shared/helpers.js'; 9 import { atomicRearrange } from '@agoric/zoe/src/contractSupport/index.js'; 10 11 const giveCollateralToLender = async ( 12 zcf, 13 { collateralSeat, lenderSeat, debtObject, debtBrand, collateralObject } 14 ) => 15 await atomicRearrange( 16 zcf, 17 harden([ 18 // Transfer the wanted Loan amount to the borrower 19 [ 20 collateralSeat, 21 lenderSeat, 22 { 23 [`${collateralObject.keyword}`]: collateralSeat.getAmountAllocated( 24 collateralObject.keyword 25 ) 26 } 27 ], 28 // Transfer *all* collateral to the collateral seat. 29 [ 30 lenderSeat, 31 collateralSeat, 32 { 33 [`${debtObject.keyword}`]: AmountMath.makeEmpty(debtBrand) 34 } 35 ] 36 ]) 37 ); 38 39 const closeSuccessfully = (zcf, lenderSeat, collateralSeat) => () => { 40 lenderSeat.exit(); 41 collateralSeat.exit(); 42 zcf.shutdown('your loan had to be liquidated'); 43 }; 44 45 const closeWithFailure = (zcf, lenderSeat, collateralSeat) => err => { 46 lenderSeat.fail(err); 47 collateralSeat.fail(err); 48 zcf.shutdownWithFailure(err); 49 throw err; 50 }; 51 52 /** 53 * This function is triggered by the priceAuthority when the value of the 54 * collateral is below the maxLtv. The function performs the 55 * liquidation and then shuts down the contract. Note that if a 56 * liquidation occurs, the borrower gets nothing and they can take no 57 * further action. 58 * 59 * For simplicity, we will sell all collateral. 60 * 61 * @type {Liquidate} 62 */ 63 const liquidate = async (zcf, loanState) => { 64 await giveCollateralToLender(zcf, loanState).then( 65 closeSuccessfully(zcf, loanState.lenderSeat, loanState.collateralSeat), 66 closeWithFailure(zcf, loanState.lenderSeat, loanState.collateralSeat) 67 ); 68 }; 69 harden(liquidate); 70 71 export { liquidate };