Skip to content

Instantly share code, notes, and snippets.

@tobi-bams
Last active April 20, 2022 13:14
Show Gist options
  • Save tobi-bams/ab645be5a78160a0a46c58e4d27f6990 to your computer and use it in GitHub Desktop.
Save tobi-bams/ab645be5a78160a0a46c58e4d27f6990 to your computer and use it in GitHub Desktop.
Finalize PSBT transaction
const { Axios } = require("./util/index");
const GetUnspentUtxo = async () => {
try {
const response = await Axios("listunspent");
// console.log(response.data.result);
return response.data.result;
} catch (error) {
console.log(error);
throw error;
}
};
const SelectUtxos = async (amount) => {
const utxos = await GetUnspentUtxo();
const selectedUtxos = [];
let currentAmount = 0;
for (let i = 0; i < utxos.length; i++) {
let utxo = utxos[i];
let input = { txid: utxo.txid, vout: utxo.vout };
currentAmount = currentAmount + utxo.amount * 100000000;
selectedUtxos.push(input);
if (currentAmount > amount * 100000000) {
break;
}
}
return selectedUtxos;
};
const CreatePSBTTransaction = async () => {
const utxos = await SelectUtxos(0.0001);
const body = [
[...utxos],
[{ tb1qpvf0hh2fmu8pp3mkwwvp38enfwtd534p096vzy: 0.0001 }],
];
try {
const transaction = await Axios("walletcreatefundedpsbt", body);
return transaction.data.result.psbt;
} catch (error) {
throw error;
}
};
const SignPsbtTransaction = async (body) => {
const psbt = await CreatePSBTTransaction();
try {
const response = await Axios("walletprocesspsbt", [psbt]);
return response.data.result.psbt;
} catch (error) {
throw error;
}
};
const FinalizePsbt = async () => {
const body = await SignPsbtTransaction();
try {
const response = await Axios("finalizepsbt", [body]);
console.log(response.data);
} catch (error) {
throw error;
}
};
FinalizePsbt();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment