@brahmafi/cards-sdk
Version:
Official SDK for integrating Swype payment and credit services
293 lines (230 loc) • 8.2 kB
Markdown
# Brahma SDK
A React SDK for seamless KYC, card activation, and credit management flows. Integrate Brahma SDK's widgets, hooks, and utilities into your app with minimal setup.
## 1. SDK Initialization & Authentication
To use the SDK, you must initialize it **after authenticating the user** with an EIP-712 signature. The authentication is valid for 1 hour; after that, a new signature is required.
**Requirements:**
- User's EOA address (wallet)
- EIP-712 signature (generated via wallet)
- API key (from Swype)
- Deadline (timestamp, 1 hour in the future)
**Example (React, using wagmi):**
```tsx
import { useAccount, useSignTypedData } from "wagmi";
import { initializeSwypeSDK, generateAuthSign } from "@brahmafi/cards-sdk";
const { address } = useAccount();
const { signTypedDataAsync } = useSignTypedData();
async function authenticateAndInit() {
// 1. Generate EIP-712 signature
const { signature, deadline } = await generateAuthSign(
address,
chainId,
signTypedDataAsync
);
// 2. Initialize SDK
await initializeSwypeSDK({
apiKey: "<YOUR_API_KEY>",
baseUrl: "https://api.console.fi",
apiPath: "/v1/vendor",
eoaAddress: address,
signature,
deadline,
});
}
```
> **Note:** After 1 hour, you must prompt the user to sign again and re-initialize the SDK.
## 2. Widgets
The SDK provides ready-to-use React components for KYC and card management.
> ### **Prerequisites**
>
> `@import "@brahmafi/cards-sdk/dist/styles.css";`
>
> Import styles in global.css
### **KycModal**
- **Props:**
- `eoaAddress: string` (required)
- `onClose?: () => void`
- `onComplete?: () => void`
- **Description:**
Handles the full KYC flow, including SumSub integration, consent, and pending/approved states. Callbacks are triggered on close or completion.
**Behavior by User Status:**
- **'initiated' / 'userNotExisting':** Shows the Submit KYC Modal for the user to start KYC.
- **'pending':** Shows the Rain KYC Pending Modal, indicating KYC is under review.
- **'approved':** The KYC is complete. The integrator must now call the `delegateCard` function to delegate credit and create the card. After delegation, refetch card status and show the dashboard with owned card details.
> **Note:** The KycModal does not handle card delegation. For 'approved' status, you must trigger the delegation flow in your app using the SDK's `delegateCard` utility.
### **ManageCardModal**
- **Props:**
- `title: string`
- `onClose: () => void`
- `callbacks: CardDetailsCallbacks`
- `address: string`
- `chainId: number`
- **Description:**
Lets users view card details, reveal secrets, freeze/unfreeze, and change PIN. Integrates with SDK hooks for state and actions.
## 3. Hooks
The SDK exposes hooks for accessing user/card/credit/transaction data:
### **useCardData**
Returns:
```ts
{
status: CardStatus | null,
userCard: UserCard | null,
isUserCardDelegated: boolean,
isLoading: boolean,
error: string | null
}
```
### **useCreditData**
Returns:
```ts
{
creditInfo: {
card: CreditInformationResponse | null,
aave: CreditInformationResponse | null,
euler: CreditInformationResponse | null
},
isLoading: boolean,
error: string | null
}
```
### **useGetTransactions**
Returns:
```ts
{
transactions: Transaction[],
isLoading: boolean,
error: string | null,
hasNext: boolean,
loadMore: () => Promise<void>,
refetch: () => Promise<void>,
fetchOnchainDetails: (transactionID: string) => Promise<OnchainTransactionDetailsResponse>
}
```
## 4. Utility Functions
### **delegateCard**
```ts
async function delegateCard(params: DelegateCardParams): Promise<void>;
```
- **Description:**
Handles the full card delegation flow: gets delegation transaction data, executes the transaction, creates the card, generates a signature, links the card, verifies, and refetches data.
- **Params:**
- `creditType`: "aave-v3" | "euler"
- `creditLimit`: number
- `sendTransactionAsync`: callback for sending the transaction
- `signTypedDataAsync`: callback for EIP-712 signature
- `userParams?`: { vaults: string[] }
### **delegateAmount**
```ts
async function delegateAmount(
params: DelegateCardParams
): Promise<{ success: boolean; message: string }>;
```
- **Description:**
Handles the process of delegating a credit limit to a user's card. It fetches the required transaction data, sends the delegation transaction, and verifies that the delegation was successful by checking the delegated amount. Updates the credit store with the latest information.
- **Params:**
- `creditType`: "aave-v3" | "euler" | any — The credit protocol to use for delegation.
- `creditLimit`: number — The amount of credit to delegate (must be >= 0).
- `sendTransactionAsync`: ({ to, value, data }) => Promise<string> — Callback to send the delegation transaction.
- `userParams?`: { vaults: string[] } — Optional additional user parameters (e.g., vault addresses).
- **Returns:**
- `{ success: boolean; message: string }` — Indicates if delegation succeeded and provides a message.
- **Notes:**
- Will retry fetching credit info up to 2 times to confirm delegation.
- If the delegated amount does not match the requested limit, returns an error message.
### **createCardAction**
```ts
async function createCardAction(params: {
chainID: number;
creditType: CreditType;
signTypedDataAsync: (params: {
domain: { chainId: number };
types: Record<string, Array<{ name: string; type: string }>>;
primaryType: string;
message: Record<string, any>;
}) => Promise<string>;
}): Promise<{ success: boolean; message: string }>;
```
- **Description:**
Handles the creation and linking of a new card for the user. If a card does not exist, it creates one, generates an EIP-712 signature to authorize the card, links the card to the user's credit provider address, and verifies the result. Updates the card status store with the latest card information.
- **Params:**
- `chainID`: number — The chain ID for the operation.
- `creditType`: CreditType — The type of credit to associate with the card.
- `signTypedDataAsync`: (params) => Promise<string> — Callback for generating an EIP-712 signature.
- **Returns:**
- `{ success: boolean; message: string }` — Indicates if card creation succeeded and provides a message.
- **Notes:**
- Will not create a new card if one already exists for the user.
- Verifies that the card is linked to the correct credit provider address after creation.
## 5. Types
The SDK exports the following types for type safety and integration:
- `CardStatus`: Status of the user's card/KYC
```js
| "userNotExisting"
| "initiated"
| "review"
| "pending"
| "approved"
| "rejected"
| "feePending";
```
- `UserCard`: Structure representing a user's card (cardID, status, type, last4, etc.)
```js
interface UserCard {
cardID: string;
creditProviderAddress: string;
type: "virtual" | "physical";
status: "active" | "inactive" | "pending" | "locked";
last4: string;
solverType: "aave-v3" | "euler" | "hypurrFi";
expirationMonth: string;
expirationYear: string;
}
```
- `Transaction`
```js
interface Transaction {
id: string;
type: TransactionType;
status: TransactionStatus;
amount: number;
currency: string;
local_amount?: number;
local_currency: string;
merchant: Merchant;
declined_reason?: string;
created_at: string;
authorized_at?: string;
posted_at?: string | null;
onchain_transactions?: OnchainTransaction[];
}
```
- `OnchainTransactionDetail`
```js
interface OnchainTransactionDetail {
id: string;
transaction_id: string;
direction: OnchainDirection;
chain_id: string;
from_address: string;
to_address: string;
transaction_hash: string;
amount: number;
amount_raw: string;
fee_raw: string;
token: string;
status: OnchainStatus;
purpose: OnchainPurpose;
error_details?: string;
created_at: string;
completed_at?: string;
}
```
- ...and more (see `src/api/types.ts` for full list).
**For more details, see the code comments and type definitions in the SDK.**