# Synor SDK Documentation

Official multi-language SDKs for the Synor blockchain platform, providing unified access to all Synor services.

## Overview

The Synor SDK provides native implementations across **12 programming languages** for **12 blockchain services**, totaling **144 SDK implementations** with consistent APIs and patterns.

## Services

| Service | Description | Key Features |
|---------|-------------|--------------|
| **Compute** | Distributed heterogeneous compute | CPU/GPU/TPU/NPU workloads, tensor operations, ML inference |
| **Wallet** | Key management & signing | HD wallets, stealth addresses, transaction signing |
| **RPC** | Blockchain data queries | Blocks, transactions, WebSocket subscriptions |
| **Storage** | Decentralized file storage | IPFS integration, pinning, CAR files, directories |
| **Database** | Multi-model database | Key-Value, Document, Vector, Time Series stores |
| **Hosting** | Decentralized web hosting | Domains, DNS, deployments, SSL certificates |
| **Bridge** | Cross-chain transfers | Lock/mint, burn/unlock, multi-chain support |
| **Mining** | Mining pool integration | Stratum protocol, device management, statistics |
| **Economics** | Pricing & billing | Usage tracking, staking, rewards, invoices |
| **Governance** | DAO & voting | Proposals, delegation, vesting schedules |
| **Privacy** | Privacy-preserving transactions | Confidential TX, ring signatures, stealth addresses |
| **Contract** | Smart contract interaction | Deploy, call, events, ABI encoding, multicall |

## Language Support

| Language | Package Manager | Async Model | Status |
|----------|-----------------|-------------|--------|
| JavaScript/TypeScript | npm | Promise/async-await | ✅ Complete |
| Python | pip/poetry | asyncio | ✅ Complete |
| Go | go mod | goroutines | ✅ Complete |
| Rust | cargo | async/await | ✅ Complete |
| Java | maven/gradle | CompletableFuture | ✅ Complete |
| Kotlin | maven/gradle | Coroutines | ✅ Complete |
| Swift | SPM | async/await | ✅ Complete |
| Flutter/Dart | pub | Future | ✅ Complete |
| C | cmake | Callbacks | ✅ Complete |
| C++ | cmake | std::future | ✅ Complete |
| C#/.NET | nuget | Task/async | ✅ Complete |
| Ruby | gem | Fiber/async | ✅ Complete |

---

## Installation

### JavaScript/TypeScript

\`\`\`bash
npm install @synor/sdk
# or
yarn add @synor/sdk
# or
pnpm add @synor/sdk
\`\`\`

### Python

\`\`\`bash
pip install synor-compute synor-wallet synor-rpc synor-storage
pip install synor-database synor-hosting synor-bridge synor-mining
pip install synor-economics synor-governance synor-privacy synor-contract
\`\`\`

### Go

\`\`\`bash
go get github.com/synor/sdk-go
\`\`\`

### Rust

\`\`\`toml
# Cargo.toml
[dependencies]
synor = "0.1"
\`\`\`

### Java

\`\`\`xml
<!-- pom.xml -->
<dependency>
    <groupId>io.synor</groupId>
    <artifactId>synor-sdk</artifactId>
    <version>0.1.0</version>
</dependency>
\`\`\`

### Kotlin

\`\`\`kotlin
// build.gradle.kts
dependencies {
    implementation("io.synor:synor-sdk:0.1.0")
}
\`\`\`

### Swift

\`\`\`swift
// Package.swift
dependencies: [
    .package(url: "https://github.com/synor/sdk-swift.git", from: "0.1.0")
]
\`\`\`

### Flutter/Dart

\`\`\`yaml
# pubspec.yaml
dependencies:
  synor_sdk: ^0.1.0
\`\`\`

### C/C++

\`\`\`cmake
# CMakeLists.txt
find_package(synor REQUIRED)
target_link_libraries(your_app synor::synor)
\`\`\`

### C#/.NET

\`\`\`bash
dotnet add package Synor.Sdk
\`\`\`

### Ruby

\`\`\`ruby
# Gemfile
gem 'synor_compute'
gem 'synor_wallet'
gem 'synor_rpc'
gem 'synor_storage'
\`\`\`

---

## Quick Start

### Compute SDK

\`\`\`typescript
// JavaScript/TypeScript
import { SynorCompute } from '@synor/sdk';

const compute = new SynorCompute({ apiKey: 'your-api-key' });

// Matrix multiplication on GPU
const result = await compute.matmul(tensorA, tensorB, {
  precision: 'fp16',
  processor: 'gpu'
});

// ML inference
const prediction = await compute.infer({
  model: 'llama-70b',
  input: 'Hello, world!'
});
\`\`\`

\`\`\`python
# Python
from synor_compute import SynorCompute

compute = SynorCompute(api_key="your-api-key")

# Tensor operations
result = await compute.matmul(tensor_a, tensor_b, precision="fp16")
\`\`\`

### Wallet SDK

\`\`\`typescript
// JavaScript/TypeScript
import { SynorWallet } from '@synor/sdk';

const wallet = new SynorWallet({ apiKey: 'your-api-key' });

// Create a new wallet
const { wallet: newWallet, mnemonic } = await wallet.createWallet();

// Sign a transaction
const signed = await wallet.signTransaction(walletId, transaction);

// Get balance
const balance = await wallet.getBalance(address);
\`\`\`

\`\`\`go
// Go
import "github.com/synor/sdk-go/wallet"

client := wallet.NewClient(wallet.Config{ApiKey: "your-api-key"})

// Create wallet
result, _ := client.CreateWallet(ctx)

// Sign transaction
signed, _ := client.SignTransaction(ctx, walletId, tx)
\`\`\`

### RPC SDK

\`\`\`typescript
// JavaScript/TypeScript
import { SynorRpc } from '@synor/sdk';

const rpc = new SynorRpc({ apiKey: 'your-api-key' });

// Get latest block
const block = await rpc.getLatestBlock();

// Subscribe to new blocks (WebSocket)
const subscription = await rpc.subscribeBlocks((block) => {
  console.log('New block:', block.height);
});

// Send transaction
const result = await rpc.sendRawTransaction(signedTxHex);
\`\`\`

### Storage SDK

\`\`\`typescript
// JavaScript/TypeScript
import { SynorStorage } from '@synor/sdk';

const storage = new SynorStorage({ apiKey: 'your-api-key' });

// Upload file
const cid = await storage.upload(fileBuffer);

// Download file
const data = await storage.download(cid);

// Pin content
await storage.pin(cid, { duration: 365 * 24 * 60 * 60 }); // 1 year
\`\`\`

### Database SDK

\`\`\`typescript
// JavaScript/TypeScript
import { SynorDatabase } from '@synor/sdk';

const db = new SynorDatabase({ apiKey: 'your-api-key' });

// Key-Value store
await db.kv.set('user:123', { name: 'Alice' });
const user = await db.kv.get('user:123');

// Document store
const docId = await db.documents.create('users', { name: 'Bob', age: 30 });
const docs = await db.documents.query('users', { filter: { age: { $gt: 25 } } });

// Vector store (for AI/embeddings)
await db.vectors.upsert('embeddings', [
  { id: 'doc1', vector: [0.1, 0.2, ...], metadata: { title: 'Doc 1' } }
]);
const results = await db.vectors.search('embeddings', queryVector, 10);

// Time series
await db.timeseries.write('metrics', [
  { timestamp: Date.now(), value: 42.5, tags: { host: 'server-1' } }
]);
\`\`\`

### Contract SDK

\`\`\`typescript
// JavaScript/TypeScript
import { SynorContract } from '@synor/sdk';

const contract = new SynorContract({ apiKey: 'your-api-key' });

// Deploy contract
const { contractAddress, transactionHash } = await contract.deploy({
  bytecode: '0x...',
  abi: contractAbi,
  constructorArgs: ['arg1', 100]
});

// Call view function
const result = await contract.call({
  contract: contractAddress,
  method: 'balanceOf',
  args: [userAddress],
  abi: contractAbi
});

// Send transaction
const txResult = await contract.send({
  contract: contractAddress,
  method: 'transfer',
  args: [recipient, amount],
  abi: contractAbi
});

// Get events
const events = await contract.getEvents({
  contract: contractAddress,
  event: 'Transfer',
  fromBlock: 1000000
});
\`\`\`

### Privacy SDK

\`\`\`typescript
// JavaScript/TypeScript
import { SynorPrivacy } from '@synor/sdk';

const privacy = new SynorPrivacy({ apiKey: 'your-api-key' });

// Create confidential transaction
const confTx = await privacy.createConfidentialTx(inputs, outputs);

// Ring signature
const ringSig = await privacy.createRingSignature(message, ringPublicKeys);
const isValid = await privacy.verifyRingSignature(ringSig, message);

// Stealth address
const stealthAddr = privacy.generateStealthAddress();
\`\`\`

### Bridge SDK

\`\`\`typescript
// JavaScript/TypeScript
import { SynorBridge } from '@synor/sdk';

const bridge = new SynorBridge({ apiKey: 'your-api-key' });

// Lock tokens on source chain
const lockReceipt = await bridge.lock({
  asset: { symbol: 'ETH', chain: 'ethereum' },
  amount: '1000000000000000000', // 1 ETH in wei
  targetChain: 'synor'
});

// Check transfer status
const status = await bridge.getTransferStatus(lockReceipt.transferId);

// Get supported chains
const chains = await bridge.getSupportedChains();
\`\`\`

---

## Configuration

All SDKs share a common configuration pattern:

\`\`\`typescript
interface SynorConfig {
  apiKey: string;           // Required: Your API key
  endpoint?: string;        // Optional: Custom API endpoint
  timeout?: number;         // Optional: Request timeout (ms), default: 30000
  retries?: number;         // Optional: Retry attempts, default: 3
  debug?: boolean;          // Optional: Enable debug logging
}
\`\`\`

### Service-Specific Endpoints

| Service | Default Endpoint |
|---------|------------------|
| Compute | \`https://compute.synor.io/v1\` |
| Wallet | \`https://wallet.synor.io/v1\` |
| RPC | \`https://rpc.synor.io/v1\` |
| Storage | \`https://storage.synor.io/v1\` |
| Database | \`https://db.synor.io/v1\` |
| Hosting | \`https://hosting.synor.io/v1\` |
| Bridge | \`https://bridge.synor.io/v1\` |
| Mining | \`https://mining.synor.io/v1\` |
| Economics | \`https://economics.synor.io/v1\` |
| Governance | \`https://governance.synor.io/v1\` |
| Privacy | \`https://privacy.synor.io/v1\` |
| Contract | \`https://contract.synor.io/v1\` |

---

## Error Handling

All SDKs use a consistent error hierarchy:

\`\`\`typescript
class SynorError extends Error {
  code?: string;        // Error code (e.g., 'INVALID_API_KEY')
  statusCode?: number;  // HTTP status code
}

// Specific error types
class ApiError extends SynorError {}          // HTTP/API errors
class ValidationError extends SynorError {}   // Invalid input
class TimeoutError extends SynorError {}      // Request timeout
class AuthenticationError extends SynorError {} // Auth failures
class NetworkError extends SynorError {}      // Connection issues
\`\`\`

### Error Handling Example

\`\`\`typescript
try {
  const result = await wallet.createWallet();
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof TimeoutError) {
    console.error('Request timed out, retrying...');
  } else if (error instanceof ApiError) {
    console.error(\`API error \${error.code}: \${error.message}\`);
  }
}
\`\`\`

---

## WebSocket Subscriptions

RPC and other services support real-time subscriptions:

\`\`\`typescript
// Subscribe to new blocks
const blockSub = await rpc.subscribeBlocks((block) => {
  console.log('New block:', block.height);
});

// Subscribe to address transactions
const addrSub = await rpc.subscribeAddress(address, (tx) => {
  console.log('New transaction:', tx.hash);
});

// Subscribe to mempool
const mempoolSub = await rpc.subscribeMempool((tx) => {
  console.log('Mempool tx:', tx.hash);
});

// Cancel subscription
blockSub.cancel();
\`\`\`

---

## Directory Structure

\`\`\`
sdk/
├── js/                  # JavaScript/TypeScript SDK
│   └── src/
│       ├── wallet/
│       ├── rpc/
│       ├── storage/
│       └── ...
├── python/              # Python SDK
│   ├── synor_compute/
│   ├── synor_wallet/
│   └── src/
│       ├── synor_database/
│       └── ...
├── go/                  # Go SDK
│   ├── synor.go         # Compute
│   ├── wallet/
│   ├── rpc/
│   └── ...
├── rust/                # Rust SDK
│   └── src/
│       ├── wallet/
│       ├── rpc/
│       └── ...
├── java/                # Java SDK
│   └── src/main/java/io/synor/
│       ├── compute/
│       ├── wallet/
│       └── ...
├── kotlin/              # Kotlin SDK
│   └── src/main/kotlin/io/synor/
│       ├── compute/
│       ├── wallet/
│       └── ...
├── swift/               # Swift SDK
│   └── Sources/
│       ├── SynorCompute/
│       ├── SynorPrivacy/
│       ├── SynorContract/
│       └── Synor/
│           ├── Wallet/
│           ├── Rpc/
│           └── ...
├── flutter/             # Flutter/Dart SDK
│   └── lib/src/
│       ├── wallet/
│       ├── rpc/
│       └── ...
├── c/                   # C SDK
│   ├── include/synor/
│   └── src/
├── cpp/                 # C++ SDK
│   ├── include/synor/
│   └── src/
│       ├── wallet/
│       ├── rpc/
│       └── ...
├── csharp/              # C#/.NET SDK
│   ├── SynorCompute/
│   ├── Synor.Sdk/
│   │   ├── Wallet/
│   │   ├── Rpc/
│   │   └── ...
│   └── src/
│       ├── Synor.Privacy/
│       └── Synor.Contract/
├── ruby/                # Ruby SDK
│   └── lib/
│       ├── synor_compute/
│       ├── synor_wallet/
│       └── ...
└── shared/              # Shared schemas and test vectors
    ├── schemas/
    └── test-vectors/
\`\`\`

---

## Testing

Each SDK includes comprehensive tests. Run tests locally:

\`\`\`bash
# JavaScript
cd sdk/js && npm test

# Python
cd sdk/python && pytest

# Go
cd sdk/go && go test ./...

# Rust
cd sdk/rust && cargo test

# Java
cd sdk/java && mvn test

# Kotlin
cd sdk/kotlin && ./gradlew test

# C#
cd sdk/csharp && dotnet test

# Ruby
cd sdk/ruby && bundle exec rspec
\`\`\`

---

## Contributing

1. Fork the repository
2. Create a feature branch
3. Implement changes following the SDK patterns
4. Add tests for new functionality
5. Submit a pull request

### SDK Development Guidelines

- **Consistent APIs**: All languages should have equivalent functionality
- **Async by default**: Use language-native async patterns
- **Error handling**: Use the standard error hierarchy
- **Documentation**: Include doc comments and examples
- **Testing**: Maintain >90% test coverage

---

## Version History

| Version | Date | Changes |
|---------|------|---------|
| 0.1.0 | 2026-01-28 | Initial release with all 12 services across 12 languages |

---

## License

MIT License - see [LICENSE](../LICENSE) for details.

---

## Support

- Documentation: https://docs.synor.io
- GitHub Issues: https://github.com/synor/sdk/issues
- Discord: https://discord.gg/synor
