Skip to content

CipherBlock-io/cipherblock-client

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Cipherblock SDK

JavaScript SDK for integrating with the Cipherblock blockchain - a portable cryptographic reputation management system.

Features

  • Wallet Management: Create, import, export, and manage multiple wallets
  • Transaction Building: Build and sign all transaction types (transfers, NFTs, ratings, burns)
  • Blockchain Interaction: Submit transactions, request tokens, query state
  • Multi-Wallet Support: Manage multiple accounts with easy switching
  • Cryptographic Operations: Sign/verify messages, hash data, generate keypairs
  • Firebase Integration: Direct access to blockchain state via Firestore (optional)

Installation

npm install cipherblock-sdk

If you want to access blockchain state directly (balances, transactions, NFTs), also install Firebase:

npm install firebase

Quick Start

Basic Usage (API Only)

import { createCipherblockSDK } from 'cipherblock-sdk';

// Create SDK instance
const sdk = createCipherblockSDK();

// Initialize (loads wallets from localStorage)
await sdk.init();

// Get or create wallet
const wallet = sdk.getWallet();
console.log('My Address:', wallet.address);

// Request tokens from faucet (once per address)
const faucetResult = await sdk.requestTokens();
console.log('Received:', faucetResult.amount, 'tokens');

Advanced Usage (with Firebase)

import { initializeApp } from 'firebase/app';
import { createCipherblockSDK } from 'cipherblock-sdk';

// Initialize Firebase
const firebaseApp = initializeApp({
    apiKey: "AIzaSyBuE6iu4v3hf01exw_RRqYAr_YM4IZTWu8",
    authDomain: "cipherblockio.firebaseapp.com",
    projectId: "cipherblockio",
    storageBucket: "cipherblockio.appspot.com"
});

// Create SDK with Firebase
const sdk = createCipherblockSDK({ firebaseApp });
await sdk.init();

// Check balance
const balance = await sdk.getBalance();
console.log('Balance:', balance, 'CBT');

// Send tokens
const result = await sdk.sendTokens(recipientAddress, 5.0);
console.log('Transaction Hash:', result.tx_hash);

// Get transaction history
const history = await sdk.client.getTransactionHistory(wallet.address);
console.log('Transactions:', history);

API Reference

SDK Instance

createCipherblockSDK(options)

Creates a new SDK instance.

Options:

  • firebaseApp: Firebase app instance (optional, required for state access)
  • submitTransactionUrl: Custom transaction endpoint (optional)
  • requestTokensUrl: Custom faucet endpoint (optional)

Returns: SDK instance with:

  • client: BlockchainClient instance
  • walletManager: WalletManager instance
  • init(): Initialize SDK (load wallets)
  • getWallet(): Get or create active wallet
  • sendTokens(recipient, amount): Send tokens
  • requestTokens(): Request from faucet
  • getBalance(): Get balance of active wallet

Wallet Class

new Wallet(keypair?)

Create a new wallet. If no keypair is provided, generates a new one.

Methods:

  • export(): Export wallet data as object
  • exportJSON(): Export wallet data as JSON string
  • getPublicInfo(): Get address and public key only

Static Methods:

  • Wallet.import(data): Import wallet from object
  • Wallet.importJSON(jsonString): Import wallet from JSON

WalletManager Class

new WalletManager(storageKey?)

Manages multiple wallets with localStorage persistence.

Methods:

  • createWallet(): Create and add new wallet
  • addWallet(wallet): Add existing wallet
  • getActiveWallet(): Get currently active wallet
  • setActiveWallet(index): Switch active wallet
  • getAllWallets(): Get all wallets
  • getWalletByAddress(address): Find wallet by address
  • save(): Save to localStorage
  • load(): Load from localStorage
  • clear(): Remove all wallets

BlockchainClient Class

new BlockchainClient(options)

Client for blockchain interactions.

Methods:

State Queries:

  • getState(): Get current blockchain state
  • getBalance(address): Get token balance
  • getNonce(address): Get transaction nonce
  • getNFTsOwnedBy(address): Get owned NFTs
  • getBlocks(start, end): Get blocks in range
  • getLatestBlocks(count): Get recent blocks
  • getTransactionHistory(address, maxBlocks): Get transaction history

Transactions:

  • submitTransaction(transaction, privateKey): Submit signed transaction
  • requestTokens(address): Request tokens from faucet

Transaction Builders:

  • buildTokenTransfer(sender, recipient, amount, nonce)
  • buildRateTransaction(sender, target, score, nonce)
  • buildNFTMint(sender, nftHash, nonce)
  • buildNFTTransfer(sender, recipient, nftHash, nonce)
  • buildNFTSellOrder(sender, nftHash, price, expiration, nonce)
  • buildNFTBuyOrder(sender, nftHash, price, expiration, nonce)
  • buildTokenBurn(sender, amount, destinationKey, nonce)
  • buildNFTBurn(sender, nftHash, destinationKey, nonce)

Crypto Functions

generateKeypair()

Generate a new secp256k1 keypair.

Returns: { privateKey, publicKey, address }

signTransaction(transaction, privateKey)

Sign a transaction.

Returns: Promise resolving to signature hex string

verifyTransactionSignature(transaction)

Verify a transaction's signature.

Returns: Boolean

signMessage(message, privateKey)

Sign an arbitrary message (off-chain).

Returns: Promise resolving to signature hex string

verifyMessage(message, signature, publicKey)

Verify a message signature.

Returns: Boolean

hashData(data)

Hash data with SHA256.

Returns: Hex string

isValidAddress(address)

Check if address format is valid.

Returns: Boolean

isValidPrivateKey(privateKey)

Check if private key format is valid.

Returns: Boolean

Transaction Types

TOKEN_TRANSFER

Transfer tokens to another address.

const nonce = await client.getNonce(wallet.address);
const tx = client.buildTokenTransfer(
    wallet.address,
    recipientAddress,
    5.0,  // amount
    nonce
);
await client.submitTransaction(tx, wallet.privateKey);

Fee: 0.001 CBT

RATE

Rate another address (reputation).

const tx = client.buildRateTransaction(
    wallet.address,
    targetAddress,
    75,  // score: -100 to 100
    nonce
);

Fee: 0.001 CBT

NFT_MINT

Create a new NFT.

import { hashData } from 'cipherblock-sdk';

const nftHash = hashData(JSON.stringify({ name: 'My NFT', image: '...' }));
const tx = client.buildNFTMint(wallet.address, nftHash, nonce);

Fee: 0.001 CBT

NFT_TRANSFER

Transfer an owned NFT.

const tx = client.buildNFTTransfer(
    wallet.address,
    recipientAddress,
    nftHash,
    nonce
);

Fee: 0.001 CBT

NFT_SELL_ORDER

List an NFT for sale.

const expiration = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString();
const tx = client.buildNFTSellOrder(
    wallet.address,
    nftHash,
    10.0,  // price
    expiration,
    nonce
);

Fee: 0.001 CBT (NFT gets locked until order completes or expires)

NFT_BUY_ORDER

Make an offer to buy an NFT.

const expiration = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString();
const tx = client.buildNFTBuyOrder(
    wallet.address,
    nftHash,
    10.0,  // price
    expiration,
    nonce
);

Fee: 0.001 CBT (tokens get locked until order completes or expires)

ASSET_BURN

Burn tokens or NFTs.

// Burn tokens
const tx = client.buildTokenBurn(
    wallet.address,
    5.0,  // amount
    'bitcoin:1A1zP1eP...',  // destination key
    nonce
);

// Burn NFT
const tx = client.buildNFTBurn(
    wallet.address,
    nftHash,
    'ethereum:0x123...',  // destination key
    nonce
);

Fee: 0.001 CBT

Constants

TRANSACTION_FEE

Standard transaction fee: 0.001 CBT

All transactions require this fee to be deducted from the sender's balance.

Examples

See the examples/ directory for complete working examples:

  • basic-usage.js: Simple wallet and faucet usage
  • advanced-usage.js: Full features with Firebase integration
  • wallet-management.js: Multi-wallet operations and import/export

Browser Usage

The SDK works in both Node.js and browsers. For browsers, use a bundler like webpack or vite:

<script type="module">
import { createCipherblockSDK } from './dist/cipherblock-sdk.js';

const sdk = createCipherblockSDK();
// ... use SDK
</script>

Wallets are automatically saved to localStorage in browsers.

Security

⚠️ Important Security Notes:

  1. Private Keys: Never expose private keys in client-side code or commit them to version control
  2. Key Storage: In production, use secure key storage solutions (hardware wallets, encrypted storage)
  3. HTTPS Only: Always use HTTPS in production to protect API calls
  4. Validate Input: Always validate user input before building transactions
  5. Rate Limiting: Be aware of faucet limits (5 tokens per address, 250/day globally)

License

MIT

Support

For issues and questions:

Contributing

Contributions are welcome! Please open an issue or pull request.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published