8000 feat: add isSponsored prop to Transaction and playground by abcrane123 · Pull Request #1499 · coinbase/onchainkit · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: add isSponsored prop to Transaction and playground #1499

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

Merged
merged 16 commits into from
Oct 29, 2024
Merged
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
17 changes: 17 additions & 0 deletions playground/nextjs-app-router/components/AppProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ type State = {
setComponentMode: (mode: ComponentMode) => void;
nftToken?: string;
setNFTToken: (nftToken: string) => void;
setIsSponsored: (isSponsored: boolean) => void;
isSponsored?: boolean;
};

const defaultState: State = {
Expand All @@ -88,6 +90,7 @@ const defaultState: State = {
componentMode: 'auto',
setComponentMode: () => {},
setNFTToken: () => {},
setIsSponsored: () => {},
};

export const AppContext = createContext(defaultState);
Expand Down Expand Up @@ -119,6 +122,8 @@ export const AppProvider = ({ children }: { children: React.ReactNode }) => {
'0x1D6b183bD47F914F9f1d3208EDCF8BefD7F84E63:1',
);

const [isSponsored, setIsSponsoredState] = useState<boolean>(false);

// Load initial values from localStorage
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO Refactor this component
useEffect(() => {
Expand All @@ -135,6 +140,7 @@ export const AppProvider = ({ children }: { children: React.ReactNode }) => {
'componentMode',
) as ComponentMode;
const storedNFTToken = localStorage.getItem('nftToken');
const storedIsSponsored = localStorage.getItem('isSponsored');

if (storedActiveComponent) {
setActiveComponent(storedActiveComponent as OnchainKitComponent);
Expand Down Expand Up @@ -163,6 +169,9 @@ export const AppProvider = ({ children }: { children: React.ReactNode }) => {
if (storedNFTToken) {
setNFTTokenState(storedNFTToken);
}
if (storedIsSponsored) {
setIsSponsoredState(JSON.parse(storedIsSponsored));
}
}, []);

// Connect to wallet if walletType changes
Expand Down Expand Up @@ -243,6 +252,11 @@ export const AppProvider = ({ children }: { children: React.ReactNode }) => {
localStorage.setItem('nftToken', nftToken);
setNFTTokenState(nftToken);
};
const setIsSponsored = (isSponsored: boolean) => {
console.log('Component isSponsored changed: ', isSponsored);
localStorage.setItem('isSponsored', JSON.stringify(isSponsored));
setIsSponsoredState(isSponsored);
};

return (
<AppContext.Provider
Expand Down Expand Up @@ -270,6 +284,8 @@ export const AppProvider = ({ children }: { children: React.ReactNode }) => {
setDefaultMaxSlippage,
nftToken,
setNFTToken,
setIsSponsored,
isSponsored,
}}
>
<OnchainKitProvider
Expand All @@ -282,6 +298,7 @@ export const AppProvider = ({ children }: { children: React.ReactNode }) => {
mode: componentMode,
theme: componentTheme === 'none' ? undefined : componentTheme,
},
paymaster: paymasters?.[chainId || 8453]?.url,
}}
projectId={ENVIRONMENT_VARIABLES[ENVIRONMENT.PROJECT_ID]}
schemaId="0xf8b05c79f090979bf4a80270aba232dff11a10d9ca55c4f88de95317970f0de9"
Expand Down
4 changes: 4 additions & 0 deletions playground/nextjs-app-router/components/DemoOptions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { OnchainKitComponent } from './AppProvider';
import { ActiveComponent } from './form/active-component';
import { Chain } from './form/chain';
import { CheckoutOptions } from './form/checkout-options';
import { IsSponsored } from './form/is-sponsored';
import { NFTOptions } from './form/nft-options';
import { SwapConfig } from './form/swap-config';
import { TransactionOptions } from './form/transaction-options';
Expand All @@ -31,6 +32,7 @@ export default function DemoOptions({
{commonOptions}
<Chain />
<PaymasterUrl />
<IsSponsored />
<CheckoutOptions />
</>
);
Expand All @@ -41,6 +43,7 @@ export default function DemoOptions({
{commonOptions}
<Chain />
<PaymasterUrl />
<IsSponsored />
<SwapConfig />
</>
);
Expand All @@ -51,6 +54,7 @@ export default function DemoOptions({
{commonOptions}
<Chain />
<PaymasterUrl />
<IsSponsored />
Copy link
Contributor

Choose a reason for hiding this comment

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

can you add this to other relevant components (Swap and Pay)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

should Pay have isSponsored prop ? isn't it always sponsored by Coinbase? or is this a short term thing ?

<TransactionOptions />
</>
);
Expand Down
9 changes: 4 additions & 5 deletions playground/nextjs-app-router/components/demo/Checkout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useCapabilities } from '@/lib/hooks';
import {
Checkout,
CheckoutButton,
Expand All @@ -10,8 +9,8 @@ import { useContext } from 'react';
import { AppContext, CheckoutTypes } from '../AppProvider';

export default function CheckoutDemo() {
const { checkoutTypes, checkoutOptions } = useContext(AppContext);
const capabilities = useCapabilities();
const { checkoutTypes, checkoutOptions, isSponsored } =
useContext(AppContext);

const chargeIDKey = useMemo(() => {
return `${checkoutOptions?.chargeId}`;
Expand Down Expand Up @@ -41,7 +40,7 @@ export default function CheckoutDemo() {
key={productIDKey}
productId={checkoutOptions?.productId}
>
isSponsored={capabilities?.paymasterService?.url != null}
isSponsored={isSponsored}
>
<CheckoutButton
coinbaseBranded={true}
Expand Down Expand Up @@ -69,7 +68,7 @@ export default function CheckoutDemo() {
key={chargeIDKey}
chargeHandler={createCharge}
>
isSponsored={capabilities?.paymasterService?.url != null}
isSponsored={isSponsored}
>
<CheckoutButton
coinbaseBranded={true}
Expand Down
4 changes: 2 additions & 2 deletions playground/nextjs-app-router/components/demo/Swap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { AppContext } from '../AppProvider';
const FALLBACK_DEFAULT_MAX_SLIPPAGE = 3;

function SwapComponent() {
const { chainId, defaultMaxSlippage, paymasters } = useContext(AppContext);
const { chainId, isSponsored, defaultMaxSlippage } = useContext(AppContext);

const degenToken: Token = {
name: 'DEGEN',
Expand Down Expand Up @@ -111,7 +111,7 @@ function SwapComponent() {
config={{
maxSlippage: defaultMaxSlippage || FALLBACK_DEFAULT_MAX_SLIPPAGE,
}}
isSponsored={paymasters != null}
isSponsored={isSponsored}
>
<SwapSettings>
<SwapSettingsSlippageTitle>Max. slippage</SwapSettingsSlippageTitle>
Expand Down
8 changes: 3 additions & 5 deletions playground/nextjs-app-router/components/demo/Transaction.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useCapabilities } from '@/lib/hooks';
import { clickCalls, clickContracts } from '@/lib/transactions';
import type { Call } from '@/onchainkit/esm/transaction/types';
import type { LifecycleStatus } from '@/onchainkit/src/transaction';
Expand All @@ -19,8 +18,7 @@ import type { ContractFunctionParameters } from 'viem';
import { AppContext, TransactionTypes } from '../AppProvider';

function TransactionDemo() {
const { chainId, transactionType } = useContext(AppContext);
const capabilities = useCapabilities();
const { chainId, transactionType, isSponsored } = useContext(AppContext);
const contracts = clickContracts as ContractFunctionParameters[];
const calls = clickCalls as Call[];
const promiseCalls = new Promise((resolve) => {
Expand Down Expand Up @@ -100,7 +98,7 @@ function TransactionDemo() {
case TransactionTypes.ContractsCallback:
return { calls: undefined, contracts: contractsCallback };
default:
return { calls: undefined, contracts: undefined };
return { calls, contracts: undefined };
}
}, [
calls,
Expand All @@ -117,7 +115,7 @@ function TransactionDemo() {
<Transaction
chainId={chainId ?? 84532} // something breaks if we don't have default network?
{...transactions}
capabilities={capabilities}
isSponsored={isSponsored}
>
>
<TransactionButton
Expand Down
28 changes: 28 additions & 0 deletions playground/nextjs-app-router/components/form/is-sponsored.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { useCallback, useContext } from 'react';
import { AppContext } from '../AppProvider';

export function IsSponsored() {
const { isSponsored, setIsSponsored } = useContext(AppContext);

const handleChange = useCallback(() => {
setIsSponsored(!isSponsored);
}, [setIsSpon 10000 sored, isSponsored]);

return (
<div className="grid gap-2">
<div className="flex items-center justify-between">
<Label htmlFor="sponsored mr-auto">isSponsored</Label>
<div className="flex items-center gap-2">
<Switch
id="is-sponsored"
checked={isSponsored}
>
/>
<Label htmlFor="is-sponsored text-foregroundMuted">True</Label>
</div>
</div>
</div>
);
}
7 changes: 7 additions & 0 deletions src/swap/components/SwapProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { formatTokenAmount } from '../../internal/utils/formatTokenAmount';
import type { Token } from '../../token';
import { GENERIC_ERROR_MESSAGE } from '../../transaction/constants';
import { isUserRejectedRequestError } from '../../transaction/utils/isUserRejectedRequestError';
import { useOnchainKit } from '../../useOnchainKit';
import { FALLBACK_DEFAULT_MAX_SLIPPAGE } from '../constants';
import { useAwaitCalls } from '../hooks/useAwaitCalls';
import { useFromTo } from '../hooks/useFromTo';
Expand Down Expand Up @@ -49,6 +50,9 @@ export function SwapProvider({
onStatus,
onSuccess,
}: SwapProviderReact) {
const {
config: { paymaster } = { paymaster: undefined },
} = useOnchainKit();
const { address, chainId } = useAccount();
const { switchChainAsync } = useSwitchChain();
// Feature flags
Expand Down Expand Up @@ -287,6 +291,7 @@ export function SwapProvider({
[from, to, lifecycleStatus, updateLifecycleStatus, useAggregator],
);

// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO Refactor this component
const handleSubmit = useCallback(async () => {
if (!address || !from.token || !to.token || !from.amount) {
return;
Expand Down Expand Up @@ -317,6 +322,7 @@ export function SwapProvider({
chainId,
config: accountConfig,
isSponsored,
paymaster: paymaster || '',
sendCallsAsync,
sendTransactionAsync,
swapTransaction: response,
Expand Down Expand Up @@ -346,6 +352,7 @@ export function SwapProvider({
from.token,
isSponsored,
lifecycleStatus,
paymaster,
sendCallsAsync,
sendTransactionAsync,
switchChainAsync,
Expand Down
CEB7
2 changes: 2 additions & 0 deletions src/swap/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type { Call } from '../transaction/types';
export type SendSwapTransactionParams = {
config: Config;
isSponsored?: boolean; // Whether the swap is sponsored (default: false)
paymaster?: string; // OnchainKit config paymaster RPC url
// biome-ignore lint: cannot find module 'wagmi/experimental/query'
sendCallsAsync: any;
sendTransactionAsync: SendTransactionMutateAsync<Config, unknown>;
Expand Down Expand Up @@ -158,6 +159,7 @@ export type ProcessSwapTransactionParams = {
chainId?: number; // The chain ID
config: Config;
isSponsored?: boolean; // Whether the swap is sponsored (default: false)
paymaster?: string; // OnchainKit config paymaster RPC url
// biome-ignore lint: cannot find module 'wagmi/experimental/query'
sendCallsAsync: any;
sendTransactionAsync: SendTransactionMutateAsync<Config, unknown>;
Expand Down
2 changes: 2 additions & 0 deletions src/swap/utils/processSwapTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export async function processSwapTransaction({
chainId,
config,
isSponsored,
paymaster,
sendCallsAsync,
sendTransactionAsync,
swapTransaction,
Expand Down Expand Up @@ -85,6 +86,7 @@ export async function processSwapTransaction({
await sendSwapTransactions({
config,
isSponsored,
paymaster,
sendCallsAsync,
sendTransactionAsync,
transactions,
Expand Down
4 changes: 2 additions & 2 deletions src/swap/utils/sendSwapTransactions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { mainnet, sepolia } from 'wagmi/chains';
import { mock } from 'wagmi/connectors';
import { setOnchainKitConfig } from '../../OnchainKitConfig';
import { Capabilities } from '../../constants';
import { getRPCUrl } from '../../network/getRPCUrl';
import type { SwapTransaction } from '../types';
import { sendSwapTransactions } from './sendSwapTransactions';

Expand Down Expand Up @@ -120,13 +119,14 @@ describe('sendSwapTransactions', () => {
updateLifecycleStatus,
walletCapabilities: { [Capabilities.AtomicBatch]: { supported: true } },
transactions,
paymaster: 'paymaster-url',
});
expect(sendCallsAsync).toHaveBeenCalledTimes(1);
expect(sendCallsAsync).toHaveBeenCalledWith({
calls: transactions.map(({ transaction }) => transaction),
capabilities: {
paymasterService: {
url: getRPCUrl(),
url: 'paymaster-url',
},
},
});
Expand Down
4 changes: 2 additions & 2 deletions src/swap/utils/sendSwapTransactions.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Capabilities } from '../../constants';
import { getRPCUrl } from '../../network/getRPCUrl';
import type { SendSwapTransactionParams } from '../types';
import { sendSingleTransactions } from './sendSingleTransactions';

export async function sendSwapTransactions({
config,
isSponsored,
paymaster,
sendCallsAsync,
sendTransactionAsync,
updateLifecycleStatus,
Expand All @@ -22,7 +22,7 @@ export async function sendSwapTransactions({
capabilities: isSponsored
? {
paymasterService: {
url: getRPCUrl(),
url: paymaster,
},
}
: {},
Expand Down
2 changes: 2 additions & 0 deletions src/transaction/components/Transaction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export function Transaction({
className,
children,
contracts,
isSponsored,
Copy link
Contributor

Choose a reason for hiding this comment

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

can you add a deprecated docstring to the capabilities prop

onError,
onStatus,
onSuccess,
Expand All @@ -35,6 +36,7 @@ export function Transaction({
capabilities={capabilities}
chainId={accountChainId}
contracts={contracts}
isSponsored={isSponsored}
>
>
>
Expand Down
Loading
0