@cultura/sdk
Version:
SDK for interacting with Cultura, a Layer 2 Ethereum blockchain acting as the global registry for human creativity and IP. It ensures transparent licensing, revenue sharing, and secure provenance.
312 lines (236 loc) • 10.4 kB
Markdown
# Cultura SDK
Welcome to the Cultura SDK! This toolkit enables developers to interact with Cultura, a Layer 2 Ethereum blockchain serving as the global registry for human creativity and intellectual property. Cultura ensures transparent licensing, revenue sharing, and secure provenance for creative works. This SDK provides a comprehensive set of tools for working with Digital Assets, Rights Attestations, and Licensing in the Cultura ecosystem.
## Installation
```bash
npm install @cultura/sdk
# or
yarn add @cultura/sdk
# or
pnpm add @cultura/sdk
```
## Quick Start
The SDK can be configured for different environments and with different wallet connections:
```typescript
import { CulturaSDK } from '@cultura/sdk'
// Create SDK instance with default configuration (testnet) read-only
const sdk = CulturaSDK.create()
// Create SDK instance for specific environment
const devnetSdk = CulturaSDK.create({ chain: 'devnet' })
const localSdk = CulturaSDK.create({ chain: 'local' })
// Create SDK instance with wallet connection (uses testnet by default)
const walletSdk = CulturaSDK.createWithWallet(window.ethereum)
// Create SDK instance with wallet connection and specific chain
const localWalletSdk = CulturaSDK.createWithWallet(window.ethereum, {
chain: 'local',
// You can provide other configuration options here
})
// Create SDK instance with wallet connection, specific chain and account address
const walletWithAddressSdk = CulturaSDK.createWithWallet(window.ethereum, {
chain: 'testnet',
account: '0x123...' as `0x${string}`,
})
// Create SDK instance with specfific account address (read-only for transactions)
const addressSdk = CulturaSDK.createWithAccount('0x123...', { chain: 'testnet' })
// Create SDK instance with an account from a private key (full signing capability)
import { privateKeyToAccount } from 'viem/accounts'
const account = privateKeyToAccount('0xYourPrivateKeyHere')
const privateKeySdk = CulturaSDK.createWithAccount(account, { chain: 'testnet' })
```
## Environments
The SDK supports the following environments:
- `local` - Local development environment
- `devnet` - Cultura Devnet (subject to heavy changes and frequent resets)
- `testnet` (default) - Cultura Testnet (stable environment for testing)
The environment is set at SDK instantiation time and doesn't rely on environment variables. Always explicitly specify the environment you want to use when creating the SDK instance.
### Installation
```bash
# Install latest stable version
pnpm add @cultura/sdk
# Install latest RC version
pnpm add @cultura/sdk@rc
# Install specific version
pnpm add @cultura/sdk@0.2.6
pnpm add @cultura/sdk@0.2.7-rc.1
```
## Usage with Frontend Frameworks
### React Example
```typescript
import { createContext, useContext, useEffect, useState } from "react";
import { CulturaSDK, utils } from "@cultura/sdk";
import { useAuth } from "your-auth-provider"; // Replace with your actual auth hook
const { getChainName } = utils;
const SDKContext = createContext<CulturaSDK | null>(null);
export function useSDK() {
const context = useContext(SDKContext);
// Don't throw an error, just return null if not in provider
return context;
}
export function SDKProvider({ children }: { children: React.ReactNode }) {
const { ready, isConnected, connectedWallet, address } = useAuth();
const [sdk, setSdk] = useState<CulturaSDK | null>(null);
useEffect(() => {
if (!ready || !isConnected || !connectedWallet || !address) {
setSdk(null);
return;
}
const chainId = parseChainId(connectedWallet.chainId); // Implement parseChainId based on your needs
// Create SDK with wallet connection
const newSdk = CulturaSDK.createWithWallet(window.ethereum, {
chain: getChainName(chainId),
account: address as `0x${string}`,
});
setSdk(newSdk);
}, [ready, isConnected, connectedWallet, address, connectedWallet?.chainId]);
return <SDKContext.Provider value={sdk}>{children}</SDKContext.Provider>;
}
```
## Core Features
- **Digital Asset Management**: Create, mint, and manage Digital Assets
- **Rights Attestations**: Attest to rights ownership and verify attestations
- **Licensing**: License Digital Assets and manage licensing rights
- **Query**: Query indexed blockchain data via The Graph
## Configuration Options
When creating an SDK instance, you can provide a configuration object with the following options:
```typescript
{
// Chain identifier - can be a name or chain ID
chain: 'testnet', // or 'devnet', 'local', or a chain ID
// Transport for blockchain communication
transport: http('https://rpc-url...'),
// Wallet client (if you have already created one)
wallet: walletClient,
// Account to use for transactions
account: '0x123...' or accountObject,
// Optional contract addresses (overrides defaults for the selected chain)
contracts: {
attestationService: '0x...',
// ... other contract addresses
}
}
```
## SDK Initialization Methods
The Cultura SDK offers different initialization methods depending on your use case:
### Read-Only Access: `create()`
```typescript
// Create SDK instance with default configuration (testnet)
const sdk = CulturaSDK.create()
// Create SDK instance for specific environment
const devnetSdk = CulturaSDK.create({ chain: 'devnet' })
const localSdk = CulturaSDK.create({ chain: 'local' })
```
The `create()` method initializes a read-only SDK instance without wallet connection. Use this when:
- You only need to query or read data from the blockchain (like token information, attestation details)
- You're building an application that displays blockchain data without write operations
- You need a fallback mode when a wallet isn't available
- You're working on server-side applications that only need to read data
Note that operations requiring transaction signing (like minting assets, creating attestations, or transferring tokens) will throw errors if attempted with a read-only instance.
### Wallet-Connected: `createWithWallet()` and `createWithAccount()`
```typescript
// Create SDK instance with wallet connection (uses testnet by default)
const walletSdk = CulturaSDK.createWithWallet(window.ethereum)
// Create SDK instance with wallet connection and specific chain
const localWalletSdk = CulturaSDK.createWithWallet(window.ethereum, {
chain: 'local',
// You can provide other configuration options here
})
// Create SDK instance with specific account address (read-only for transactions)
const addressSdk = CulturaSDK.createWithAccount('0x123...', { chain: 'testnet' })
// Create SDK instance with an account from a private key (full signing capability)
import { privateKeyToAccount } from 'viem/accounts'
const account = privateKeyToAccount('0xYourPrivateKeyHere')
const privateKeySdk = CulturaSDK.createWithAccount(account, { chain: 'testnet' })
```
Use these methods when your application needs to perform transactions like:
- Creating and minting Digital Assets
- Managing rights attestations
- Approving operations
- Transferring tokens
- Any other operation that requires transaction signing
## Query Example
Here's a quick example of querying data with a read-only SDK instance:
```typescript
import { CulturaSDK } from '@cultura/sdk'
// Create a read-only SDK instance for local development
const sdk = CulturaSDK.create({ chain: 'local' })
// Get the query client
const queryClient = sdk.query
// Example 1: Get all verified rights
async function getVerifiedRights() {
const verifiedRights = await queryClient.verifiedRights.getAll(10, 0)
console.log(`Found ${verifiedRights.length} verified rights:`)
verifiedRights.forEach((right) => {
console.log(`- ID: ${right.id}, Grade: ${right.grade}`)
console.log(` Asset Name: ${right.digitalAsset?.assetName || 'Unnamed'}`)
console.log(` Bond Amount: ${right.currentBondAmount}`)
console.log(` Is Verified: ${right.isVerified}`)
})
}
// Example 2: Get all digital assets
async function getDigitalAssets() {
const assets = await queryClient.digitalAsset.getAll(10, 0)
console.log(`Found ${assets.length} digital assets:`)
assets.forEach((asset) => {
console.log(`- Token ID: ${asset.tokenId}`)
console.log(` Owner: ${asset.owner.address}`)
console.log(` Name: ${asset.assetName || 'Unnamed'}`)
console.log(` Licensed Asset: ${asset.isLicensedAsset ? 'Yes' : 'No'}`)
})
}
// Example 3: Get verified rights for a specific owner
async function getRightsByOwner(ownerAddress) {
const ownerRights = await queryClient.verifiedRights.getByOwner(ownerAddress)
console.log(`Found ${ownerRights.length} rights for this owner:`)
ownerRights.forEach((right) => {
console.log(`- ID: ${right.id}, Grade: ${right.grade}`)
if (right.digitalAsset) {
console.log(` Asset: ${right.digitalAsset.assetName || 'Unnamed'}`)
}
})
}
// Example 4: Get licensed assets derived from a parent asset
async function getLicensedAssets(parentAssetId, contractAddress) {
const licensedAssets = await queryClient.digitalAsset.getLicensedAssets(
parentAssetId,
contractAddress
)
console.log(`Found ${licensedAssets.length} licensed assets:`)
licensedAssets.forEach((asset) => {
console.log(`- Token ID: ${asset.tokenId}`)
console.log(` Owner: ${asset.owner.address}`)
console.log(` Name: ${asset.assetName || 'Unnamed'}`)
})
}
// Run examples
async function runExamples() {
try {
await getVerifiedRights()
await getDigitalAssets()
await getRightsByOwner('0x70997970C51812dc3A010C7d01b50e0d17dc79C8')
await getLicensedAssets('1', '0x5FbDB2315678afecb367f032d93F642f64180aa3')
} catch (error) {
console.error('Error running examples:', error)
}
}
runExamples()
```
## Examples
For more comprehensive, in-depth examples of SDK usage flows, check out the examples in the `examples/` directory:
- `query-examples.ts`: Demonstrates various query operations using the SDK
- `verified-rights-licensing-flow.ts`: Shows a complete flow for verified rights licensing
You can run these examples to see the SDK in action and understand common integration patterns:
```bash
# Run the rights licensing flow example
npm run example
# or
yarn example
# or
pnpm example
# Run the query examples
npm run example:query
# or
yarn example:query
# or
pnpm example:query
```
## License
[MIT](./LICENSE.md)