Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support OP_RETURN output for BTC transaction #3667

Merged
merged 2 commits into from
Oct 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/engine/src/vaults/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ export type ITransferInfo = {
txInterval?: string;
ignoreInscriptions?: boolean;
useCustomAddressesBalance?: boolean;
opReturn?: string;
};
export type IApproveInfo = {
from: string; // token owner
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { bytesToHex } from '@noble/hashes/utils';
import * as BitcoinJS from 'bitcoinjs-lib';

import type { SignedTx } from '@onekeyhq/engine/src/types/provider';
Expand Down Expand Up @@ -336,8 +337,15 @@ export class KeyringHardware extends KeyringHardwareBase {
private buildHardwareOutput = async (
output: TxOutput,
): Promise<Messages.TxOutputType> => {
const { isCharge, bip44Path } = output.payload || {};
const { isCharge, bip44Path, opReturn } = output.payload || {};

if (opReturn && typeof opReturn === 'string' && opReturn.length > 0) {
return {
script_type: 'PAYTOOPRETURN',
amount: '0',
op_return_data: bytesToHex(Buffer.from(opReturn)),
};
}
if (isCharge && bip44Path) {
const { getHDPath, getOutputScriptType } = await CoreSDKLoader();
const addressN = getHDPath(bip44Path);
Expand Down
36 changes: 33 additions & 3 deletions packages/engine/src/vaults/utils/btcForkChain/VaultBtcFork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -869,15 +869,32 @@ export default class VaultBtcFork extends VaultBase {
txid: txId,
value: value.toString(),
})),
outputs: outputs.map(({ value, address }) => {
outputs: outputs.map(({ value, address, script }) => {
const valueText = value?.toString();

// OP_RETURN output
if (
valueText &&
new BigNumber(valueText).eq(0) &&
!address &&
script === transferInfo.opReturn
) {
return {
address: '',
value: valueText,
payload: {
opReturn: transferInfo.opReturn,
},
};
}

// If there is no address, it should be set to the change address.
const addressOrChangeAddress = address || dbAccount.address;
if (!addressOrChangeAddress) {
throw new Error(
'buildEncodedTxFromBatchTransfer ERROR: Invalid change address',
);
}
const valueText = value?.toString();
if (!valueText || new BigNumber(valueText).lte(0)) {
throw new Error(
'buildEncodedTxFromBatchTransfer ERROR: Invalid value',
Expand Down Expand Up @@ -1934,12 +1951,25 @@ export default class VaultBtcFork extends VaultBase {
value,
},
];

if (
transferInfo.opReturn &&
typeof transferInfo.opReturn === 'string' &&
transferInfo.opReturn.length
) {
outputsForCoinSelect.push({
address: '',
value: 0,
script: transferInfo.opReturn,
});
}
}

const algorithm: ICoinSelectAlgorithm | undefined = !isBatchTransfer
? transferInfos[0].coinSelectAlgorithm
: undefined;
if (!isBatchTransfer && outputsForCoinSelect.length > 1) {
// transfer output + maybe opReturn output
if (!isBatchTransfer && outputsForCoinSelect.length > 2) {
throw new Error('single transfer should only have one output');
}
const { inputs, outputs, fee } = isNftTransfer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -608,11 +608,7 @@ class Provider {
unsignedTx: IUnsignedTxPro,
signers: { [p: string]: Signer },
) {
const {
inputs,
outputs,
payload: { opReturn },
} = unsignedTx;
const { inputs, outputs } = unsignedTx;

const [inputAddressesEncodings, nonWitnessPrevTxs] =
await this.collectInfoForSoftwareSign(unsignedTx);
Expand Down Expand Up @@ -688,22 +684,27 @@ class Provider {
}

outputs.forEach((output) => {
psbt.addOutput({
address: output.address,
value: output.value.integerValue().toNumber(),
});
const { payload } = output;
if (
payload?.opReturn &&
typeof payload?.opReturn === 'string' &&
payload?.opReturn.length > 0
) {
const embed = BitcoinJS.payments.embed({
data: [loadOPReturn(payload?.opReturn)],
});
psbt.addOutput({
script: checkIsDefined(embed.output),
value: 0,
});
} else {
psbt.addOutput({
address: output.address,
value: output.value.integerValue().toNumber(),
});
}
});

if (typeof opReturn === 'string') {
const embed = BitcoinJS.payments.embed({
data: [loadOPReturn(opReturn)],
});
psbt.addOutput({
script: checkIsDefined(embed.output),
value: 0,
});
}

return psbt;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ const loadOPReturn = (
opReturn: string,
opReturnSizeLimit: number = TX_OP_RETURN_SIZE_LIMIT,
) => {
if (opReturn.length > opReturnSizeLimit) {
throw new Error('OP_RETURN data is too large.');
}
const buffer = Buffer.from(opReturn);
return buffer.slice(0, opReturnSizeLimit);
};
Expand Down
3 changes: 2 additions & 1 deletion packages/engine/src/vaults/utils/btcForkChain/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export type IEncodedTxBtc = {
outputs: {
address: string;
value: string;
payload?: { isCharge?: boolean; bip44Path?: string };
payload?: { isCharge?: boolean; bip44Path?: string; opReturn?: string };
inscriptions?: NFTBTCAssetModel[];
}[];
feeRate: string;
Expand All @@ -119,6 +119,7 @@ export type IEncodedTxBtc = {
address: string;
value?: number;
isMax?: boolean;
script?: string;
}[];
transferInfo: ITransferInfo;
transferInfos?: ITransferInfo[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ export const coinSelect = ({
const finalOutputs = outputsForCoinSelect.map((o) => ({
address: o.address,
value: o.isMax ? undefined : o.value,
script: o.script,
}));

let unspentSelectFn = max ? coinSelectSplit : coinSelectAuto;
Expand Down