Skip to content

Commit

Permalink
feat: convert encoded tx to psbt hex
Browse files Browse the repository at this point in the history
  • Loading branch information
originalix committed May 24, 2024
1 parent c1f9033 commit 9412393
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 38 deletions.
100 changes: 76 additions & 24 deletions packages/engine/src/vaults/utils/btcForkChain/VaultBtcFork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ import {
coinSelectForOrdinal,
getAccountDefaultByPurpose,
getBIP44Path,
initBitcoinEcc,
} from './utils';

import type { ExportedPrivateKeyCredential } from '../../../dbs/base';
Expand Down Expand Up @@ -1062,30 +1063,31 @@ export default class VaultBtcFork extends VaultBase {
override async broadcastTransaction(
signedTx: ISignedTxPro,
): Promise<ISignedTxPro> {
debugLogger.engine.info('broadcastTransaction START:', {
rawTx: signedTx.rawTx,
});
const provider = await this.getProvider();
const txid = await provider.broadcastTransaction(signedTx.rawTx);
debugLogger.engine.info('broadcastTransaction END:', {
txid,
rawTx: signedTx.rawTx,
});

const { inputs } = (signedTx.encodedTx as IEncodedTxBtc) ?? { inputs: [] };

const utoxIds = inputs.map((input) => getUtxoId(this.networkId, input));

try {
await simpleDb.utxoAccounts.deleteCoinControlItem(utoxIds);
} catch {
// pass
}

return {
...signedTx,
txid,
};
throw new NotImplemented();
// debugLogger.engine.info('broadcastTransaction START:', {
// rawTx: signedTx.rawTx,
// });
// const provider = await this.getProvider();
// const txid = await provider.broadcastTransaction(signedTx.rawTx);
// debugLogger.engine.info('broadcastTransaction END:', {
// txid,
// rawTx: signedTx.rawTx,
// });

// const { inputs } = (signedTx.encodedTx as IEncodedTxBtc) ?? { inputs: [] };

// const utoxIds = inputs.map((input) => getUtxoId(this.networkId, input));

// try {
// await simpleDb.utxoAccounts.deleteCoinControlItem(utoxIds);
// } catch {
// // pass
// }

// return {
// ...signedTx,
// txid,
// };
}

override async getTransactionStatuses(
Expand Down Expand Up @@ -2209,4 +2211,54 @@ export default class VaultBtcFork extends VaultBase {
data: serviceData as NFTBTCAssetModel[],
});
}

async convertEncodedTxToPsbt(params: { encodedTx: IEncodedTxBtc }) {
initBitcoinEcc();
const { encodedTx } = params;
const { inputs, outputs, totalFee } = encodedTx;
const utxos = await this.getAccountUtxos(encodedTx.inputs);
const provider = await this.getProvider();
const psbt = provider.getPsbt();
let inputsSum = 0;
for (let i = 0; i < inputs.length; i += 1) {
const input = utxos[i];
psbt.addInput({
hash: input.txid,
index: input.vout,
witnessUtxo: {
script: Buffer.from(input.scriptPubKey, 'hex'),
value: input.value,
},
});
inputsSum += input.value;
}

console.log('===>inputsSum: ', inputsSum);

for (const output of outputs) {
const { address, value } = output;
psbt.addOutput({
address,
value: new BigNumber(value).toNumber(),
});
}

return psbt.toHex();
}

async getAccountUtxos(utxos: IBtcUTXO[]) {
const result = [];
const client = await (await this.getProvider()).blockbook;
for (const utxo of utxos) {
const txDetails = await client.getTransactionDetail(utxo.txid);
result.push({
txid: utxo.txid,
vout: utxo.vout,
value: new BigNumber(utxo.value).toNumber(),
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
scriptPubKey: txDetails?.vout?.[utxo.vout].hex ?? '',
});
}
return result;
}
}
1 change: 1 addition & 0 deletions packages/kit-bg/src/providers/ProviderApiBtc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { isNil } from 'lodash';

import { getFiatEndpoint } from '@onekeyhq/engine/src/endpoint';
import type { NFTBTCAssetModel } from '@onekeyhq/engine/src/types/nft';
import type { IBtcUTXO } from '@onekeyhq/engine/src/vaults/utils/btcForkChain/types';
import type VaultBtcFork from '@onekeyhq/engine/src/vaults/utils/btcForkChain/VaultBtcFork';
import { getActiveWalletAccount } from '@onekeyhq/kit/src/hooks';
import {
Expand Down
18 changes: 18 additions & 0 deletions packages/kit-bg/src/services/ServiceInscribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1131,4 +1131,22 @@ export default class ServiceInscribe extends ServiceBase {
// noop
}
}

@backgroundMethod()
async convertEncodedTxToPsbt({
encodedTx,
networkId,
accountId,
}: {
encodedTx: IEncodedTxBtc;
networkId: string;
accountId: string;
}) {
const vault = (await this.backgroundApi.engine.getVault({
networkId,
accountId,
})) as VaultBtcFork;
const psbt = vault.convertEncodedTxToPsbt({ encodedTx });
return psbt;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,13 @@ import {
ETHMessageTypes,
getEthProviderMethodFromMessageType,
} from '@onekeyhq/engine/src/types/message';
import type {
IEncodedTxBtc,
IUnsignedMessageBtc,
} from '@onekeyhq/engine/src/vaults/impl/btc/types';
import type { IUnsignedMessageBtc } from '@onekeyhq/engine/src/vaults/impl/btc/types';
import type {
IEncodedTxEvm,
IUnsignedMessageEvm,
} from '@onekeyhq/engine/src/vaults/impl/evm/Vault';
import type { IEncodedTx } from '@onekeyhq/engine/src/vaults/types';
import type { IEncodedTxBtc } from '@onekeyhq/engine/src/vaults/utils/btcForkChain/types';
import { OnekeyNetwork } from '@onekeyhq/shared/src/config/networkIds';
import { isBTCNetwork } from '@onekeyhq/shared/src/engine/engineConsts';
import debugLogger from '@onekeyhq/shared/src/logger/debugLogger';
Expand Down Expand Up @@ -167,6 +165,7 @@ export function useSignOrSendOfExternalAccount({
export function useSignOrSendOfBtcExternalAccount({
encodedTx,
networkId,
accountId,
}: {
encodedTx: IEncodedTx | undefined;
sourceInfo?: IDappSourceInfo | undefined;
Expand All @@ -186,17 +185,15 @@ export function useSignOrSendOfBtcExternalAccount({
if (!tx) {
throw new Error('encodedTx is missing!');
}
const psbtHex =
await backgroundApiProxy.serviceInscribe.convertEncodedTxToPsbt({
encodedTx: tx,
accountId,
networkId,
});
const result =
await window.$onekey.$privateExternalAccount?.btc_signTransaction({
encodedTx: {
inputs: tx.inputs,
outputs: tx.outputs,
// @ts-expect-error
inputsForCoinSelect: tx.inputsForCoinSelect,
// @ts-expect-error
outputsForCoinSelect: tx.outputsForCoinSelect,
fee: tx.totalFee,
},
psbtHex,
network:
currentNetwork.id === OnekeyNetwork.btc ? 'mainnet' : 'testnet',
});
Expand All @@ -205,7 +202,7 @@ export function useSignOrSendOfBtcExternalAccount({
rawTx: result.rawTx,
encodedTx,
};
}, [encodedTx, networkId, engine]);
}, [encodedTx, networkId, accountId, engine]);

return {
sendTxForBtcExternalAccount,
Expand Down

0 comments on commit 9412393

Please sign in to comment.