Skip to content

Commit

Permalink
feat: add send transaction hook
Browse files Browse the repository at this point in the history
Signed-off-by: Gregory Hill <[email protected]>
  • Loading branch information
gregdhill committed Sep 5, 2024
1 parent 5b1fe2c commit 07e8ebb
Show file tree
Hide file tree
Showing 7 changed files with 363 additions and 372 deletions.
1 change: 1 addition & 0 deletions packages/sats-wagmi/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export * from './useDisconnect';
export * from './useBalance';
export * from './useFeeRate';
export * from './useFeeEstimate';
export * from './useSendTransaction';
2 changes: 1 addition & 1 deletion packages/sats-wagmi/src/hooks/useAccount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const useAccount = ({ onConnect }: UseAccountProps = {}) => {
queryFn: () => {
if (!connector) return undefined;

const address = connector?.getPaymentAddress();
const address = connector.getPaymentAddress();

onConnect?.({ address, connector });

Expand Down
2 changes: 2 additions & 0 deletions packages/sats-wagmi/src/hooks/useBalance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { UseQueryOptions, useQuery } from '@tanstack/react-query';
import { EsploraClient } from '@gobob/bob-sdk';

import { useSatsWagmi } from '../provider';
import { INTERVAL } from '../utils';

import { useAccount } from './useAccount';

Expand Down Expand Up @@ -30,6 +31,7 @@ const useBalance = (props: UseBalanceProps = {}) => {

return { value: BigInt(balance) };
},
refetchInterval: INTERVAL.SECONDS_10,
...props
});
};
Expand Down
35 changes: 35 additions & 0 deletions packages/sats-wagmi/src/hooks/useSendTransaction.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useMutation, UseMutationOptions } from '@tanstack/react-query';

import { useSatsWagmi } from '../provider';

import { useAccount } from './useAccount';

type UseSendTransactionProps = Omit<
UseMutationOptions<any, unknown, { to: string; value: bigint }, unknown>,
'mutationKey' | 'mutationFn'
>;

const useSendTransaction = (props: UseSendTransactionProps = {}) => {
const { connector } = useSatsWagmi();
const { address } = useAccount();

const { mutate, mutateAsync, ...result } = useMutation({
mutationKey: ['sats-send-transaction', address],
mutationFn: async ({ to, value }: { to: string; value: bigint }) => {
if (!connector) return undefined;

const txid = await connector.sendToAddress(to, Number(value));

return txid;
},
...props
});

return {
...result,
sendTransaction: mutate,
sendTransactionAsync: mutateAsync
};
};

export { useSendTransaction };
95 changes: 49 additions & 46 deletions playgrounds/vite-react/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { formatEther } from 'viem';
import type { FormEvent } from 'react';

import { type Hex, formatUnits, parseUnits } from 'viem';
import {
// type BaseError,
useAccount,
Expand All @@ -9,14 +11,22 @@ import {
useConnect,
// useConnections,
// useConnectorClient,
useDisconnect
// useSendTransaction,
useDisconnect,
useSendTransaction
// useSignMessage,
// useSwitchAccount,
// useSwitchChain,
// useWaitForTransactionReceipt,
} from '@gobob/sats-wagmi';

function formatBtc(sats: bigint) {
return formatUnits(sats, 8);
}

function parseBtc(ether: string) {
return parseUnits(ether, 8);
}

function App() {
// useAccountEffect({
// onConnect(_data) {
Expand All @@ -37,8 +47,8 @@ function App() {
<Connections />
<BlockNumber /> */}
<Balance />
{/* <ConnectorClient />
<SendTransaction /> */}
{/* <ConnectorClient /> */}
<SendTransaction />
</>
);
}
Expand Down Expand Up @@ -173,15 +183,13 @@ function Connect() {
// }

function Balance() {
const { data: default_ } = useBalance();
const { data: account_ } = useBalance();

return (
<div>
<h2>Balance</h2>

<div>Balance (Default Chain): {!!default_?.value && formatEther(default_.value)}</div>
<div>Balance (Account Chain): {!!account_?.value && formatEther(account_.value)}</div>
<div>Balance: {!!account_?.value && formatBtc(account_.value)}</div>
</div>
);
}
Expand Down Expand Up @@ -218,46 +226,41 @@ function Balance() {
// )
// }

// function SendTransaction() {
// const { data: hash, error, isPending, sendTransaction } = useSendTransaction()
function SendTransaction() {
const { data: hash, isPending, sendTransaction } = useSendTransaction();

// async function submit(e: FormEvent<HTMLFormElement>) {
// e.preventDefault()
// const formData = new FormData(e.target as HTMLFormElement)
// const to = formData.get('address') as Hex
// const value = formData.get('value') as string
// sendTransaction({ to, value: parseEther(value) })
// }
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
const to = formData.get('address') as Hex;
const value = formData.get('value') as string;

// const { isLoading: isConfirming, isSuccess: isConfirmed } =
// useWaitForTransactionReceipt({
// hash,
// })
sendTransaction({ to, value: parseBtc(value) });
}

// return (
// <div>
// <h2>Send Transaction</h2>
// <form onSubmit={submit}>
// <input name="address" placeholder="Address" required />
// <input
// name="value"
// placeholder="Amount (ETH)"
// type="number"
// step="0.000000001"
// required
// />
// <button disabled={isPending} type="submit">
// {isPending ? 'Confirming...' : 'Send'}
// </button>
// </form>
// {hash && <div>Transaction Hash: {hash}</div>}
// {isConfirming && 'Waiting for confirmation...'}
// {isConfirmed && 'Transaction confirmed.'}
// {error && (
// <div>Error: {(error as BaseError).shortMessage || error.message}</div>
// )}
// </div>
// )
// }
// const { isLoading: isConfirming, isSuccess: isConfirmed } =
// useWaitForTransactionReceipt({
// hash,
// })

return (
<div>
<h2>Send Transaction</h2>
<form onSubmit={submit}>
<input required name='address' placeholder='Address' />
<input required name='value' placeholder='Amount (BTC)' step='0.00000001' type='number' />
<button disabled={isPending} type='submit'>
{isPending ? 'Confirming...' : 'Send'}
</button>
</form>
{hash && <div>Transaction Hash: {hash}</div>}
{/* {isConfirming && 'Waiting for confirmation...'}
{isConfirmed && 'Transaction confirmed.'} */}
{/* {error && (
<div>Error: {(error as BaseError).shortMessage || error.message}</div>
)} */}
</div>
);
}

export default App;
31 changes: 8 additions & 23 deletions playgrounds/vite-react/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,12 @@ import { nodePolyfills } from 'vite-plugin-node-polyfills';

// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
nodePolyfills({
include: ['path'],
// To exclude specific polyfills, add them to this list. Note: if include is provided, this has no effect
exclude: [
'http' // Excludes the polyfill for `http` and `node:http`.
],
// Whether to polyfill specific globals.
globals: {
Buffer: true, // can also be 'build', 'dev', or false
global: true,
process: true
},
// Override the default polyfills for specific modules.
overrides: {
// Since `fs` is not supported in browsers, we can use the `memfs` package to polyfill it.
fs: 'memfs'
},
// Whether to polyfill `node:` protocol imports.
protocolImports: true
})
]
plugins: [nodePolyfills(), react()],
build: {
target: 'esnext',
sourcemap: true, // Source map generation must be turned on,
rollupOptions: {
external: ['vite-plugin-node-polyfills/shims/buffer']
}
}
});
Loading

0 comments on commit 07e8ebb

Please sign in to comment.