hm-aftermath-ts-sdk
Version:
Aftermath TypeScript SDK
279 lines (278 loc) • 11.7 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransactionsApiHelpers = void 0;
const transactions_1 = require("@mysten/sui/transactions");
const utils_1 = require("../utils");
class TransactionsApiHelpers {
// =========================================================================
// Constructor
// =========================================================================
constructor(Provider) {
this.Provider = Provider;
// =========================================================================
// Public Methods
// =========================================================================
// =========================================================================
// Fetching
// =========================================================================
this.fetchTransactionsWithCursor = (inputs) => __awaiter(this, void 0, void 0, function* () {
var _a;
const { query, cursor, limit } = inputs;
const transactionsWithCursor = yield this.Provider.provider.queryTransactionBlocks(Object.assign(Object.assign({}, query), { cursor,
limit, options: {
showEvents: true,
showBalanceChanges: true,
showEffects: true,
showObjectChanges: true,
showInput: true,
} }));
return {
transactions: transactionsWithCursor.data,
nextCursor: (_a = transactionsWithCursor.nextCursor) !== null && _a !== void 0 ? _a : null,
};
});
this.fetchSetGasBudgetForTx = (inputs) => __awaiter(this, void 0, void 0, function* () {
const { tx } = inputs;
const [txResponse, referenceGasPrice] = yield Promise.all([
this.Provider.provider.dryRunTransactionBlock({
transactionBlock: yield tx.build({
client: this.Provider.provider,
}),
}),
this.Provider.provider.getReferenceGasPrice(),
]);
const gasData = txResponse.effects.gasUsed;
const gasUsed = BigInt(gasData.computationCost) + BigInt(gasData.storageCost);
// scale up by 10% for safety margin
const safeGasBudget = gasUsed + gasUsed / BigInt(10);
tx.setGasBudget(safeGasBudget);
tx.setGasPrice(referenceGasPrice);
return tx;
});
this.fetchSetGasBudgetForTxV0 = (inputs) => __awaiter(this, void 0, void 0, function* () {
var _b;
const { tx } = inputs;
const [txResponse, referenceGasPrice] = yield Promise.all([
(_b = this.Provider.providerV0) === null || _b === void 0 ? void 0 : _b.dryRunTransactionBlock({
transactionBlock: yield tx.build({
client: this.Provider.providerV0,
}),
}),
this.Provider.provider.getReferenceGasPrice(),
]);
const gasUsed = !txResponse
? // TODO: make this into larger val
BigInt(0)
: (() => {
const gasData = txResponse.effects.gasUsed;
return (BigInt(gasData.computationCost) +
BigInt(gasData.storageCost));
})();
// scale up by 10% for safety margin
const safeGasBudget = gasUsed + gasUsed / BigInt(10);
tx.setGasBudget(safeGasBudget);
tx.setGasPrice(referenceGasPrice);
return tx;
});
this.fetchSetGasBudgetAndSerializeTx = (inputs) => __awaiter(this, void 0, void 0, function* () {
const { tx, isSponsoredTx } = inputs;
if (isSponsoredTx)
return (yield tx).serialize();
return (yield this.fetchSetGasBudgetForTx({ tx: yield tx })).serialize();
});
this.fetchSetGasBudgetAndSerializeTxV0 = (inputs) => __awaiter(this, void 0, void 0, function* () {
const { tx, isSponsoredTx } = inputs;
if (isSponsoredTx)
return (yield tx).serialize();
return (yield this.fetchSetGasBudgetForTxV0({ tx: yield tx })).serialize();
});
}
static splitCoinTx(inputs) {
const { tx, coinType, coinId, amount } = inputs;
return tx.moveCall({
target: this.createTxTarget(
// Sui.constants.addresses.suiPackageId,
"0x2", "coin", "split"),
typeArguments: [coinType],
arguments: [
typeof coinId === "string" ? tx.object(coinId) : coinId,
tx.pure.u64(amount), // split_amount
],
});
}
}
exports.TransactionsApiHelpers = TransactionsApiHelpers;
// =========================================================================
// Public Static Methods
// =========================================================================
// =========================================================================
// Helpers
// =========================================================================
TransactionsApiHelpers.createTxTarget = (packageAddress, packageName, functionName) => `${packageAddress}::${packageName}::${functionName}`;
TransactionsApiHelpers.createBuildTxFunc = (func) => {
const builderFunc = (someInputs) => {
const tx = new transactions_1.Transaction();
tx.setSender(someInputs.walletAddress);
func(Object.assign({ tx }, someInputs));
return tx;
};
return builderFunc;
};
TransactionsApiHelpers.serviceCoinDataFromCoinTxArg = (inputs) => {
const { coinTxArg } = inputs;
if (typeof coinTxArg === "string")
return { Coin: utils_1.Helpers.addLeadingZeroesToType(coinTxArg) };
if (!("$kind" in coinTxArg)) {
if (typeof coinTxArg === "function" || "GasCoin" in coinTxArg)
throw new Error("unable to convert gas coin arg to service coin data");
// Input
return coinTxArg;
}
if (coinTxArg.$kind === "NestedResult")
return {
[coinTxArg.$kind]: coinTxArg.NestedResult,
};
if (coinTxArg.$kind === "Result")
return { [coinTxArg.$kind]: coinTxArg.Result };
if (coinTxArg.$kind === "GasCoin")
throw new Error("unable to convert gas coin arg to service coin data");
// Input
return { [coinTxArg.$kind]: coinTxArg.Input };
};
TransactionsApiHelpers.serviceCoinDataFromCoinTxArgV0 = (inputs) => {
const { coinTxArg } = inputs;
if (typeof coinTxArg === "string")
return { Coin: utils_1.Helpers.addLeadingZeroesToType(coinTxArg) };
if (coinTxArg.kind === "NestedResult")
return {
[coinTxArg.kind]: [coinTxArg.index, coinTxArg.resultIndex],
};
if (coinTxArg.kind === "Result")
return { [coinTxArg.kind]: coinTxArg.index };
// Input
return { [coinTxArg.kind]: coinTxArg.index };
};
TransactionsApiHelpers.coinTxArgFromServiceCoinData = (inputs) => {
const { serviceCoinData } = inputs;
const key = Object.keys(serviceCoinData)[0];
// TODO: handle all cases
if (key === "Coin")
throw new Error("serviceCoinData in format { Coin: ObjectId } not supported");
// TODO: handle this cleaner
const kind = key;
if (kind === "NestedResult") {
return {
NestedResult: Object.values(serviceCoinData)[0],
};
}
if (kind === "Input") {
return {
Input: Object.values(serviceCoinData)[0],
};
}
return {
Result: Object.values(serviceCoinData)[0],
};
};
TransactionsApiHelpers.coinTxArgFromServiceCoinDataV0 = (inputs) => {
const { serviceCoinData } = inputs;
const key = Object.keys(serviceCoinData)[0];
// TODO: handle all cases
if (key === "Coin")
throw new Error("serviceCoinData in format { Coin: ObjectId } not supported");
// TODO: handle this cleaner
const kind = key;
if (kind === "NestedResult") {
return {
kind,
index: Object.values(serviceCoinData)[0][0],
resultIndex: Object.values(serviceCoinData)[0][1],
};
}
return {
kind,
index: Object.values(serviceCoinData)[0],
};
};
// public static mergeCoinsTx(inputs: {
// tx: Transaction;
// coinType: CoinType;
// destinationCoinId: TransactionArgument | string;
// sources: TransactionArgument[] | ObjectId[];
// }) {
// const { tx, coinType, destinationCoinId, sources } = inputs;
// // TODO: clean this up
// const coinVec =
// typeof sources[0] === "string"
// ? tx.makeMoveVec({
// objects: sources.map((source) =>
// tx.object(source as ObjectId)
// ),
// type: `Coin<${coinType}>`,
// })
// : sources;
// return tx.moveCall({
// target: this.createTxTarget(
// Sui.constants.addresses.suiPackageId,
// "pay",
// "join_vec"
// ),
// typeArguments: [coinType],
// arguments: [
// typeof destinationCoinId === "string"
// ? tx.object(destinationCoinId)
// : destinationCoinId, // Coin,
// // TODO: clean this up
// // @ts-ignore
// coinVec, // coins
// ],
// });
// }
TransactionsApiHelpers.transferTxMetadata = (inputs) => {
const { initTx, newTx } = inputs;
const sender = initTx.getData().sender;
if (sender)
newTx.setSender(sender);
const expiration = initTx.getData().expiration;
if (expiration)
newTx.setExpiration(expiration);
const gasData = initTx.getData().gasData;
if (gasData.budget && typeof gasData.budget !== "string")
newTx.setGasBudget(gasData.budget);
if (gasData.owner)
newTx.setGasOwner(gasData.owner);
if (gasData.payment)
newTx.setGasPayment(gasData.payment);
if (gasData.price && typeof gasData.price !== "string")
newTx.setGasPrice(gasData.price);
};
TransactionsApiHelpers.transferTxMetadataV0 = (inputs) => {
const { initTx, newTx } = inputs;
const sender = initTx.blockData.sender;
if (sender)
newTx.setSender(sender);
const expiration = initTx.blockData.expiration;
if (expiration && !("None" in expiration && expiration.None === null))
// @ts-ignore
newTx.setExpiration(expiration);
const gasData = initTx.blockData.gasConfig;
if (gasData.budget && typeof gasData.budget !== "string")
newTx.setGasBudget(gasData.budget);
if (gasData.owner)
newTx.setGasOwner(gasData.owner);
if (gasData.payment)
newTx.setGasPayment(gasData.payment.map((payment) => (Object.assign(Object.assign({}, payment), { version: typeof payment.version === "bigint"
? Number(payment.version)
: payment.version }))));
if (gasData.price && typeof gasData.price !== "string")
newTx.setGasPrice(gasData.price);
};