UNPKG

blub-sdk

Version:

A modular SDK for interacting with the BLUB ecosystem on the Sui blockchain.

69 lines (68 loc) 2.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mintZeroCoin = mintZeroCoin; exports.buildInputCoin = buildInputCoin; const CoinAssist_1 = require("./CoinAssist"); function mintZeroCoin(txb, coinType) { return txb.moveCall({ target: "0x2::coin::zero", typeArguments: [coinType], }); } function buildInputCoin(txb, allCoins, amount, coinType) { const usedCoinAsests = CoinAssist_1.CoinUtils.getCoinAssets(coinType, allCoins); if (amount === BigInt(0)) { if (CoinAssist_1.CoinUtils.isSuiCoin(coinType) || (usedCoinAsests.length === 0 && !CoinAssist_1.CoinUtils.isSuiCoin(coinType))) { const zeroCoin = mintZeroCoin(txb, coinType); return { targetCoin: zeroCoin, isMintZeroCoin: true, targetCoinAmount: 0, }; } else { return { targetCoin: txb.object(usedCoinAsests[0].coinObjectId), isMintZeroCoin: false, targetCoinAmount: Number(usedCoinAsests[0].balance.toString()), }; } } const totalCoinBalance = CoinAssist_1.CoinUtils.calculateTotalBalance(usedCoinAsests); if (totalCoinBalance < amount) { throw new Error("Insufficient balance when build merge coin, coinType: " + coinType); } if (CoinAssist_1.CoinUtils.isSuiCoin(coinType)) { const resultCoin = txb.splitCoins(txb.gas, [ txb.pure.u64(amount.toString()), ]); return { targetCoin: resultCoin, isMintZeroCoin: true, targetCoinAmount: Number(amount.toString()), }; } // sort used coin by amount, asc let sortCoinAssets = CoinAssist_1.CoinUtils.sortByBalance(usedCoinAsests); // find first three coin if greater than amount const totalThreeCoinBalance = sortCoinAssets .slice(0, 3) .reduce((acc, coin) => acc + coin.balance, BigInt(0)); if (totalThreeCoinBalance < BigInt(amount)) { sortCoinAssets = CoinAssist_1.CoinUtils.sortByBalanceDes(usedCoinAsests); } const selectedCoinResult = CoinAssist_1.CoinUtils.selectCoinObjectIdGreaterThanOrEqual(sortCoinAssets, amount); const [masterCoin, ...mergedCoin] = selectedCoinResult.objectArray; if (mergedCoin.length > 0) { txb.mergeCoins(masterCoin, mergedCoin.map((coin) => txb.object(coin))); } const targetCoin = txb.splitCoins(txb.object(masterCoin), [ txb.pure.u64(amount.toString()), ]); return { targetCoin, isMintZeroCoin: false, targetCoinAmount: Number(amount.toString()), }; }