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

react waas demo to use contract call for 'runSendTransaction', and re… #29

Closed
wants to merge 5 commits into from
Closed
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
3 changes: 2 additions & 1 deletion examples/react-waas/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
"version": "0.2.0",
"type": "module",
"scripts": {
"start": "vite --port 4444",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this must be port 4444 or else the auth won't work

"start": "vite --port 3000",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"0xsequence": "^1.9.19",
"@0xsequence/kit": "workspace:*",
"@0xsequence/kit-checkout": "workspace:*",
"@tanstack/react-query": "^5.32.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand Down
4 changes: 3 additions & 1 deletion examples/react-waas/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import './App.css'
import { useOpenConnectModal, useWaasFeeOptions } from '@0xsequence/kit'
import { useOpenConnectModal, useWaasFeeOptions, useWaasRevalidation } from '@0xsequence/kit'
import {
useAccount,
useChainId,
Expand Down Expand Up @@ -105,6 +105,8 @@ export const App = () => {
}
}, [txnData])

useWaasRevalidation()

// Fee options are required when txn is not gas sponsored (not needed on testnets)
const [pendingFeeOptionConfirmation, confirmPendingFeeOption, rejectPendingFeeOption] = useWaasFeeOptions()

Expand Down
6 changes: 4 additions & 2 deletions examples/react-waas/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ const queryClient = new QueryClient()
const chains: readonly [Chain, ...Chain[]] = [arbitrumNova as Chain, arbitrumSepolia as Chain, mainnet as Chain, polygon as Chain]

// replace with your keys, and better to use env vars
const projectAccessKey = 'T3czhtWsTONJpbjFgAdLAuEAAAAAAAAA'
const waasConfigKey = 'eyJwcm9qZWN0SWQiOjc1LCJycGNTZXJ2ZXIiOiJodHRwczovL3dhYXMuc2VxdWVuY2UuYXBwIn0='
// const projectAccessKey = 'T3czhtWsTONJpbjFgAdLAuEAAAAAAAAA'
const projectAccessKey = 'AQAAAAAAAAK2JvvZhWqZ51riasWBftkrVXE'
// const waasConfigKey = 'eyJwcm9qZWN0SWQiOjc1LCJycGNTZXJ2ZXIiOiJodHRwczovL3dhYXMuc2VxdWVuY2UuYXBwIn0='
const waasConfigKey = 'eyJwcm9qZWN0SWQiOjY5NCwicnBjU2VydmVyIjoiaHR0cHM6Ly9kZXYtd2Fhcy5zZXF1ZW5jZS5hcHAiLCJlbWFpbFJlZ2lvbiI6ImNhLWNlbnRyYWwtMSIsImVtYWlsQ2xpZW50SWQiOiI1NGF0bjV1cGk2M3FjNTlhMWVtM3ZiaHJzbiJ9'
const googleClientId = '603294233249-6h5saeg2uiu8akpcbar3r2aqjp6j7oem.apps.googleusercontent.com'
// const appleClientId =
// const appleRedirectURI = 'https://' + window.location.host
Expand Down
121 changes: 72 additions & 49 deletions examples/react/src/components/Homepage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,11 @@ import {
import { allNetworks } from '@0xsequence/network'
import { Footer } from './Footer'
import { messageToSign } from '../constants'
import { delay, formatAddress, getCheckoutSettings } from '../utils'
import { abi } from '../constants/nft-abi'
import { delay, formatAddress, getCheckoutSettings } from '../utils'
import { sequence } from '0xsequence'
import demoAbi from '../constants/demo-abi'
import { ethers } from 'ethers'
import { Alert, AlertProps } from './Alert'
import { ConnectionMode } from '../config'
import { formatUnits, parseUnits } from 'viem'
Expand All @@ -69,8 +72,8 @@ export const Homepage = () => {

const isMobile = useMediaQuery('isMobile')

const { data: txnData, sendTransaction, isPending: isPendingSendTxn, error } = useSendTransaction()
const { data: txnData2, isPending: isPendingMintTxn, writeContract } = useWriteContract()
const { data: txnData, sendTransaction, isLoading: isPendingSendTxn, error } = useSendTransaction()
const { data: txnData2, isLoading: isPendingMintTxn, writeContract } = useWriteContract()

const [isSigningMessage, setIsSigningMessage] = React.useState(false)
const [isMessageValid, setIsMessageValid] = React.useState<boolean | undefined>()
Expand All @@ -83,15 +86,15 @@ export const Homepage = () => {
localStorage.getItem('confirmationEnabled') === 'true'
)

const [pendingFeeOptionConfirmation, confirmPendingFeeOption, rejectPendingFeeOption] = useWaasFeeOptions()
// const [pendingFeeOptionConfirmation, confirmPendingFeeOption, rejectPendingFeeOption] = useWaasFeeOptions()

const [selectedFeeOptionTokenName, setSelectedFeeOptionTokenName] = React.useState<string | undefined>()
// const [selectedFeeOptionTokenName, setSelectedFeeOptionTokenName] = React.useState<string | undefined>()

useEffect(() => {
if (pendingFeeOptionConfirmation) {
setSelectedFeeOptionTokenName(pendingFeeOptionConfirmation.options[0].token.name)
}
}, [pendingFeeOptionConfirmation])
// useEffect(() => {
// if (pendingFeeOptionConfirmation) {
// setSelectedFeeOptionTokenName(pendingFeeOptionConfirmation.options[0].token.name)
// }
// }, [pendingFeeOptionConfirmation])

useEffect(() => {
console.log(error?.message)
Expand All @@ -101,13 +104,13 @@ export const Homepage = () => {

const { indexerClient } = getNetworkConfigAndClients(chainId)

const [feeOptionBalances, setFeeOptionBalances] = React.useState<{ tokenName: string; decimals: number; balance: string }[]>([])
// const [feeOptionBalances, setFeeOptionBalances] = React.useState<{ tokenName: string; decimals: number; balance: string }[]>([])

const [feeOptionAlert, setFeeOptionAlert] = React.useState<AlertProps | undefined>(undefined)
// const [feeOptionAlert, setFeeOptionAlert] = React.useState<AlertProps | undefined>(undefined)

useEffect(() => {
checkTokenBalancesForFeeOptions()
}, [pendingFeeOptionConfirmation])
// useEffect(() => {
// checkTokenBalancesForFeeOptions()
// }, [pendingFeeOptionConfirmation])

const handleSwitchConnectionMode = (mode: ConnectionMode) => {
const searchParams = new URLSearchParams()
Expand All @@ -116,36 +119,36 @@ export const Homepage = () => {
window.location.search = searchParams.toString()
}

const checkTokenBalancesForFeeOptions = async () => {
if (pendingFeeOptionConfirmation) {
const [account] = await walletClient.getAddresses()
const nativeTokenBalance = await indexerClient.getEtherBalance({ accountAddress: account })

const tokenBalances = await indexerClient.getTokenBalances({
accountAddress: account
})

console.log('feeOptions', pendingFeeOptionConfirmation.options)
console.log('nativeTokenBalance', nativeTokenBalance)
console.log('tokenBalances', tokenBalances)

const balances = pendingFeeOptionConfirmation.options.map(option => {
if (option.token.contractAddress === null) {
return { tokenName: option.token.name, decimals: option.token.decimals, balance: nativeTokenBalance.balance.balanceWei }
} else {
return {
tokenName: option.token.name,
decimals: option.token.decimals,
balance:
tokenBalances.balances.find(b => b.contractAddress.toLowerCase() === option.token.contractAddress.toLowerCase())
?.balance || '0'
}
}
})

setFeeOptionBalances(balances)
}
}
// const checkTokenBalancesForFeeOptions = async () => {
// if (pendingFeeOptionConfirmation) {
// const [account] = await walletClient.getAddresses()
// const nativeTokenBalance = await indexerClient.getEtherBalance({ accountAddress: account })

// const tokenBalances = await indexerClient.getTokenBalances({
// accountAddress: account
// })

// console.log('feeOptions', pendingFeeOptionConfirmation.options)
// console.log('nativeTokenBalance', nativeTokenBalance)
// console.log('tokenBalances', tokenBalances)

// const balances = pendingFeeOptionConfirmation.options.map(option => {
// if (option.token.contractAddress === null) {
// return { tokenName: option.token.name, decimals: option.token.decimals, balance: nativeTokenBalance.balance.balanceWei }
// } else {
// return {
// tokenName: option.token.name,
// decimals: option.token.decimals,
// balance:
// tokenBalances.balances.find(b => b.contractAddress.toLowerCase() === option.token.contractAddress.toLowerCase())
// ?.balance || '0'
// }
// }
// })

// setFeeOptionBalances(balances)
// }
// }

const networkForCurrentChainId = allNetworks.find(n => n.chainId === chainId)

Expand Down Expand Up @@ -215,13 +218,33 @@ export const Homepage = () => {
}

const runSendTransaction = async () => {
// NOTE: commented code is how to send ETH value to the account
// if (!walletClient) {
// return
// }
// const [account] = await walletClient.getAddresses()
// sendTransaction({ to: account, value: '0', gas: null })

// NOTE: below is a a simple contract call. See `runMintNFT`
// on another example where you can use the wagmi `writeContract`
// method to do the same thing.
if (!walletClient) {
return
}

const [account] = await walletClient.getAddresses()
const contractAbiInterface = new ethers.utils.Interface([
'function demo()'
])

sendTransaction({ to: account, value: '0', gas: null })
const data = contractAbiInterface.encodeFunctionData(
'demo', []
)

sendTransaction({
to: '0x37470dac8a0255141745906c972e414b1409b470',
data,
gas: null
})
}

const runMintNFT = async () => {
Expand Down Expand Up @@ -445,7 +468,7 @@ export const Homepage = () => {
/>
</Box>

{pendingFeeOptionConfirmation && feeOptionBalances.length > 0 && (
{/* {pendingFeeOptionConfirmation && feeOptionBalances.length > 0 && (
<Box marginY="3">
<Select
name="feeOption"
Expand Down Expand Up @@ -525,7 +548,7 @@ export const Homepage = () => {
)}
</Box>
</Box>
)}
)} */}

{isWaasConnection && (
<Box marginY="3">
Expand Down
19 changes: 19 additions & 0 deletions examples/react/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ chains.forEach(chain => {
transports[chain.id] = http(network.rpcUrl)
})

/// Use this to test the waas connectors
// WaaS config
const waasConfigKey = 'eyJwcm9qZWN0SWQiOjE2ODE1LCJycGNTZXJ2ZXIiOiJodHRwczovL3dhYXMuc2VxdWVuY2UuYXBwIn0='
const googleClientId = '970987756660-35a6tc48hvi8cev9cnknp0iugv9poa23.apps.googleusercontent.com'
const appleClientId = 'com.horizon.sequence.waas'
Expand Down Expand Up @@ -83,6 +85,23 @@ const getUniversalConnectors = () => {
return connectors
}

/// Use this to test the universal connectors
// const connectors = [
// ...getDefaultConnectors({
// walletConnectProjectId: 'c65a6cb1aa83c4e24500130f23a437d8',
// defaultChainId: arbitrumNova.id,
// appName: 'demo app',
// projectAccessKey
// }),
// ...(isDebugMode
// ? getKitConnectWallets(projectAccessKey, [
// mock({
// accounts: ['0xCb88b6315507e9d8c35D81AFB7F190aB6c3227C9']
// })
// ])
// : [])
// ]

export const wagmiConfig = createConfig({
transports,
chains,
Expand Down
11 changes: 11 additions & 0 deletions examples/react/src/constants/demo-abi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const abi = [
{
name: 'demo',
inputs: [],
outputs: [],
stateMutability: 'nonpayable',
type: 'function'
}
]

export default abi
2 changes: 1 addition & 1 deletion examples/react/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default defineConfig(() => {
},
server: {
minify: false,
port: 4444,
port: 3000,
fs: {
// Allow serving files from one level up to the project root
allow: ['..']
Expand Down
1 change: 1 addition & 0 deletions packages/connectors/src/connectors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ export * from './mock'
export * from './sequence'
export * from './twitch'
export * from './walletConnect'
export * from './wagmiConnectors'
export * from './types'
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SequenceWaaS, SequenceConfig, ExtendedSequenceConfig, Transaction, FeeOption } from '@0xsequence/waas'
import { LocalStorageKey } from '@0xsequence/kit'
import { TransactionRejectedRpcError, UserRejectedRequestError, getAddress } from 'viem'
import { createConnector } from 'wagmi'
import { createConnector, CreateConnectorFn } from 'wagmi'
import { ethers } from 'ethers'
import { v4 as uuidv4 } from 'uuid'
import { sequence } from '0xsequence'
Expand All @@ -18,7 +18,9 @@ export type BaseSequenceWaasConnectorOptions = SequenceConfig & SequenceWaasConn

sequenceWaasWallet.type = 'sequence-waas' as const

export function sequenceWaasWallet(params: BaseSequenceWaasConnectorOptions) {
export type SequenceWaasConnector = CreateConnectorFn<SequenceWaasProvider, any, {}>

export function sequenceWaasWallet(params: BaseSequenceWaasConnectorOptions): SequenceWaasConnector {
type Provider = SequenceWaasProvider
type Properties = { sequenceWaas: SequenceWaaS; sequenceWaasProvider: SequenceWaasProvider }

Expand Down
2 changes: 1 addition & 1 deletion packages/connectors/src/defaultConnectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export const getDefaultWaasConnectors = ({
enableConfirmationModal
}: GetDefaultWaasConnectors): CreateConnectorFn[] => {
const wallets: any[] = [
// emailWaas({ projectAccessKey, waasConfigKey, enableConfirmationModal, network: defaultChainId }),
emailWaas({ projectAccessKey, waasConfigKey, enableConfirmationModal, network: defaultChainId }),
coinbaseWallet({
appName
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,16 @@ export const ConnectWalletContent = (props: ConnectWalletContentProps) => {

<Box marginTop="6">
{emailConnector && showEmailInput && (
<form onSubmit={onConnectInlineEmail}>
<TextInput onChange={onChangeEmail} value={email} name="email" placeholder="Enter email" data-1p-ignore />
<Box as="form" onSubmit={onConnectInlineEmail}>
<Box style={{ width: 'calc(100% - 32px)' }}>
<TextInput
onChange={onChangeEmail}
value={email}
name="email"
placeholder="Enter email"
data-1p-ignore
/>
</Box>
<Box alignItems="center" justifyContent="center" marginTop="4">
{!emailAuthInProgress && (
<Button
Expand All @@ -240,7 +248,7 @@ export const ConnectWalletContent = (props: ConnectWalletContentProps) => {
)}
{emailAuthInProgress && <Spinner />}
</Box>
</form>
</Box>
)}

{socialAuthConnectors.length > 0 && (
Expand Down
4 changes: 2 additions & 2 deletions packages/kit/src/components/styles.css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ globalStyle(`${googleWaasButtonContainer}`, {
export const digitInput = style([
textVariants({ variant: 'large' }),
{
height: '48px',
width: '40px',
height: '24px',
width: '20px',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
Expand Down
1 change: 1 addition & 0 deletions packages/kit/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './useOpenConnectModal'
export * from './useTheme'
export * from './useWalletSettings'
export * from './useWaasFeeOptions'
export * from './useWaasRevalidation'
Loading
Loading