Skip to content

Commit

Permalink
feature(sats): remove usage of unsafe send (#135)
Browse files Browse the repository at this point in the history
* feature(sats): remove usage of unsafe send

* feature(sats): remove usage of unsafe send
  • Loading branch information
thedoublejay authored Nov 8, 2023
1 parent 19ff2d0 commit f9a3136
Show file tree
Hide file tree
Showing 8 changed files with 171 additions and 416 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Just two simple steps:
export default function YourReactComponent() {
return (
<OrdConnectProvider initialNetwork={"testnet"} initialSafeMode={true}>
<OrdConnectProvider initialNetwork={"testnet"}>
<OrdConnectKit />
</OrdConnectProvider>
);
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
"lint": "turbo run lint -- --fix"
},
"devDependencies": {
"@stickyjs/prettier": "^1.3.4",
"@ordzaar/standard-web-linter": "^0.3.3",
"@ordzaar/standard-prettier": "^0.3.4",
"@ordzaar/standard-web-linter": "^0.3.4",
"husky": "^8.0.3",
"turbo": "^1.10.16"
},
Expand Down
12 changes: 5 additions & 7 deletions packages/ord-connect/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,13 @@
"peerDependencies": {
"@sadoprotocol/ordit-sdk": "2.3.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"sats-connect": "^1.1.1"
"react-dom": "^18.2.0"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^25.0.7",
"@types/node": "^20.8.8",
"@types/react": "^18.2.36",
"@types/react-dom": "^18.2.14",
"@types/react": "^18.2.37",
"@types/react-dom": "^18.2.15",
"@typescript-eslint/eslint-plugin": "^6.10.0",
"@typescript-eslint/parser": "^6.10.0",
"@vitejs/plugin-react-swc": "^3.4.1",
Expand All @@ -52,15 +51,14 @@
"typescript": "^5.2.2",
"vite": "^4.5.0",
"vite-plugin-css-injected-by-js": "^3.3.0",
"vite-plugin-dts": "^2.3.0",
"vite-plugin-dts": "^3.6.3",
"vite-plugin-node-polyfills": "^0.16.0"
},
"dependencies": {
"@headlessui/react": "^1.7.17",
"@sadoprotocol/ordit-sdk": "2.3.2",
"bitcoinjs-lib": "6.1.3",
"boring-avatars": "^1.10.1",
"sats-connect": "^1.1.1"
"boring-avatars": "^1.10.1"
},
"lint-staged": {
"*": [
Expand Down
34 changes: 4 additions & 30 deletions packages/ord-connect/src/hooks/useBalance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import {
} from "@sadoprotocol/ordit-sdk";
import { useState } from "react";

import { useOrdContext, Wallet } from "../providers/OrdContext.tsx";
import { useOrdContext } from "../providers/OrdContext.tsx";

export function useBalance(): [() => Promise<number>, string | null, boolean] {
const { network, publicKey, format, safeMode, wallet } = useOrdContext();
const { network, publicKey, format } = useOrdContext();
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState<boolean>(false);

const datasource = new JsonRpcDatasource({ network });

const getSafeBalance = async (): Promise<number> => {
const getBalance = async (): Promise<number> => {
setLoading(true);
try {
setError(null);
Expand Down Expand Up @@ -47,31 +47,5 @@ export function useBalance(): [() => Promise<number>, string | null, boolean] {
}
};

const getNativeBalance = async (): Promise<number> => {
setLoading(true);
try {
setError(null);
if (!format || !publicKey) {
throw new Error("No wallet is connected");
}

if (wallet === Wallet.UNISAT) {
const unisatBalance = await window.unisat.getBalance();
setLoading(false);
return unisatBalance.confirmed;
}
if (wallet === Wallet.XVERSE) {
throw Error(
"Xverse does not support returning a balance. Turn on safeMode.",
);
}
return 0;
} catch (err: any) {
setError(err.message);
setLoading(false);
return 0; // Returning 0 as default value in case of an error
}
};

return [safeMode ? getSafeBalance : getNativeBalance, error, loading];
return [getBalance, error, loading];
}
55 changes: 4 additions & 51 deletions packages/ord-connect/src/hooks/useSend.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { JsonRpcDatasource, PSBTBuilder } from "@sadoprotocol/ordit-sdk";
import { useState } from "react";
import { BitcoinNetworkType, sendBtcTransaction } from "sats-connect";

import signPsbt from "../lib/signPsbt";
import { useOrdContext, Wallet } from "../providers/OrdContext.tsx";
import { capitalizeFirstLetter } from "../utils/text-helper";
import { useOrdContext } from "../providers/OrdContext.tsx";

type SendFunction = (
address: string,
Expand All @@ -13,13 +11,13 @@ type SendFunction = (
) => Promise<string | null>;

export function useSend(): [SendFunction, string | null, boolean] {
const { wallet, network, address, publicKey, safeMode } = useOrdContext();
const { wallet, network, address, publicKey } = useOrdContext();
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState<boolean>(false);

const datasource = new JsonRpcDatasource({ network });

const safeSend: SendFunction = async (toAddress, satoshis, feeRate) => {
const send: SendFunction = async (toAddress, satoshis, feeRate) => {
setLoading(true);
try {
setError(null);
Expand Down Expand Up @@ -59,50 +57,5 @@ export function useSend(): [SendFunction, string | null, boolean] {
}
};

const unsafeSend: SendFunction = async (toAddress, satoshis, feeRate) => {
setLoading(true);
try {
setError(null);
if (!address || !publicKey) {
throw new Error("No wallet is connected");
}

let txId;
if (wallet === Wallet.UNISAT) {
txId = await window.unisat.sendBitcoin(toAddress, satoshis, {
feeRate,
});
} else if (wallet === Wallet.XVERSE) {
const payload = {
network: {
type: capitalizeFirstLetter(network) as BitcoinNetworkType,
},
recipients: [{ address: toAddress, amountSats: BigInt(satoshis) }],
senderAddress: address.payments,
};

const xverseOptions = {
payload,
onCancel: () => {
throw Error("User rejected the request.");
},
// eslint-disable-next-line no-return-assign
onFinish: (xverseTxId) => (txId = xverseTxId),
};

await sendBtcTransaction(xverseOptions);
} else {
throw new Error("No wallet selected");
}

setLoading(false);
return txId;
} catch (err: any) {
setError(err.message);
setLoading(false);
return null;
}
};

return [safeMode ? safeSend : unsafeSend, error, loading];
return [send, error, loading];
}
2 changes: 1 addition & 1 deletion packages/ord-connect/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ function SampleComponent() {

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<OrdConnectProvider initialNetwork="testnet" initialSafeMode>
<OrdConnectProvider initialNetwork="testnet">
<SampleComponent />
<OrdConnectKit disableMobile={false} />
</OrdConnectProvider>
Expand Down
26 changes: 1 addition & 25 deletions packages/ord-connect/src/providers/OrdContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,6 @@ export enum Wallet {
XVERSE = "xverse",
}

// TO-DO: Support unsafe psbt
export enum SafeMode {
InscriptionAwareOnly,
InscriptionAndOrdinalAware,
NoSafety,
}

export interface BiAddress<T> {
payments: T | null;
ordinals: T | null;
Expand Down Expand Up @@ -51,8 +44,6 @@ interface OrdContextI {
closeModal: () => void;
format: BiAddressFormat;
updateFormat: (format: BiAddressFormat) => void;
safeMode: boolean;
updateSafeMode: (safeMode: boolean) => void;
disconnectWallet: () => void;
}

Expand All @@ -70,8 +61,6 @@ const OrdContext = createContext<OrdContextI>({
closeModal: () => {},
format: emptyBiAddressObject,
updateFormat: () => {},
safeMode: null,
updateSafeMode: () => {},
disconnectWallet: () => {},
});

Expand All @@ -80,7 +69,6 @@ const ADDRESS = "address";
const WALLET = "wallet";
const PUBLIC_KEY = "publicKey";
const FORMAT = "format";
const SAFE_MODE = "safeMode";
const NETWORK = "network";

// Helper function to get item from localStorage
Expand Down Expand Up @@ -132,13 +120,11 @@ function setItemToLocalStorage(
*
* @param {React.PropsWithChildren<any>} props - Props object.
* @param {string} [props.initialNetwork] - Initialize the internal context network state on mount.
* * @param {string} [props.initialSafeMode] - Initialize the internal context safeMode state on mount.
* @returns {JSX.Element} Provider component for OrdConnect.
*/
export function OrdConnectProvider({
children,
initialNetwork,
initialSafeMode,
}: React.PropsWithChildren<any>) {
const [address, setAddress] = useState<BiAddressString>(
() => getItemFromLocalStorage(ADDRESS) ?? emptyBiAddressObject,
Expand All @@ -148,10 +134,6 @@ export function OrdConnectProvider({
initialNetwork ?? getItemFromLocalStorage(NETWORK) ?? Network.TESTNET,
);

const [safeMode, setSafeMode] = useState<boolean>(
initialSafeMode ?? Boolean(getItemFromLocalStorage(SAFE_MODE)) ?? true,
);

const [wallet, setWallet] = useState<Wallet | null>(() =>
getItemFromLocalStorage(WALLET),
);
Expand All @@ -170,10 +152,6 @@ export function OrdConnectProvider({
useEffect(() => setItemToLocalStorage(PUBLIC_KEY, publicKey), [publicKey]);
useEffect(() => setItemToLocalStorage(FORMAT, format), [format]);
useEffect(() => setItemToLocalStorage(NETWORK, network), [network]);
useEffect(
() => setItemToLocalStorage(SAFE_MODE, safeMode.toString()),
[safeMode],
);

function disconnectWallet() {
setAddress(emptyBiAddressObject);
Expand All @@ -197,11 +175,9 @@ export function OrdConnectProvider({
closeModal: () => setIsModalOpen(false),
format,
updateFormat: setFormat,
safeMode,
updateSafeMode: setSafeMode,
disconnectWallet,
}),
[address, publicKey, network, isModalOpen, format, safeMode],
[address, publicKey, network, isModalOpen, format],
);

return <OrdContext.Provider value={context}>{children}</OrdContext.Provider>;
Expand Down
Loading

0 comments on commit f9a3136

Please sign in to comment.