Skip to content

Commit

Permalink
feat(useSendV2): add useSendV2 hook (#304)
Browse files Browse the repository at this point in the history
* feat(useSendV2): add useSendV2 hook

* fix: revert lint

* fix: lint

* chore: update to named params

* fix: useSendV2 function params
  • Loading branch information
veralygit authored May 15, 2024
1 parent 4b20d6a commit 7781a7c
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
88 changes: 88 additions & 0 deletions packages/ord-connect/src/hooks/useSendV2.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { useCallback, useState } from "react";
import { JsonRpcDatasource, PSBTBuilder } from "@ordzaar/ordit-sdk";

import signPsbt from "../lib/signPsbt";
import { useOrdConnect } from "../providers/OrdConnectProvider";

type SendFunction = (sendParams: SendParams) => Promise<SendResponse>;

type SendParams = {
toAddress: string;
satoshis: number;
feeRate: number;
relay?: boolean;
};

type SendResponse = {
txId?: string;
signedPsbtHex?: string;
error?: string;
};

export function useSendV2() {
const { wallet, network, address, publicKey } = useOrdConnect();
const [isLoading, setIsLoading] = useState<boolean>(false);

const send: SendFunction = useCallback(
async ({ toAddress, satoshis, feeRate, relay = true }: SendParams) => {
setIsLoading(true);

try {
if (
!address ||
!address.payments ||
!publicKey ||
!publicKey.payments ||
!wallet
) {
throw new Error("No wallet is connected");
}

const psbtBuilder = new PSBTBuilder({
address: address.payments,
feeRate,
network,
publicKey: publicKey.payments,
outputs: [
{
address: toAddress,
value: satoshis,
},
],
});

await psbtBuilder.prepare();

const signedPsbt = await signPsbt({
address: address.payments,
wallet,
network,
psbt: psbtBuilder.toPSBT(),
});

if (relay) {
const datasource = new JsonRpcDatasource({ network });
const txId = await datasource.relay({ hex: signedPsbt.hex });
setIsLoading(false);
return {
txId,
};
}

setIsLoading(false);

return {
signedPsbtHex: signedPsbt.hex,
};
} catch (err) {
setIsLoading(false);
return {
error: (err as Error).message,
};
}
},
[address, network, publicKey, wallet],
);

return { send, isLoading };
}
1 change: 1 addition & 0 deletions packages/ord-connect/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export { OrdConnectKit } from "./components/OrdConnectKit";
export { SelectWalletModal } from "./components/SelectWalletModal";
export { useBalance } from "./hooks/useBalance";
export { useSend } from "./hooks/useSend";
export { useSendV2 } from "./hooks/useSendV2";
export { useSign } from "./hooks/useSign";
export { useSignMessage } from "./hooks/useSignMessage";
export type {
Expand Down

0 comments on commit 7781a7c

Please sign in to comment.