npm package: @fliidotdev/blinks-core
Description: Core functionality for Solana Blinks SDK
Author: fliidotdev
Latest version: 0.1.3

# @fliidotdev/blinks-core

Core functionality for building Solana Blinks and Actions. This package provides the foundational components and utilities for creating blockchain-powered interactive experiences.

## Installation

```bash
npm install @fliidotdev/blinks-core
# or
yarn add @fliidotdev/blinks-core
# or
pnpm add @fliidotdev/blinks-core
```

## Features

- **Solana Integration**: Direct integration with Solana blockchain
- **Action Handlers**: Process and execute blockchain actions
- **Transaction Building**: Simplified transaction creation and signing
- **Wallet Connection**: Support for multiple Solana wallets
- **Error Handling**: Comprehensive error handling and recovery
- **Type Safety**: Full TypeScript support with strict typing
- **Performance Optimized**: Lightweight and efficient

## Quick Start

```typescript
import { BlinkCore, createAction, executeTransaction } from '@fliidotdev/blinks-core';
import { Connection, PublicKey } from '@solana/web3.js';

// Initialize connection
const connection = new Connection('https://api.mainnet-beta.solana.com');
const blink = new BlinkCore({
  connection,
  network: 'mainnet-beta'
});

// Create an action
const action = createAction({
  type: 'transfer',
  params: {
    recipient: new PublicKey('...'),
    amount: 1000000000, // 1 SOL in lamports
    memo: 'Payment for services'
  }
});

// Execute the action
const signature = await blink.execute(action);
console.log('Transaction signature:', signature);
```

## Core Concepts

### Actions

Actions are the fundamental building blocks of Blinks. They represent blockchain operations that users can perform.

```typescript
import { Action, ActionType } from '@fliidotdev/blinks-core';

const transferAction: Action = {
  type: ActionType.TRANSFER,
  label: 'Send SOL',
  description: 'Transfer SOL to another wallet',
  icon: '💸',
  params: {
    recipient: 'wallet_address',
    amount: 1.5
  }
};
```

### Blinks

Blinks are interactive blockchain links that execute actions when triggered.

```typescript
import { createBlink } from '@fliidotdev/blinks-core';

const paymentBlink = createBlink({
  title: 'Pay Invoice #1234',
  description: 'Payment for consulting services',
  action: transferAction,
  metadata: {
    invoiceId: '1234',
    dueDate: '2024-12-31'
  }
});

// Generate shareable URL
const blinkUrl = paymentBlink.toUrl();
```

### Transaction Building

Build complex transactions with multiple instructions:

```typescript
import { TransactionBuilder } from '@fliidotdev/blinks-core';

const builder = new TransactionBuilder(connection);

await builder
  .addTransfer({
    from: wallet.publicKey,
    to: recipientKey,
    amount: 1000000000
  })
  .addMemo('Payment for order #5678')
  .build();

const signature = await builder.send(wallet);
```

## API Reference

### `BlinkCore`

Main class for interacting with Blinks.

#### Constructor

```typescript
new BlinkCore(config: BlinkConfig)
```

**Parameters:**
- `config.connection` - Solana RPC connection
- `config.network` - Network type ('mainnet-beta' | 'devnet' | 'testnet')
- `config.wallet?` - Optional wallet adapter

#### Methods

##### `execute(action: Action): Promise<string>`

Execute an action and return the transaction signature.

##### `validateAction(action: Action): boolean`

Validate an action before execution.

##### `estimateFees(action: Action): Promise<number>`

Estimate transaction fees in lamports.

### `createAction`

Factory function for creating actions.

```typescript
createAction(config: ActionConfig): Action
```

**Parameters:**
- `config.type` - Action type
- `config.params` - Action parameters
- `config.validation?` - Optional validation rules

### `createBlink`

Factory function for creating Blinks.

```typescript
createBlink(config: BlinkConfig): Blink
```

### Action Types

```typescript
enum ActionType {
  TRANSFER = 'transfer',
  SWAP = 'swap',
  STAKE = 'stake',
  MINT = 'mint',
  BURN = 'burn',
  CUSTOM = 'custom'
}
```

## Advanced Usage

### Custom Actions

Create custom actions for specific use cases:

```typescript
import { createCustomAction } from '@fliidotdev/blinks-core';

const customAction = createCustomAction({
  name: 'multi-sig-transfer',
  handler: async (params) => {
    // Custom logic here
    return {
      instructions: [...],
      signers: [...]
    };
  },
  validator: (params) => {
    // Validation logic
    return params.amount > 0;
  }
});
```

### Batch Operations

Execute multiple actions in a single transaction:

```typescript
import { batchExecute } from '@fliidotdev/blinks-core';

const results = await batchExecute([
  transferAction1,
  transferAction2,
  swapAction
], {
  parallel: false,
  stopOnError: true
});
```

### Error Handling

```typescript
import { BlinkError, ErrorCode } from '@fliidotdev/blinks-core';

try {
  await blink.execute(action);
} catch (error) {
  if (error instanceof BlinkError) {
    switch (error.code) {
      case ErrorCode.INSUFFICIENT_FUNDS:
        console.error('Not enough SOL');
        break;
      case ErrorCode.NETWORK_ERROR:
        console.error('Network issue');
        break;
      default:
        console.error('Unknown error:', error.message);
    }
  }
}
```

## Integration with Wallets

### Phantom Wallet

```typescript
import { PhantomAdapter } from '@fliidotdev/blinks-core/adapters';

const adapter = new PhantomAdapter();
await adapter.connect();

const blink = new BlinkCore({
  connection,
  wallet: adapter
});
```

### Solflare Wallet

```typescript
import { SolflareAdapter } from '@fliidotdev/blinks-core/adapters';

const adapter = new SolflareAdapter();
// ... similar setup
```

## Testing

```typescript
import { MockBlink, MockWallet } from '@fliidotdev/blinks-core/testing';

describe('Blink Actions', () => {
  it('should execute transfer', async () => {
    const mockBlink = new MockBlink();
    const mockWallet = new MockWallet();
    
    const result = await mockBlink.execute({
      type: ActionType.TRANSFER,
      params: { amount: 1 }
    });
    
    expect(result).toBeDefined();
  });
});
```

## Best Practices

1. **Always validate actions** before execution
2. **Handle errors gracefully** with proper user feedback
3. **Estimate fees** before submitting transactions
4. **Use environment variables** for RPC endpoints
5. **Implement retry logic** for network failures
6. **Log transactions** for debugging and audit

## Configuration

### Environment Variables

```bash
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
SOLANA_NETWORK=mainnet-beta
DEFAULT_COMMITMENT=confirmed
```

### Custom RPC

```typescript
const blink = new BlinkCore({
  connection: new Connection(process.env.SOLANA_RPC_URL, {
    commitment: 'confirmed',
    confirmTransactionInitialTimeout: 60000
  })
});
```

## Migration Guide

### From v0.x to v1.x

```typescript
// Before (v0.x)
import Blink from '@fliidotdev/blinks-core';
const blink = new Blink();

// After (v1.x)
import { BlinkCore } from '@fliidotdev/blinks-core';
const blink = new BlinkCore({ connection });
```

## Troubleshooting

### Common Issues

1. **Transaction timeout**: Increase confirmation timeout
2. **Insufficient SOL**: Ensure wallet has enough SOL for fees
3. **Network congestion**: Implement retry with exponential backoff
4. **Invalid keypair**: Verify wallet connection

## Performance

- Average action execution: ~2-3 seconds
- Transaction confirmation: ~400ms (with proper RPC)
- Bundle size: ~45KB minified

## Security

- Never expose private keys
- Validate all user inputs
- Use secure RPC endpoints
- Implement rate limiting
- Audit smart contract interactions

## License

MIT © [fliidotdev](https://github.com/fliidotdev)

## Contributing

Contributions are welcome! Please see our [Contributing Guide](https://github.com/fliidotdev/blinks-sdk/blob/main/CONTRIBUTING.md).

## Support

- [Documentation](https://docs.flii.dev/blinks)
- [GitHub Issues](https://github.com/fliidotdev/blinks-sdk/issues)
- [Discord Community](https://discord.gg/fliidotdev)