# Sugar Money SDK

A TypeScript SDK for interacting with the Sugar Money Solana program and its API.

The **Sugar Money Program SDK** is meant to be used to interact with our solana program.

The **Sugar Money API SDK** is meant to be used to interact with the different API endpoints, also used by https://sugar.money.

## Table of Contents

- [Sugar Money SDK](#sugar-money-sdk)
  - [Table of Contents](#table-of-contents)
  - [Installation](#installation)
  - [Sugar Money Program SDK Usage](#sugar-money-program-sdk-usage)
    - [Init](#init)
    - [Configuration](#configuration)
    - [Key Features](#key-features)
    - [Examples](#examples)
      - [Execute a Trade](#execute-a-trade)
      - [Query Bonding Curve State](#query-bonding-curve-state)
    - [Error Handling](#error-handling)
  - [Sugar Money API SDK Usage](#sugar-money-api-sdk-usage)
    - [Init](#init-1)
    - [Configuration](#configuration-1)
    - [Examples](#examples-1)
      - [Free coin creation](#free-coin-creation)
      - [On chain coin creation](#on-chain-coin-creation)
    - [WebSocket API](#websocket-api)
      - [Connection](#connection)
      - [Subscribe to All Events](#subscribe-to-all-events)
      - [Connection Event Handlers](#connection-event-handlers)
      - [Available Event Types](#available-event-types)
      - [Disconnection](#disconnection)
    - [Payouts](#payouts)
    - [Error Handling](#error-handling-1)
  - [License](#license)

## <a id="installation"></a>Installation

```bash

npm install sugar-money

```

For program interactions we rely on:

```

"@solana/web3.js": "1.98.0",

```

The transaction instructions generated by the SDK are not v2 compatible.

## <a id="sugar-money-program-sdk-usage"></a>Sugar Money Program SDK Usage

### <a id="init"></a>Init

```typescript
import { SugarMoneyProgram, SugarMoneyProgramConfig } from 'sugar-money';

import { AnchorProvider, Wallet } from '@coral-xyz/anchor';
import { Connection, Keypair } from '@solana/web3.js';
import { bs58 } from '@coral-xyz/anchor/dist/cjs/utils/bytes';

const keypair = Keypair.fromSecretKey(
  bs58.decode(
    'your-base-58-secret-key',
  ),
);
const provider = new AnchorProvider(new Connection('RPC_URL'), new Wallet(keypair));
const sugarMoneyProgram = new SugarMoneyProgram(provider);

// Or specify a cluster
const sugarMoneyProgramConfig = new SugarMoneyProgramConfig('production');

const sugarMoneyProgram = new SugarMoneyProgram(provider, 'production', sugarMoneyProgramConfig);
```

### <a id="configuration"></a>Configuration

The Sugar Money Program SDK supports the following networks:

- `mainnet`

- `devnet`

- `localnet`

### <a id="key-features"></a>Key Features

1. **Trading Operations**
   - Execute buy/sell trades with exact input or output amounts

   - Support for slippage protection

   - Automatic fee calculation

2. **Bonding Curve Management**
   - Create and manage bonding curves

   - Query curve states and reserves

   - Track virtual and real token/SOL reserves

3. **Account Management**
   - Query global state

   - Manage authority and permissions

   - Handle token vaults and associated accounts

### <a id="examples"></a>Examples

#### <a id="execute-a-trade"></a>Execute a Trade

```typescript
import { BN } from '@coral-xyz/anchor';
import { SugarMoneyTradeDirectionEnum, SugarMoneyTradeTypeEnum } from 'sugar-money/program';

const tradeParams = {
  tradeType: SugarMoneyTradeTypeEnum.ExactIn,

  tradeDirection: SugarMoneyTradeDirectionEnum.Buy,

  amountToTrade: new BN(1000000000), // 1 SOL

  // value between 0 and 10000 with 0.001% precision

  slippage: 100, // 0.1%

  mint: tokenMintPublicKey,
};

const [tradeInfo, error] = await sugarMoneyProgram.getTrade(tradeParams);

if (error) {
  console.error('Trade error:', error);

  return;
}

console.log('Trade details:', {
  inputAmount: tradeInfo.inputAmount.toString(),

  outputAmount: tradeInfo.minmaxOutputAmount.toString(),

  price: tradeInfo.price.toString(),

  fee: tradeInfo.fee.toString(),
});
```

#### <a id="query-bonding-curve-state"></a>Query Bonding Curve State

```typescript
const [bondingCurvePda] = sugarMoneyProgram.getBondingCurveAccounts(mintPublicKey);

const curveState = await sugarMoneyProgram.deserializeCurve(bondingCurvePda.publicKey);

console.log('Curve state:', {
  realTokenReserve: curveState.realTokenReserve.toString(),

  realSolReserve: curveState.realSolReserve.toString(),

  virtualTokenReserve: curveState.virtualTokenReserve.toString(),

  virtualSolReserve: curveState.virtualSolReserve.toString(),
});
```

### <a id="error-handling"></a>Error Handling

The SDK provides custom error types for common scenarios:

- `SugarMoneyProgramRpcError`: RPC-related errors with transaction IDs

- `PermissionError`: Authorization-related errors

- `SlippageError`: Trade slippage validation errors

- `TradeError`: General trading-related errors

## <a id="sugar-money-api-sdk-usage"></a>Sugar Money API SDK Usage

### <a id="init-api"></a>Init

```typescript
import { SugarMoneyApi, SugarMoneyApiEnvironmentsEnum, generateSdkId } from 'sugar-money';

import { sign } from 'tweetnacl';

// usually you'd pass your wallet public key and a method to sign a message

const keypair = Keypair.generate();

// Generate a UUID once and reuse it throughout your application

const sdkId = generateSdkId();

const sugarMoneyApi = new SugarMoneyApi({
  environment: SugarMoneyApiEnvironmentsEnum.Preprod,

  sdkId, // Optional: helps with debugging integration issues
});

await sugarMoneyApi.login({
  publicKey: keypair.publicKey,

  signMessageFn: async (message: Uint8Array) => {
    return sign.detached(message, keypair.secretKey);
  },
});
```

**SDK ID Parameter**

The optional `sdkId` parameter helps debug issues while integrating the SDK. **If provided, it must be a valid UUID** to ensure uniqueness. This ID is sent with API requests and can be provided to support for faster issue resolution. It's optional and has no functional impact on the SDK's behavior.

**Generating UUIDs:**

The SDK provides a convenient `generateSdkId()` function that creates a RFC 4122 compliant UUID v4. Generate it once and reuse the same ID throughout your application:

```typescript
import { generateSdkId } from 'sugar-money';

const sdkId = generateSdkId(); // ⇨ 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
```

Alternatively, you can generate UUIDs using:

- Node.js: `import { randomUUID } from 'crypto'; randomUUID()`

- Browser: `crypto.randomUUID()`

### <a id="configuration-api"></a>Configuration

The API SDK supports the following networks:

- `production`

- `preprod`

- `staging`

- `development`

- `local`

### <a id="examples-api"></a>Examples

#### <a id="free-coin-creation"></a>Free coin creation

Coins can be created for free. These coins only exist in our backend until a first buy happens, at which point they are created on chain. The example below creates a coin in our backend. After this step you can perform the first buy to have it created on chain. You can also interact directly with `SugarMoneyProgram` to not go through the API.

```typescript
// login - the generated token lasts 30 days and is managed by the lib.

// you can pass an existing authToken to not have to keep logging in on app restart.

const authToken = await sugarMoneyApi.login({
  publicKey: keypair.publicKey,

  signMessageFn: async (message: Uint8Array) => {
    return sign.detached(message, keypair.secretKey);
  },
});

// coin metadata

const coinMetadata = {
  name: 'Test Coin',

  symbol: 'TEST',

  description: 'Test Coin Description',

  website: 'https://test.com',

  twitter: 'https://twitter.com/test',
};

// prepare your image

const imagePath = join(__dirname, 'test.jpg'); // Replace with your image path

const imageBuffer = readFileSync(imagePath);

const imageBlob = new Blob([imageBuffer], { type: 'image/jpg' });

Object.defineProperty(imageBlob, 'name', {
  value: 'image.jpg',

  writable: false,
});

// create coin

// returns SugarMoneyApiCoinResponseType, which contains the metadata_uri and coin address, needed to create the coin on chain

const coin = await api.coin.postCoin({
  metadata: coinMetadata,

  image: imageBlob as any,

  migrationInPsol: true, // defaults to true
});
```

#### <a id="on-chain-coin-creation"></a>On chain coin creation

```typescript
import { TradeDirectionEnum, TradeTypeEnum } from 'sugar-money/program';

// generate transaction instructions to create the coin

const [createIxs] = await sugarMoneyProgram.createIx(name, ticker, ipfsUrl, coinPublicKey);

const transaction = new Transaction();

transaction.add(...createIxs);

const solAmount = 0.1;

const coinMintPublicKey = '';

// generate transactions instructions for the initial buy

const tradeInfo = await sugarMoneyProgram.getTrade({
  tradeType: SugarMoneyTradeTypeEnum.ExactIn,

  amountToTrade: new BN(solAmount * LAMPORTS_PER_SOL),

  tradeDirection: SugarMoneyTradeDirectionEnum.Buy,

  mint: coinMintPublicKey,
});

transaction.add(tradeInfo.ix);

const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash({
  commitment: 'confirmed',
});

transaction.recentBlockhash = blockhash;

transaction.feePayer = wallet.publicKey;

const userSignedTx = await wallet.signTransaction?.(transaction);

const serializedTransaction = userSignedTx

  .serialize({
    requireAllSignatures: false,

    verifySignatures: false,
  })

  .toString('base64');

// send serialised transaction to the API for signing by the Sugar suffixed secret key,

// which will also broadcast the transaction

await sugarMoneyApi.coin.postSignTransaction({
  serialisedTx: serializedTransaction,

  mint: coinMintPublicKey,

  blockhash,

  lastValidBlockHeight,
});
```

### <a id="websocket"></a>WebSocket API

The Sugar Money API SDK includes real-time WebSocket support for monitoring token events, trades, price updates, and more. All WebSocket events are fully typed based on the official OpenAPI schema.

#### <a id="websocket-connection"></a>Connection

```typescript
// Connect to WebSocket with default options

const connection = await sugarMoneyApi.websocket.connect();

// Check connection status

console.log('State:', connection.getState()); // 'connected', 'connecting', 'disconnected', 'error'

console.log('Is connected:', connection.isConnected());
```

#### <a id="websocket-subscribe-all"></a>Subscribe to All Events

Use the `subscribeToAll` method to receive ALL WebSocket events with a single handler:

```typescript
// Subscribe to all events

sugarMoneyApi.websocket.subscribeToAll((message) => {
  console.log(`Event: ${message.type}`);

  switch (message.type) {
    case 'solana_price':
      const priceData = message.data as any; // SugarMoneyWebSocketSolanaPrice

      console.log(`SOL Price: ${priceData.price}`);

      break;

    case 'new_token':

    case 'token_create':
      const tokenData = message.data as any; // SugarMoneyWebSocketToken

      console.log(`Token: ${tokenData.name} (${tokenData.symbol})`);

      break;

    case 'token_trade':
      const tradeData = message.data as any; // SugarMoneyWebSocketTokenWithTradeData

      console.log(
        `Trade: ${tradeData.trade_data.is_buy ? 'BUY' : 'SELL'} ${tradeData.trade_data.sol_amount} SOL`,
      );

      break;

    case 'token_comment':
      const commentData = message.data as any; // SugarMoneyWebSocketTokenComment

      console.log(`Comment: "${commentData.message}" by ${commentData.user.username}`);

      break;

    case 'token_migrate':
      const migrateData = message.data as any; // SugarMoneyWebSocketToken

      console.log(`Migration: ${migrateData.name} migrated to Raydium`);

      break;

    case 'token_complete':
      const completeData = message.data as any; // SugarMoneyWebSocketToken

      console.log(`Completed: ${completeData.name} bonding curve complete`);

      break;

    case 'token_featured':
      const featuredData = message.data as any; // SugarMoneyWebSocketToken

      console.log(`Featured: ${featuredData.name} is featured`);

      break;

    default:
      console.log(`Unknown event: ${message.type}`);
  }
});

// Unsubscribe from all events

const handler = (message) => {
  /* ... */
};

sugarMoneyApi.websocket.subscribeToAll(handler);

// Later...

sugarMoneyApi.websocket.unsubscribeFromAll(handler);
```

#### <a id="websocket-connection-events"></a>Connection Event Handlers

```typescript
// Get the connection instance for advanced usage

const connection = sugarMoneyApi.websocket.getConnection();

// Handle connection events

connection.onConnection(() => {
  console.log('WebSocket connected!');
});

connection.onDisconnection(() => {
  console.log('WebSocket disconnected!');
});

connection.onError((error) => {
  console.error('WebSocket error:', error);
});

// You can also subscribe to specific events using the connection directly

connection.on('token_trade', (tradeData) => {
  console.log('Direct subscription to trades:', tradeData);
});
```

#### <a id="websocket-available-events"></a>Available Event Types

The WebSocket API supports the following event types:

- **`solana_price`** - Solana USD price updates

- **`new_token`** - New token creation events

- **`token_create`** - Token creation events

- **`token_trade`** - Real-time trading activity

- **`token_migrate`** - Token migration to Raydium

- **`token_complete`** - Bonding curve completion

- **`token_featured`** - Token featured events

- **`token_comment`** - New token comments

#### <a id="websocket-disconnection"></a>Disconnection

```typescript
// Disconnect manually

sugarMoneyApi.websocket.disconnect();

// Auto-reconnection is enabled by default

// Configure reconnection behavior:

const connection = await sugarMoneyApi.websocket.connect({
  autoReconnect: true,

  reconnectInterval: 3000, // 3 seconds

  maxReconnectAttempts: 5,
});
```

### <a id="payouts"></a>Payouts

All payouts follow the same standard, there are 3 endpoints:

**1. Request**

Create a request for a payout. The request payload is resource specific (please check the types) but the return type is always the same assuming no error occurred:

```typescript
{
  serialisedTransaction: string;

  blockhash: string;

  lastValidBlockHeight: number;

  nonce: number;
}
```

**2. Submit**

Submit the data to finalise the payout. To call this endpoint you have to sign the `serialisedTransaction` returned from calling `/request`. Example:

```typescript

  const transaction = Transaction.from(Buffer.from(response.serialisedTransaction, 'base64'));

  const signedTransaction = await wallet.signTransaction?.(transaction);

  const serialisedTransaction = signedTransaction

    .serialize({ requireAllSignatures: false, verifySignatures: false })

    .toString('base64'),


  sugarMoneyApi.tickets.payout.submit({

    signed_tx: serialisedTransaction,

    nonce: response.nonce,

    blockhash: response.blockhash,

    lastValidBlockHeight: response.lastValidBlockHeight,

  });

```

**3. Check Progress**

We use locking mechanisms for payouts and it may happen that you are unable to claim a payout due to a lock, please call this endpoint to verify whether there is a lock for your claim operation.

### <a id="error-handling-api"></a>Error Handling

// TODO

## <a id="license"></a>License

MIT License

Copyright (c) 2025 Sugar Money

Permission is hereby granted, free of charge, to any person obtaining a copy

of this software and associated documentation files (the "Software"), to deal

in the Software without restriction, including without limitation the rights

to use, copy, modify, merge, publish, distribute, sublicense, and/or sell

copies of the Software, and to permit persons to whom the Software is

furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all

copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR

IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER

LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,

OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE

SOFTWARE.
