UNPKG

ribbit-wallet-connect

Version:

Next-generation multi-chain wallet and payments app that makes crypto simple, secure, and usable in daily life.

461 lines (358 loc) 11.2 kB
# Ribbit Connect Ribbit Wallet is a crypto wallet that supports Supra network. It is currently available as an Android app. Web applications can interact with the wallet through an sdk initialized using ribbit-wallet-connect. It stores connected wallet address locally on the browser with an expiry limit of 10 days. To connect to another wallet address you need to disconnect the wallet manually and connect again and give access to Dapp. ## Installation ```bash npm install ribbit-wallet-connect # or yarn add ribbit-wallet-connect ``` ## Changes ### Update packages and fix any vulnerabilities This version updates npm packages and fixes any vulnerabilities. ## Usage ### Importing the SDK To use ribbit connect Sdk, all you need to import is initSdk which initializes an instance of sdk. This instance will provide you all the other methods like connectToWallet, getBalance, sendTransaction, getWalletAddress. ```typescript import { initSdk, type RibbitWalletSDK } 'ribbit-wallet-connect'; // Inside your client component or hook const [wallet, setWallet] = useState<WalletInfo | null>(null); const [sdk, setSdk] = useState<RibbitWalletSDK | null>(null); useEffect(() => { try { const instance: RibbitWalletSDK = initSdk(); setSdk(instance); const existing = instance?.getWalletInfo(); if (existing?.connected) { setWallet(existing); setIsConnected(true); } } catch (error) { console.error('Error initializing SDK:', error); } }, []); ``` To import types follow the guideline below to import relevant types exported by the sdk. ```typescript import type { DappMetadata, WalletInfo } from 'ribbit-wallet-connect'; ``` ### Connecting to Wallet To connect to the Ribbit Wallet, you need to provide metadata about your dApp: ```typescript import type { DappMetadata, WalletInfo } from 'ribbit-wallet-connect'; const dappMetadata: DappMetadata = { name: 'My dApp', description: 'A description of my dApp', logo: 'https://mydapp.com/logo.png', url: 'https://mydapp.com', }; ``` Then, request a connection to the Ribbit Wallet: ```typescript const response: WalletInfo = await sdk.connectToWallet(dappMetadata); ``` Handling the Wallet Connection Response ```typescript try { const response: WalletInfo = await sdk.connectToWallet(dappMetadata); if (response) { const { walletAddress, connected } = response; console.log('Wallet connected!'); console.log('Address:', walletAddress); console.log('connected:', connected); // 👉 Proceed with your dApp logic using the connected wallet info } else { console.error('Connection rejected or failed'); } } catch (error) { console.warn(`Error connecting to wallet: ${error}`); } ``` ### Sign Message The `signMessage` method prompts the user to cryptographically sign a message using their wallet, returning the signature and related details if approved. ```typescript import type { SignMessageResponse, SignMessageRequest, } from 'ribbit-wallet-connect'; try { const response: SignMessageResponse = await sdk.signMessage({ message: 'Sign to login at', nonce: new Date().getTime(), chainId: SupraChainId.TESTNET, }); if (response.approved) { console.log(`Message signed successfully!`); console.log(`Result: ${JSON.stringify(response)}`); } else { console.log( `Message signing rejected: ${response.error || 'Unknown error'}` ); } } catch (error) { console.log(`Message signing failed: ${error}`); } ``` ### Sending Transactions #### Chain ID Reference | Chain | Chain ID | | ------------- | -------- | | Supra Testnet | `6` | | Supra Mainnet | `8` | To send a transaction to the blockchain: ### Using supra-l1-sdk Create a base64 raw transaction using supra-l1-sdk ```typescript import { BCS, HexString, TxnBuilderTypes } from 'supra-l1-sdk'; const receiver = BCS.bcsSerializeAddress('0x1234577898sdjbcws98y9......'); const amount = BCS.bcsSerializeU64(BigInt(100000000)); // 1 SUPRA = 100,000,000 microSUPRA const tokenType = BCS.typeTagStruct('0x1::supra_coin::SupraCoin'); const transactionPayload: RawTxnRequest = { sender: selectedWalletAddress, moduleAddress: '0x1234578899999..........', moduleName: 'module name', functionName: 'function name', typeArgs: [tokenType], args: [receiver, amount], chainId, }; const rawTransactionBase64 = await sdk.createRawTransactionBuffer( transactionPayload ); ``` Then, send rawTransaction to the Ribbit Wallet using supra: ```typescript const response: RawTransactionResponse = await sdk.signAndSendRawTransaction({ rawTxn: rawTransactionBase64, chainId, meta: { description: 'Send tokens', }, }); ``` ### Using ribbit-wallet-connect Create a base64 raw transaction using serializers exposed by ribbit-wallet-connect ```typescript import { type RawTransactionResponse, type RawTxnRequest, SupraChainId, BCS, RawTxnFormat, } from 'ribbit-wallet-connect'; const chainId = SupraChainId.TESTNET; const receiver = BCS.bcsSerializeAddress( '0xcd57ba74df68ceea6c46b0e30ac77204bd043d1f57b92384c8d42acb9ed63184' ); const amount = BCS.bcsSerializeU64(BigInt(100000000)); // 1 SUPRA = 100,000,000 microSUPRA const tokenType = BCS.typeTagStruct('0x1::supra_coin::SupraCoin'); const rawTxnRequest: RawTxnRequest = { sender: wallet?.walletAddress, moduleAddress: '0x4feceed8187cde99299ba0ad418412a7d84e54b70bdc4efe756067ca0c3f9c9a', moduleName: 'token', functionName: 'send', typeArgs: [tokenType], args: [receiver, amount], chainId, }; const rawTxnBase64: string = await sdk.createRawTransactionBuffer( rawTxnRequest, RawTxnFormat.aptos ); ``` then, send rawTransaction to the Ribbit Wallet using ribbit-wallet-connect: ```typescript const response: RawTransactionResponse = await sdk.sendTransaction({ rawTxn: rawTransactionBase64, chainId, format: RawTxnFormat.aptos meta: { description: 'Send tokens', }, }); ``` Handling the send transaction Response ```typescript if (response.approved) { console.log('Transaction sent successfully:', response.txHash); // You can handle the result here (e.g., transaction hash) } else { console.error('Transaction was rejected or failed:', response.error); } } catch (error) { console.error('Unexpected error:', error); } ``` ## Getting Wallet Address You can retrieve the connected wallet's address using the `getWalletAddress()` method provided by the Ribbit Wallet SDK. ```ts try { const wallet = sdk.getWalletInfo(); if (wallet) { console.log('Wallet Address:', wallet.walletAddress); } else { console.log(`Wallet address not available`); } } catch (error) { console.log('Failed to get wallet address:', error); } ``` ## Getting Token Balance You can retrieve the wallet’s token balance by calling `getWalletBalance()` from the Ribbit SDK. ```ts try { const walletBalanceRequest: WalletBalanceRequest = { chainId: SupraChainId.TESTNET, '0x1::supra_coin::SupraCoin', 7 } const balance = await sdk.getWalletBalance(walletBalanceRequest); console.log("Wallet balance:", balance); } catch (error) { console.log("Failed to get wallet balance:", error); } ``` ### Disconnecting To disconnect from the wallet: ```typescript try { await sdk.disconnect(); console.log('Disconnected successfully'); } catch (error) { console.error('Failed to disconnect:', error); } ``` ## Type Definitions – Ribbit SDK Below are the core TypeScript types and enums used in the Ribbit Wallet SDK. These types help developers interact with the wallet in a structured and type-safe way. --- ### `RibbitWalletSdk` Interface of sdk itself allowing the consumer to see methods exposed. ```ts export interface RibbitWalletSDK { initialize(): void; connectToWallet(metadata: DappMetadata): Promise<WalletInfo>; disconnect(): Promise<void>; getWalletInfo(): WalletInfo | null; signMessage(message: SignMessageRequest): Promise<SignMessageResponse>; signAndSendRawTransaction( tx: RawTransactionRequest ): Promise<RawTransactionResponse>; createRawTransactionBuffer( tx: RawTxnRequest, format?: RawTxnFormat ): Promise<string>; getWalletBalance( walletBalanceRequest: WalletBalanceRequest ): Promise<WalletBalanceResponse>; } ``` --- ### `DappMetadata` Metadata describing your dApp, shown to users when requesting wallet connection. ```ts export type DappMetadata = { name: string; // Name of your dApp url: string; // Website URL of your dApp description: string; // Short description shown in wallet UI logo: string; // URL to your dApp's logo (SVG/PNG) }; ``` --- ### `WalletInfo` Returned after calling `connectToWallet()` from ribbit extension. Indicates whether the connection was successful and provides walletAddress to Dapp. ```ts export interface WalletInfo { connected: boolean; walletAddress: string; } ``` --- ### `TransactionParams` The structure of the transaction details passed to `createRawTransactionBuffer`. ```ts export type RawTxnRequest = { sender: string; moduleAddress: string; moduleName: string; functionName: string; typeArgs: TypeTag[] | string[] | TxnBuilderTypes.TypeTag[]; args: EntryFunctionArgument[] | Uint8Array[]; chainId: number; }; ``` --- ### `TransactionPayload` The payload object required to initiate a transaction. ```ts export interface RawTransactionRequest { rawTxn: string; // rawtxn in base64 format chainId: number; // chain id - 6 or 8 format?: RawTxnFormat.supra; //optional, default value is supra. for aptos send RawTxnFormat.aptos /** Optional metadata for UI confirmation */ meta?: { /** Human-readable description for confirmation */ description?: string; /** Any extra data for UI display */ [key: string]: any; }; } ``` --- ### `TransactionResponse` Response returned after submitting a transaction. ```ts export interface TransactionResponse { approved: boolean; // True if transaction was approved result?: string; // Optional result - "Success" | "Failed" txHash?: string; // Optional transaction hash (e.g., transaction hash) error?: string; // Optional error message } ``` --- ### `WalletBalanceRequest` Describes the structure of the request object used to fetch a wallet's token balance. ```ts export interface WalletBalanceRequest { chainId: number; resourceType: string; decimals: number; } ``` ### `WalletBalanceResponse` ```ts export interface WalletBalanceResponse { balance: number | null; error?: string | null; } ``` --- ### `SupraChainId` Chain ID values used in the SDK for targeting different Supra networks. ```ts export enum SupraChainId { TESTNET = 6, // Supra Testnet MAINNET = 8, // Supra Mainnet } ``` --- ### `SignMessageRequest` Signing message request ```ts export interface SignMessageRequest { message: string; nonce?: number; chainId: number; } ``` --- ### `SignMessageResponse` Signing message response ```ts export interface SignMessageResponse { approved: boolean; signature?: string; error?: string; publicKey?: string; address?: string; } ```