|
| 1 | +import { Service } from "./service"; |
| 2 | +import type { BitcoinTx, BitcoinSignedTx, BitcoinTxHash } from "../types/bitcoin"; |
| 3 | +import api from "../api"; |
| 4 | +import { Psbt } from "bitcoinjs-lib"; |
| 5 | +import type { ServiceProps } from "../types/service"; |
| 6 | +import type { Integration } from "../types/integrations"; |
| 7 | +import { FireblocksSigner as FireblocksPsbtSigner } from "@fireblocks/psbt-sdk"; |
| 8 | + |
| 9 | +export class BabylonService extends Service { |
| 10 | + constructor({ testnet }: ServiceProps) { |
| 11 | + super({ testnet }); |
| 12 | + } |
| 13 | + |
| 14 | + /** |
| 15 | + * Craft a babylon stake transaction |
| 16 | + */ |
| 17 | + async craftStakeTx(accountId: string, publicKey: string, amountSatoshi: number, timeLock: number, feeRate: number): Promise<BitcoinTx> { |
| 18 | + const { data } = await api.post<BitcoinTx>('/v1/babylon/transaction/stake', { |
| 19 | + account_id: accountId, |
| 20 | + public_key: publicKey, |
| 21 | + amount_satoshi: amountSatoshi, |
| 22 | + time_lock: timeLock, |
| 23 | + fee_rate: feeRate, |
| 24 | + }); |
| 25 | + return data; |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Sign transaction with given integration |
| 30 | + * @param integration custody solution to sign with |
| 31 | + * @param tx raw babylon transaction |
| 32 | + * @param note note to identify the transaction in your custody solution |
| 33 | + */ |
| 34 | + async sign(integration: Integration, tx: BitcoinTx, note?: string): Promise<BitcoinSignedTx> { |
| 35 | + const fbSigner = await FireblocksPsbtSigner.create({ |
| 36 | + fireblocks: { |
| 37 | + basePath: "https://api.fireblocks.io/v1", |
| 38 | + apiKey: integration.fireblocksApiKey, |
| 39 | + secretKey: integration.fireblocksSecretKey, |
| 40 | + }, |
| 41 | + assetId: this.testnet ? "BTC_TEST" : "BTC", |
| 42 | + vaultId: integration.vaultId.toString(), |
| 43 | + addressIndex: 0, |
| 44 | + note: note ?? "BTC tx from @kilnfi/sdk", |
| 45 | + }); |
| 46 | + |
| 47 | + const psbt = Psbt.fromHex(tx.data.unsigned_tx_serialized); |
| 48 | + |
| 49 | + await psbt.signAllInputsAsync(fbSigner); |
| 50 | + |
| 51 | + psbt.finalizeAllInputs(); |
| 52 | + const signedTransaction = psbt.extractTransaction().toHex(); |
| 53 | + |
| 54 | + return { data: { signed_tx_serialized: signedTransaction } }; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Broadcast transaction to the network |
| 59 | + * @param signedTx the transaction to broadcast |
| 60 | + */ |
| 61 | + async broadcast(signedTx: BitcoinSignedTx): Promise<BitcoinTxHash> { |
| 62 | + const { data } = await api.post<BitcoinTxHash>('/v1/babylon/transaction/broadcast', { |
| 63 | + tx_serialized: signedTx.data.signed_tx_serialized, |
| 64 | + }); |
| 65 | + return data; |
| 66 | + } |
| 67 | +} |
0 commit comments