|
1 | | -// TODO: implement buildLiquidateTx |
| 1 | +import { |
| 2 | + BlockfrostProvider, |
| 3 | + MeshTxBuilder, |
| 4 | + applyParamsToScript, |
| 5 | + serializePlutusScript, |
| 6 | + resolvePlutusScriptHash, |
| 7 | + mConStr0, |
| 8 | + mConStr2, |
| 9 | + type UTxO, |
| 10 | + type BrowserWallet, |
| 11 | +} from "@meshsdk/core"; |
| 12 | + |
| 13 | +import { |
| 14 | + UNPARAMETERISED_SCRIPT_CBOR, |
| 15 | + PARAMS, |
| 16 | + PYTH, |
| 17 | + computeBurnReturn, |
| 18 | +} from "./contract"; |
| 19 | + |
| 20 | +// ── Derive parameterised script once ───────────────────────────────────────── |
| 21 | + |
| 22 | +function getScript() { |
| 23 | + const scriptCbor = applyParamsToScript(UNPARAMETERISED_SCRIPT_CBOR, [ |
| 24 | + PARAMS.PYTH_POLICY_ID, |
| 25 | + PARAMS.ADA_USD_FEED_ID, |
| 26 | + PARAMS.COLLATERAL_RATIO, |
| 27 | + PARAMS.LIQUIDATION_THRESHOLD, |
| 28 | + ]); |
| 29 | + |
| 30 | + const script = { code: scriptCbor, version: "V3" as const }; |
| 31 | + const poolAddress = serializePlutusScript(script, undefined, 0).address; |
| 32 | + const scriptHash = resolvePlutusScriptHash(poolAddress); |
| 33 | + |
| 34 | + return { scriptCbor, scriptHash, poolAddress }; |
| 35 | +} |
| 36 | + |
| 37 | +// ── buildLiquidateTx ────────────────────────────────────────────────────────── |
| 38 | + |
| 39 | +/** |
| 40 | + * Build, sign, and submit a Liquidate transaction. |
| 41 | + * |
| 42 | + * Anyone can call this when the position's health ratio drops below |
| 43 | + * liquidation_threshold. No owner signature required. |
| 44 | + * |
| 45 | + * @param wallet Connected CIP-30 browser wallet (MeshSDK BrowserWallet) |
| 46 | + * @param synthToBurn Synth token amount to burn (in micro-USD, 6 decimals) |
| 47 | + * @param pythHex Signed Pyth price message (solanaPayload from backend) |
| 48 | + * @param adaUsdPrice Current ADA/USD price as a float (e.g. 0.70) |
| 49 | + * @param blockfrostKey Blockfrost preprod project ID |
| 50 | + * @returns Submitted transaction hash |
| 51 | + */ |
| 52 | +export async function buildLiquidateTx( |
| 53 | + wallet: BrowserWallet, |
| 54 | + synthToBurn: bigint, |
| 55 | + pythHex: string, |
| 56 | + adaUsdPrice: number, |
| 57 | + blockfrostKey: string |
| 58 | +): Promise<string> { |
| 59 | + const provider = new BlockfrostProvider(blockfrostKey); |
| 60 | + const { scriptCbor, scriptHash, poolAddress } = getScript(); |
| 61 | + |
| 62 | + // ── 1. Fetch UTxOs ──────────────────────────────────────────────────────── |
| 63 | + |
| 64 | + // Pool UTxO — the single UTxO locked at the script address. |
| 65 | + const poolUtxos: UTxO[] = await provider.fetchAddressUTxOs(poolAddress); |
| 66 | + if (poolUtxos.length === 0) throw new Error("Pool UTxO not found"); |
| 67 | + const poolUtxo = poolUtxos[0]; |
| 68 | + |
| 69 | + // Pyth State NFT UTxO — reference input carrying the oracle state. |
| 70 | + const pythStateUnit = PARAMS.PYTH_POLICY_ID + PYTH.STATE_ASSET_NAME; |
| 71 | + const pythUtxos: UTxO[] = await provider.fetchAddressUTxOs(PYTH.STATE_ADDRESS, pythStateUnit); |
| 72 | + if (pythUtxos.length === 0) throw new Error("Pyth State NFT UTxO not found"); |
| 73 | + const stateUtxo = pythUtxos[0]; |
| 74 | + |
| 75 | + // Liquidator UTxOs — for collateral; ADA reward goes to liquidator's change address. |
| 76 | + const walletUtxos: UTxO[] = await wallet.getUtxos(); |
| 77 | + const collateral: UTxO[] = await wallet.getCollateral(); |
| 78 | + if (collateral.length === 0) |
| 79 | + throw new Error("No collateral set in wallet. Enable collateral in your wallet settings."); |
| 80 | + |
| 81 | + const walletAddress = await wallet.getChangeAddress(); |
| 82 | + |
| 83 | + // ── 2. Compute amounts ──────────────────────────────────────────────────── |
| 84 | + |
| 85 | + const adaToReturn = computeBurnReturn(synthToBurn, adaUsdPrice); |
| 86 | + if (adaToReturn <= 0n) throw new Error("ADA return amount too small"); |
| 87 | + |
| 88 | + const currentPoolLovelace = BigInt( |
| 89 | + poolUtxo.output.amount.find((a) => a.unit === "lovelace")?.quantity ?? "0" |
| 90 | + ); |
| 91 | + if (adaToReturn > currentPoolLovelace) |
| 92 | + throw new Error("Insufficient ADA in pool for this liquidation amount"); |
| 93 | + |
| 94 | + const newPoolLovelace = currentPoolLovelace - adaToReturn; |
| 95 | + |
| 96 | + // ── 3. Build datums and redeemers ───────────────────────────────────────── |
| 97 | + |
| 98 | + // Preserve the existing pool datum owner from the inline datum on the pool UTxO. |
| 99 | + // In Mesh "Data" format: ByteArray is a plain hex string, Constr is mConStr0. |
| 100 | + const existingOwnerPkh = |
| 101 | + (poolUtxo.output.plutusData as any)?.fields?.[0] ?? ""; |
| 102 | + const poolDatum = mConStr0([existingOwnerPkh]); |
| 103 | + |
| 104 | + // Action.Liquidate — Constr(2, []) |
| 105 | + const liquidateRedeemer = mConStr2([]); |
| 106 | + |
| 107 | + // Pyth withdraw redeemer — List<ByteArray> with the signed price message. |
| 108 | + const pythRedeemer = [pythHex]; |
| 109 | + |
| 110 | + const col = collateral[0]; |
| 111 | + |
| 112 | + // ── 4. Build transaction ────────────────────────────────────────────────── |
| 113 | + |
| 114 | + const txBuilder = new MeshTxBuilder({ fetcher: provider, submitter: provider }); |
| 115 | + |
| 116 | + await txBuilder |
| 117 | + // Spend the pool UTxO (spend validator delegates to mint validator). |
| 118 | + .spendingPlutusScriptV3() |
| 119 | + .txIn( |
| 120 | + poolUtxo.input.txHash, |
| 121 | + poolUtxo.input.outputIndex, |
| 122 | + poolUtxo.output.amount, |
| 123 | + poolUtxo.output.address |
| 124 | + ) |
| 125 | + .txInInlineDatumPresent() |
| 126 | + .txInRedeemerValue(liquidateRedeemer, "Mesh") |
| 127 | + .txInScript(scriptCbor) |
| 128 | + |
| 129 | + // Return pool UTxO with decreased ADA + same datum. |
| 130 | + .txOut(poolAddress, [{ unit: "lovelace", quantity: newPoolLovelace.toString() }]) |
| 131 | + .txOutInlineDatumValue(poolDatum, "Mesh") |
| 132 | + |
| 133 | + // Burn synth tokens (negative mint amount). |
| 134 | + .mintPlutusScriptV3() |
| 135 | + .mint((-synthToBurn).toString(), scriptHash, "") |
| 136 | + .mintingScript(scriptCbor) |
| 137 | + .mintRedeemerValue(liquidateRedeemer, "Mesh") |
| 138 | + |
| 139 | + // Pyth State NFT as reference input (never spent). |
| 140 | + .readOnlyTxInReference(stateUtxo.input.txHash, stateUtxo.input.outputIndex) |
| 141 | + |
| 142 | + // Zero-ADA withdrawal from Pyth verify script — carries the signed price message. |
| 143 | + .withdrawal(PYTH.WITHDRAW_ADDRESS, "0") |
| 144 | + .withdrawalPlutusScriptV3() |
| 145 | + .withdrawalScript(PYTH.WITHDRAW_SCRIPT_CBOR) |
| 146 | + .withdrawalRedeemerValue(pythRedeemer, "Mesh") |
| 147 | + |
| 148 | + // Collateral + change (liquidator receives the ADA profit via change). |
| 149 | + .txInCollateral( |
| 150 | + col.input.txHash, |
| 151 | + col.input.outputIndex, |
| 152 | + col.output.amount, |
| 153 | + col.output.address |
| 154 | + ) |
| 155 | + .changeAddress(walletAddress) |
| 156 | + .selectUtxosFrom(walletUtxos) |
| 157 | + // No requiredSignerHash — liquidation is permissionless. |
| 158 | + .complete(); |
| 159 | + |
| 160 | + const unsignedTx = txBuilder.txHex; |
| 161 | + const signedTx = await wallet.signTx(unsignedTx); |
| 162 | + return wallet.submitTx(signedTx); |
| 163 | +} |
0 commit comments