> ## Documentation Index
> Fetch the complete documentation index at: https://docs.base.org/llms.txt
> Use this file to discover all available pages before exploring further.

# subscription.prepareCharge

> Prepare transaction calls to charge a subscription (advanced)

export const Button = ({children, disabled, variant = "primary", size = "medium", iconName, roundedFull = false, className = '', fullWidth = false, onClick = undefined}) => {
  const variantStyles = {
    primary: 'bg-blue text-black border border-blue hover:bg-blue-80 active:bg-[#06318E] dark:text-white',
    secondary: 'bg-white border border-white text-palette-foreground hover:bg-zinc-15 active:bg-zinc-30',
    outlined: 'bg-transparent text-white border border-white hover:bg-white hover:text-black active:bg-[#E3E7E9]'
  };
  const sizeStyles = {
    medium: 'text-md px-4 py-2 gap-3',
    large: 'text-lg px-6 py-4 gap-5'
  };
  const sizeIconRatio = {
    medium: '0.75rem',
    large: '1rem'
  };
  const classes = ['text-md px-4 py-2 whitespace-nowrap', 'flex items-center justify-center', 'disabled:opacity-40 disabled:pointer-events-none', 'transition-all', variantStyles[variant], sizeStyles[size], roundedFull ? 'rounded-full' : 'rounded-lg', fullWidth ? 'w-full' : 'w-auto', className];
  const buttonClasses = classes.filter(Boolean).join(' ');
  const iconSize = sizeIconRatio[size];
  return <button type="button" disabled={disabled} className={buttonClasses} onClick={onClick}>
      <span>{children}</span>
      {iconName && <Icon name={iconName} width={iconSize} height={iconSize} color="currentColor" />}
    </button>;
};

export const BaseBanner = ({content = null, id, dismissable = true}) => {
  const LOCAL_STORAGE_KEY_PREFIX = 'cb-docs-banner';
  const [isVisible, setIsVisible] = useState(false);
  const onDismiss = () => {
    localStorage.setItem(`${LOCAL_STORAGE_KEY_PREFIX}-${id}`, 'false');
    setIsVisible(false);
  };
  useEffect(() => {
    const storedValue = localStorage.getItem(`${LOCAL_STORAGE_KEY_PREFIX}-${id}`);
    setIsVisible(storedValue !== 'false');
  }, []);
  if (!isVisible) {
    return null;
  }
  return <div className="fixed bottom-0 left-0 right-0 bg-white py-8 px-4 lg:px-12 z-50 text-black dark:bg-black dark:text-white border-t dark:border-gray-95">
      <div className="flex items-center max-w-8xl mx-auto">
        {typeof content === 'function' ? content({
    onDismiss
  }) : content}
        {dismissable && <button onClick={onDismiss} className="flex-shrink-0 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors" aria-label="Dismiss banner">
          ✕
        </button>}
      </div>
    </div>;
};

Defined in the [Base Account SDK](https://github.com/base/account-sdk)

<Note>
  **Most developers should use [`charge()`](/base-account/reference/base-pay/charge) instead**, which handles execution automatically using CDP wallets. This function is for advanced use cases requiring custom transaction handling.
</Note>

<Info>
  The `prepareCharge` function prepares the necessary transaction calls to charge a subscription. It returns the array of call data objects to execute the charge through `wallet_sendCalls` or `eth_sendTransaction`. This gives you programmatic control over when and how to execute subscription charges.
</Info>

## When to Use This

Use `prepareCharge` only if you need:

* **Custom wallet infrastructure** (not using CDP)
* **Manual transaction control**
* **Integration with existing wallet systems**
* **Client-side charging** (though this is uncommon)

For standard backend subscription management, use [`charge()`](/base-account/reference/base-pay/charge) instead.

## Parameters

<ParamField body="id" type="string" required>
  The subscription ID (permission hash) returned from subscribe().

  **Pattern:** `^0x[0-9a-fA-F]{64}$`
</ParamField>

<ParamField body="amount" type="string | 'max-remaining-charge'" required>
  Amount to charge (e.g., "10.50") or 'max-remaining-charge' for the full remaining amount in the current period.
</ParamField>

<ParamField body="testnet" type="boolean">
  Must match the testnet setting used in the original subscribe call. Default: false
</ParamField>

## Returns

<ResponseField name="result" type="PrepareChargeResult">
  Array of transaction calls to execute the charge.

  <Expandable title="PrepareChargeResult properties">
    <ResponseField name="to" type="Address">
      The address to call (smart contract address).
    </ResponseField>

    <ResponseField name="data" type="Hex">
      The encoded call data for the transaction.
    </ResponseField>

    <ResponseField name="value" type="'0x0'">
      The value to send (always 0x0 for spend permissions).
    </ResponseField>
  </Expandable>
</ResponseField>

The returned array contains:

* An approval call (if the permission is not yet active)
* A spend call to charge the subscription

<RequestExample>
  ```typescript EOA Owner Wallet theme={null}
  import { base } from '@base-org/account';
  import { createWalletClient, http } from 'viem';
  import { privateKeyToAccount } from 'viem/accounts';
  import { base as baseChain } from 'viem/chains';

  // Initialize wallet client with your subscription owner account
  const account = privateKeyToAccount('0x...'); // Your app's private key
  const walletClient = createWalletClient({
    account,
    chain: baseChain,
    transport: http()
  });

  // Prepare to charge a specific amount
  const chargeCalls = await base.subscription.prepareCharge({
    id: '0x71319cd488f8e4f24687711ec5c95d9e0c1bacbf5c1064942937eba4c7cf2984',
    amount: '9.99',
    testnet: false
  });

  // Execute each charge call
  const transactionHashes = [];

  for (const call of chargeCalls) {
    const hash = await walletClient.sendTransaction({
      to: call.to,
      data: call.data,
      value: call.value || 0n
    });
    
    transactionHashes.push(hash);
    
    // Wait for transaction confirmation before next call
    await walletClient.waitForTransactionReceipt({ hash });
  }

  console.log(`Charge transactions: ${transactionHashes.join(', ')}`);
  ```

  ```typescript Smart Owner Wallet theme={null}
  import { base } from '@base-org/account';
  import { createPublicClient, http } from 'viem';
  import { privateKeyToAccount } from 'viem/accounts';
  import { base as baseChain } from 'viem/chains';
  import { toCoinbaseSmartAccount, createBundlerClient } from 'viem/account-abstraction';

  // Create public client
  const publicClient = createPublicClient({
    chain: baseChain,
    transport: http()
  });

  // Convert private key to owner account
  const owner = privateKeyToAccount('0x...'); // Your app's private key

  // Create a Coinbase Smart Wallet account from the owner
  const smartAccount = await toCoinbaseSmartAccount({
    client: publicClient,
    owners: [owner],
    version: '1'
  });

  // Create bundler client for sending UserOperations
  const bundlerClient = createBundlerClient({
    account: smartAccount,
    chain: baseChain,
    client: publicClient,
    transport: http('your-bundler-url') // Your bundler URL
  });

  // Prepare to charge the maximum available amount
  const chargeCalls = await base.subscription.prepareCharge({
    id: subscriptionId,
    amount: 'max-remaining-charge',
    testnet: false
  });

  // Send UserOperation through bundler
  const userOpHash = await bundlerClient.sendUserOperation({
    calls: chargeCalls
  });

  // Wait for the UserOperation to be included
  const receipt = await bundlerClient.waitForUserOperationReceipt({
    hash: userOpHash
  });

  console.log(`Charge bundled in transaction: ${receipt.receipt.transactionHash}`);
  ```
</RequestExample>

<ResponseExample>
  ```typescript Two Calls (Approval + Spend) theme={null}
  [
    {
      to: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      data: "0x095ea7b3...",
      value: "0x0"
    },
    {
      to: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      data: "0xa9059cbb...",
      value: "0x0"
    }
  ]
  ```

  ```typescript Single Call (Spend Only) theme={null}
  [
    {
      to: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      data: "0xa9059cbb...",
      value: "0x0"
    }
  ]
  ```
</ResponseExample>

## Error Handling

```typescript theme={null}
try {
  const chargeCalls = await base.subscription.prepareCharge({
    id: subscriptionId,
    amount: chargeAmount,
    testnet: false
  });
  // Execute charge
} catch (error) {
  console.error(`Failed to prepare charge: ${error.message}`);
}
```

## Comparison with charge()

<Tabs>
  <Tab title="Using prepareCharge (Advanced)">
    ```typescript theme={null}
    // You manage everything manually
    const chargeCalls = await base.subscription.prepareCharge({
      id: subscriptionId,
      amount: 'max-remaining-charge',
      testnet: false
    });

    // Initialize wallet client
    const walletClient = createWalletClient({
      account: privateKeyToAccount('0x...'),
      chain: baseChain,
      transport: http()
    });

    // Execute each call sequentially
    for (const call of chargeCalls) {
      const hash = await walletClient.sendTransaction({
        to: call.to,
        data: call.data,
        value: call.value || 0n
      });
      
      await walletClient.waitForTransactionReceipt({ hash });
    }

    // Handle gas estimation, nonce management, retries, etc.
    ```
  </Tab>

  <Tab title="Using charge() (Recommended)">
    ```typescript theme={null}
    // Everything handled automatically
    const result = await base.subscription.charge({
      id: subscriptionId,
      amount: 'max-remaining-charge',
      testnet: false
    });

    // Done! CDP wallet handles:
    // - Wallet initialization
    // - Transaction signing
    // - Gas estimation
    // - Nonce management
    // - Call batching
    // - Transaction confirmation
    // - Optional paymaster support

    console.log(`Charged: ${result.id}`);
    ```
  </Tab>
</Tabs>

## Migration to charge()

If you're currently using `prepareCharge` in a Node.js backend, consider migrating to `charge()`:

```typescript Before (prepareCharge) theme={null}
// Old approach - manual execution
const chargeCalls = await base.subscription.prepareCharge({
  id: subscriptionId,
  amount: '9.99',
  testnet: false
});

const walletClient = createWalletClient({
  account: privateKeyToAccount(process.env.PRIVATE_KEY),
  chain: baseChain,
  transport: http()
});

const transactionHashes = [];
for (const call of chargeCalls) {
  const hash = await walletClient.sendTransaction({
    to: call.to,
    data: call.data,
    value: call.value || 0n
  });
  
  transactionHashes.push(hash);
  await walletClient.waitForTransactionReceipt({ hash });
}
```

```typescript After (charge) theme={null}
// New approach - automatic execution with CDP
const result = await base.subscription.charge({
  id: subscriptionId,
  amount: '9.99',
  testnet: false
});

console.log(`Charged: ${result.id}`);
```

## Related Functions

<CardGroup cols={3}>
  <Card title="Charge" icon="bolt" href="/base-account/reference/base-pay/charge">
    Automatic charging with CDP
  </Card>

  <Card title="Check Status" icon="chart-line" href="/base-account/reference/base-pay/getStatus">
    Verify subscription before charging
  </Card>

  <Card title="Custom Revoke" icon="code" href="/base-account/reference/base-pay/prepareRevoke">
    Advanced revoke execution
  </Card>
</CardGroup>

<BaseBanner
  id="privacy-policy"
  dismissable={false}
  content={({ onDismiss }) => (
<div className="flex items-center">
  <div className="mr-2">
    We're updating the Base Privacy Policy, effective July 25, 2025, to reflect an expansion of Base services. Please review the updated policy here:{" "}
    <a
      href="https://docs.base.org/privacy-policy-2025"
      target="_blank"
      className="whitespace-nowrap"
    >
      Base Privacy Policy
    </a>. By continuing to use Base services, you confirm that you have read and understand the updated policy.
  </div>
  <Button onClick={onDismiss}>I Acknowledge</Button>
</div>
)}
/>
