English
API Service
Naming Service
๐Ÿ“ฌ
On-Chain Messaging Service
JS Library
โ€‹
โ€‹โ€‹
โ€‹
โ€‹

@bonfida/bot JS library

A JavaScript client library for interacting with the @bonfida/bot on-chain program. This library can be used for :
  • Creating pools.
  • Trading on behalf of pools by sending signals.
  • Depositing assets into a pool in exchange for pool tokens.
  • Redeeming pool tokens to retrieve an investement from the pool.

Installation

This library provides bindings for different pool operations. Adding it to a project is quite easy. Using npm:
1
npm install @bonfida/bot
Copied!
Using yarn:
1
yarn add @bonfida/bot
Copied!

Concepts

Pool state and locking

There are two scenarios in which a pool can find itself in a locked state :
  • There are pending orders : some Serum orders have not yet been settled with the settleFunds instruction.
  • There are fees to collect. At intervals greater than a week, signal provider and Bonfida fees must be extracted from the pool.
However, a locked pool can be unlocked with a sequence of permissionless operations. When the pool has pending orders, it is often possible to resolve the situation by running a settleFunds instruction. This is due to the fact that orders are either in the event queue and waiting to be consumed by Serum permissionless crankers, or waiting to be settled. When the pool has fees to collect, the permissionless collectFees instruction extracts all accrued fees from the pool and transfers those to defined signal provider (50% of fee) and Bonfida Bots Insurance Fund (25% of fee), as well as a FIDA buy and burn address (25% of fee).
TLDR: It is always possible for users to unlock the pool when they want to exit or even just enter into it.

Usage

Creating a pool

1
import { Connection, Account, PublicKey } from '@solana/web3.js';
2
import { createPool } from '@bonfida/bot';
3
import { signAndSendTransactionInstructions, Numberu64 } from '@bonfida/bot';
4
import { ENDPOINTS } from '@bonfida/bot';
5
โ€‹
6
const connection = new Connection(ENDPOINTS.mainnet);
7
โ€‹
8
const sourceOwnerAccount = new Account(['<MY PRIVATE KEY ARRAY>']);
9
const signalProviderAccount = new Account(['<MY PRIVATE KEY ARRAY AGAIN>']);
10
โ€‹
11
// The payer account will pay for the fees involved with the transaction.
12
// For the sake of simplicity, we choose the source owner.
13
const payerAccount = sourceOwnerAccount;
14
โ€‹
15
// Creating a pool means making the initial deposit.
16
// Any number of assets can be added. For each asset, the public key of the payer token account should be provided.
17
// The deposit amounts are also given, with the precision (mostly 6 decimals) of the respective token.
18
const sourceAssetKeys = [
19
new PublicKey('<First asset Key>'),
20
new PublicKey('<Second asset Key>'),
21
];
22
const deposit_amounts = [1000000, 1000000]; // This corresponds to 1 token of each with 6 decimals precisions
23
โ€‹
24
//Fetching the number of decimals using the mint of a token can be done with:
25
export const decimalsFromMint = async (
26
connection: Connection,
27
mint: PublicKey,
28
) => {
29
const result = await connection.getParsedAccountInfo(mint);
30
// @ts-ignore
31
const decimals = result?.value?.data?.parsed?.info?.decimals;
32
if (!decimals) {
33
throw new Error('Invalid mint');
34
}
35
return decimals;
36
};
37
โ€‹
38
// Maximum number of assets that can be held by the pool at any given time.
39
// A higher number means more flexibility but increases the initial pool account allocation fee.
40
const maxNumberOfAsset = 10;
41
โ€‹
42
// It is necessary for the purpose of security to hardcode all Serum markets that will be usable by the pool.
43
// It is advised to put here as many trusted markets with enough liquidity as required.
44
const allowedMarkets = [
45
new PublicKey('E14BKBhDWD4EuTkWj1ooZezesGxMW8LPCps4W5PuzZJo'),
46
]; // FIDA/USDC market address, for example
47
// Market addresses can be fetched with:
48
let marketAddress =
49
MARKETS[
50
MARKETS.map(m => {
51
return m.name;
52
}).lastIndexOf('<Market name, FIDA/USDC for instance>')
53
].address;
54
โ€‹
55
// Interval of time in seconds between two fee collections. This must be greater or equal to a week (604800 s).
56
// @ts-ignore
57
const feeCollectionPeriod = new Numberu64(604800);
58
โ€‹
59
// Total percentage of the pool to be collected as fees (which are split up between teh signal provider and Bonfida) at an interval defined by feeCollectionPeriod
60
// @ts-ignore
61
const feePercentage = 0.1;
62
โ€‹
63
const pool = async () => {
64
// Create pool
65
let [poolSeed, createInstructions] = await createPool(
66
connection,
67
sourceOwnerAccount.publicKey,
68
sourceAssetKeys,
69
signalProviderAccount.publicKey,
70
deposit_amounts,
71
maxNumberOfAsset,
72
allowedMarkets,
73
payerAccount.publicKey,
74
// @ts-ignore
75
feeCollectionPeriod,
76
// @ts-ignore
77
feePercentage,
78
);
79
โ€‹
80
await signAndSendTransactionInstructions(
81
connection,
82
[sourceOwnerAccount], // The owner of the source asset accounts must sign this transaction.
83
payerAccount,
84
createInstructions,
85
);
86
console.log('Created Pool');
87
};
88
โ€‹
89
pool();
Copied!

Signal provider operations

Sending an order to the pool as a signal provider
1
import { MARKETS } from '@project-serum/serum';
2
import { Connection, Account } from '@solana/web3.js';
3
import {
4
createOrder,
5
ENDPOINTS,
6
OrderSide,
7
OrderType,
8
SelfTradeBehavior,
9
} from '@bonfida/bot';
10
import { signAndSendTransactionInstructions, Numberu64 } from '@bonfida/bot';
11
import bs58 from 'bs58';
12
โ€‹
13
const connection = new Connection(ENDPOINTS.mainnet);
14
โ€‹
15
let marketInfo =
16
MARKETS[
17
MARKETS.map(m => {
18
return m.name;
19
}).lastIndexOf('<Market name, FIDA/USDC for instance>')
20
];
21
โ€‹
22
// Each @bonfida/bot pool is identified by a 32 byte pool seed
23
// This seed can be encoded as a base58 string which is similar to a public key.
24
let poolSeed = bs58.decode('<poolSeeds>');
25
โ€‹
26
const signalProviderAccount = new Account('<MY PRIVATE KEY ARRAY>');
27
โ€‹
28
const payerAccount = signalProviderAccount;
29
โ€‹
30
let side = OrderSide.Ask;
31
โ€‹
32
// The limit price is defined as the number of price currency lots required to pay for a lot of coin currency.
33
// The coin lot size and price currency lot sizes can be fetched via getMarketData from '@bonfida/bot'
34
// @ts-ignore
35
let limitPrice = new Numberu64(100000);
36
โ€‹
37
// The max quantity is defined as the maximum percentage of available coin assets to be exchanged in the transaction from the pool.
38
// If the order is an Ask, this equates to the maximum quantity willing to be sold.
39
// If the order is a Bid, this equates to the maximum quantity which is required to be bought.
40
// If the amountToTrade argument is specified to createOrder, it will overwrite this percentage with the absolute amount given.
41
let maxQuantityPercentage = 20;
42
โ€‹
43
// Until partial cancels of orders are implemented in Serum, the only supported order type for pools is IOC.
44
// This prevents long running limit orders from locking the pool and allows users to buy in and out of the pool
45
// at their owen convenience.
46
let orderType = OrderType.ImmediateOrCancel;
47
โ€‹
48
// The client_id can always be set to 0 for now. Its only use is to give the ability to refer to a particular order easily by this id in
49
// order to cancel it. Since only IOC orders are supported for now, the client_id can be set to any value.
50
// @ts-ignore
51
let clientId = new Numberu64(0);
52
โ€‹
53
// This only really matters for market makers. Since only IOC orders are supported for now, this parameter doesn't really matter.
54
let selfTradeBehavior = SelfTradeBehavior.DecrementTake;
55
โ€‹
56
const order = async () => {
57
let [openOrderAccount, createPoolTxInstructions] = await createOrder(
58
connection,
59
poolSeed,
60
marketInfo.address,
61
side,
62
limitPrice,
63
maxQuantityPercentage,
64
orderType,
65
clientId,
66
selfTradeBehavior,
67
null, // Self referring
68
payerAccount.publicKey,
69
);
70
โ€‹
71
await signAndSendTransactionInstructions(
72
connection,
73
[openOrderAccount, signalProviderAccount], // Required transaction signers
74
payerAccount,
75
createPoolTxInstructions,
76
);
77
console.log('Created Order for Pool');
78
};
79
โ€‹
80
order();
Copied!

Non-privileged operations

Depositing funds into a pool
In exchange for a distribution of tokens which is proportional to the current asset holdings of the pool, a pool will issue pool tokens which are redeemable for a commensurate proportion of pool assets at a later date. This operation represents the fundamental investment mechanism.
1
import { deposit } from '@bonfida/bot';
2
import { signAndSendTransactionInstructions, Numberu64 } from '@bonfida/bot';
3
import { BONFIDABOT_PROGRAM_ID } from '@bonfida/bot';
4
โ€‹
5
// This value represents the maximum amount of pool tokens being requested by the user
6
// If the source asset accounts happen to be underfunded for this value to be reached,
7
// The pool will attempt to issue as many pool tokens as possible to the client while
8
// proportionately extracting funds from the source asset accounts.
9
// The number of decimals is 6.
10
// @ts-ignore
11
const poolTokenAmount = new Numberu64(3000000);
12
โ€‹
13
const depositIntoPool = async () => {
14
// Deposit into Pool.
15
let depositTxInstructions = await deposit(
16
connection,
17
sourceOwnerAccount.publicKey,
18
sourceAssetKeys,
19
poolTokenAmount,
20
[poolSeed],
21
payerAccount.publicKey,
22
);
23
โ€‹
24
await signAndSendTransactionInstructions(
25
connection,
26
[sourceOwnerAccount], // Required transaction signer
27
payerAccount,
28
depositTxInstructions,
29
);
30
console.log('Deposited into Pool');
31
};
32
โ€‹
33
depositIntoPool();
Copied!
Retrieving funds from a pool
1
import { redeem } from '@bonfida/bot';
2
import { signAndSendTransactionInstructions, Numberu64 } from '@bonfida/bot';
3
โ€‹
4
// By setting this value to be lower than the actual pool token balance of the pool token account,
5
// It is possible to partially redeem assets from a pool.
6
// @ts-ignore
7
const poolTokenAmount = new Numberu64(1000000);
8
โ€‹
9
const redeemFromPool = async () => {
10
let redeemTxInstruction = await redeem(
11
connection,
12
sourceOwnerAccount.publicKey,
13
sourcePoolTokenKey,
14
sourceAssetKeys,
15
[poolSeed],
16
poolTokenAmount,
17
);
18
โ€‹
19
await signAndSendTransactionInstructions(
20
connection,
21
[sourceOwnerAccount], // Required transaction signer
22
payerAccount,
23
redeemTxInstruction,
24
);
25
console.log('Redeemed out of Pool');
26
};
27
โ€‹
28
redeemFromPool();
Copied!

Settling funds from an order

Once a Serum order has gone through, it is necessary to retrieve the funds from the openOrder account in order to unlock the pool for all deposit and redeem operations. Thankfully, this operation is permissionless which means that a locked pool is unlockable by anyone. This means that in order to make sure that a deposit or redeem instruction will go through, it is interesting to precede it with a settle instruction in the same transaction.
1
import { Account } from '@solana/web3.js';
2
import { settleFunds } from '@bonfida/bot';
3
import { signAndSendTransactionInstructions } from '@bonfida/bot';
4
โ€‹
5
const payerAccount = Account('<MY PRIVATE KEY ARRAY>');
6
โ€‹
7
// It is also possible to settle all openOrders for a pool via getPoolOrderInfos from '@bonfida/bot'
8
let settleFundsTxInstructions = await settleFunds(
9
connection,
10
poolSeed,
11
marketAddress,
12
OpenOrderAccount.address,
13
null,
14
);
15
โ€‹
16
await signAndSendTransactionInstructions(
17
connection,
18
[], // No signer is required for this transaction! (Except to pay for transaction fees)
19
payerAccount,
20
settleFundsTxInstructions,
21
);
22
console.log('Settled Funds');
Copied!

Triggering a fee collection operation

In order to unlock a potentially unlocked pool, or in order to trigger fee collection as a signal provider, it is necesary to activate the collectFees permissionless crank.
Beneficiary
Fee Proportion
Signal provider
50%
Bonfida
25%
FIDA buy and burn
25%
1
import { collectFees } from '@bonfida/bot';
2
import { signAndSendTransactionInstructions } from '@bonfida/bot';
3
โ€‹
4
let collectFeesTxInstruction = await collectFees(connection, [poolSeed]);
5
โ€‹
6
await signAndSendTransactionInstructions(
7
connection,
8
[],
9
payerAccount,
10
collectFeesTxInstruction,
11
);
12
console.log('Redeemed out of Pool');
Copied!
Last modified 4mo ago