ribbit-wallet-connect
Version:
Next-generation multi-chain wallet and payments app that makes crypto simple, secure, and usable in daily life.
373 lines (286 loc) • 8.64 kB
Markdown
# 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 injected object called window.ribbit, which is provided by the ribbit-wallet-connect package.
## Installation
```bash
npm install ribbit-wallet-connect
# or
yarn add ribbit-wallet-connect
```
## Usage
### Importing the SDK
```typescript
import { DappMetadata, ConnectResponse } from 'ribbit-wallet-connect';
```
### Connecting to Wallet
To connect to the Ribbit Wallet, you need to provide metadata about your dApp:
```typescript
import { DappMetadata, ConnectResponse } 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: ConnectResponse = await window.ribbit.connectToWallet(
dappMetadata
);
```
Handling the Wallet Connection Response
```typescript
if (response.approved) {
const { accounts, chainId, sessionId } = response;
console.log('Wallet connected!');
console.log('Accounts:', accounts);
console.log('Chain ID:', chainId);
console.log('Session ID:', sessionId);
// 👉 Proceed with your dApp logic using the connected wallet info
} else {
console.error(
'Connection rejected or failed:',
response.error || response.message
);
}
```
### 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
try {
const response = await window.ribbit.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
To send a transaction to the blockchain:
#### Chain ID Reference
| Chain | Chain ID |
| ------------- | -------- |
| Supra Testnet | `6` |
| Supra Mainnet | `8` |
Create a base64 raw transaction
```typescript
import {BCS, type RawTxnRequest, type RawTransactionResponse } from 'ribbit-wallet-connect';
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,
sequenceNumber,
moduleAddress:
'0x1234578899999..........',
moduleName: 'module name',
functionName: 'function name',
typeArgs: [tokenType],
args: [receiver, amount],
maxGasAmount : BigInt(5000),
gasUnitPrice: BigInt(1),
expirationTimestampSecs: Math.floor(Date.now() / 1000) + 300,
chainId,
}
const rawTransactionBase64 = window.ribbit.signAndSendRawTransaction(transactionPayload);
```
Then, request a sending to the Ribbit Wallet:
```typescript
const response: RawTransactionResponse = await window.ribbit.sendTransaction({
rawTxn: rawTxnBase64,
chainId,
meta: {
description: 'Send tokens',
},
});
```
Handling the send transaction Response
```typescript
if (response.approved) {
console.log('Transaction sent successfully:', response.result);
// 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);
}
```
### Checking Session Status
You can check if a user is currently connected:
```typescript
const session = await window.ribbit.getSessionStatus();
if (!session || !session?.sessionId) {
console.log('Not connected to wallet');
} else {
console.log('Connection is still active');
}
```
## Getting Wallet Address
You can retrieve the connected wallet's address using the `getWalletAddress()` method provided by the Ribbit Wallet SDK.
```ts
try {
const address = await window.ribbit.getWalletAddress(SupraChainId.TESTNET);
console.log('Wallet balance:', address);
} 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 window.ribbit.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 window.ribbit.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.
### `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)
};
```
### `RibbitSession`
Session information returned upon successful wallet connection from ribbit app.
```ts
export type RibbitSession = {
sessionId: string; // Unique session identifier
expiresAt: number; // Timestamp when the session expires (in ms)
};
```
### `ConnectResponse`
Returned after calling `connectToWallet()` from ribbit extension. Indicates whether the user approved the connection and provides session details.
```ts
export interface ConnectResponse {
sessionId?: string;
approved: boolean;
accounts?: string[];
chainId?: number;
message?: string;
error?: string;
}
```
### `TransactionParams`
The structure of the transaction details passed to `createRawTransactionBuffer`.
```ts
export type RawTxnRequest = {
sender: string; // '0xkjdbc6r80.........'
sequenceNumber: number; // 1
moduleAddress: string; // '0x17926519763425198327....'
moduleName: string; // 'transfer'
functionName: string; // 'send'
typeArgs?: TypeTag[]; // e.g. ["0x1::supra_coin::SupraCoin"]
args: EntryFunctionArgument[]; // ['receiver address', 'amount'] using BCS.serialize functions
maxGasAmount: number | string; // 1
gasUnitPrice: number | string; // 1
expirationTimestampSecs: number | string; // 1
chainId: number; // 1
};
```
### `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
/** 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?: any; // Optional result
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;
}
```
### `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;
}
```