Skip to content

Commit

Permalink
chore: cpmm contract call demo
Browse files Browse the repository at this point in the history
  • Loading branch information
cruzshia committed May 7, 2024
0 parents commit 0fb2bc0
Show file tree
Hide file tree
Showing 27 changed files with 9,158 additions and 0 deletions.
28 changes: 28 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module.exports = {
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
],
env: {
es6: true,
browser: true,
jest: true,
node: true,
},
rules: {
'@typescript-eslint/no-explicit-any': 0,
'object-shorthand': 'warn',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-unused-vars': 'warn',
'@typescript-eslint/no-empty-interface': 'off',
'react/display-name': 'off',
'@typescript-eslint/no-empty-function': 'off',
'react/prop-types': 'off',
'no-async-promise-executor': 'warn',
'prefer-const': 'warn',
},
};
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*.log
.DS_Store
node_modules
dist
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 CruzShia

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.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# RAYDIUM SDK V2 demo

## Getting Started

### Installation

`yarn install`

this will install the dependencies for running the demo script

### Prerequisites

Modify `src/common/connection.ts` to fit your configuration

- `<YOUR_WALLET_SECRET_KEY>`: replace to your own one
- `<YOUR_RPC_URL>`: replace to your prefer one

### Usage

- `yarn test` run all demo functions
- `yarn test test/<SCRIPT_NAME>.test.ts` run the specific demo test script. e.g. yarn test test/cpmm/create-pool.test.ts
- `yarn test test/<FOLDER_NAME>` run the specific feature all demo test script. e.g. yarn test test/cpmm/\*

### Skip test

if you want to skip some test function, modify test function `it(` -> `it.skip(` in test/xxx.test.ts file.
5 changes: 5 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
moduleNameMapper: {
'@/(.*)$': '<rootDir>/src/$1',
},
};
60 changes: 60 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"version": "0.1.0",
"license": "MIT",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=10"
},
"scripts": {
"test": "tsdx test",
"lint": "tsdx lint"
},
"peerDependencies": {},
"husky": {
"hooks": {
"pre-commit": "tsdx lint"
}
},
"prettier": {
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "es5"
},
"name": "sdk-demo-v2",
"author": "CruzShia",
"module": "dist/sdk-demo-v2.esm.js",
"size-limit": [
{
"path": "dist/sdk-demo-v2.cjs.production.min.js",
"limit": "10 KB"
},
{
"path": "dist/sdk-demo-v2.esm.js",
"limit": "10 KB"
}
],
"devDependencies": {
"@size-limit/preset-small-lib": "^11.1.2",
"husky": "^9.0.11",
"size-limit": "^11.1.2",
"tsdx": "^0.14.1",
"tslib": "^2.6.2",
"typescript": "^5.4.5"
},
"dependencies": {
"@project-serum/borsh": "^0.2.5",
"@solana/spl-token": "^0.4.6",
"@solana/web3.js": "^1.91.8",
"@types/bn.js": "^5.1.5",
"bn.js": "^5.2.1",
"bs58": "^5.0.0",
"buffer-layout": "^1.2.2",
"decimal.js": "^10.4.3"
}
}
42 changes: 42 additions & 0 deletions src/common/connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js';
import { TOKEN_PROGRAM_ID, AccountLayout, RawAccount } from '@solana/spl-token';
import bs58 from 'bs58';
import BN from 'bn.js';

let owner: Keypair | undefined;

export const connection = new Connection(clusterApiUrl('devnet')); //<YOUR_RPC_URL>
const PRIVATE_KEY = '<YOUR_WALLET_SECRET_KEY>';

let tokenAccounts = new Map<string, RawAccount & { publicKey?: PublicKey }>();
let solBalance = new BN(0);

export const initWallet = async () => {
owner = Keypair.fromSecretKey(bs58.decode(PRIVATE_KEY));

const solAccountResp = await connection.getAccountInfo(
owner.publicKey,
'confirmed'
);
if (solAccountResp) solBalance = new BN(solAccountResp.lamports);

const ownerTokenAccountResp = await connection.getTokenAccountsByOwner(
owner.publicKey,
{ programId: TOKEN_PROGRAM_ID },
'confirmed'
);

for (const { pubkey: publicKey, account } of ownerTokenAccountResp.value) {
const accountInfo = AccountLayout.decode(account.data);
tokenAccounts.set(accountInfo.mint.toBase58(), {
...accountInfo,
publicKey,
});
}

return {
owner,
tokenAccounts,
solBalance,
};
};
13 changes: 13 additions & 0 deletions src/common/math.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import BN from 'bn.js';

export function divCeil(a: BN, b: BN): BN {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const dm = a.divmod(b);

// Fast case - exact division
if (dm.mod.isZero()) return dm.div;

// Round up
return dm.div.isNeg() ? dm.div.isubn(1) : dm.div.iaddn(1);
}
40 changes: 40 additions & 0 deletions src/common/programId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { PublicKey, SystemProgram } from '@solana/web3.js';
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';

export const RENT_PROGRAM_ID = new PublicKey(
'SysvarRent111111111111111111111111111111111'
);

export const SYSTEM_PROGRAM_ID = SystemProgram.programId;
export const MEMO_PROGRAM_ID2 = new PublicKey(
'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'
);

export function findProgramAddress(
seeds: Array<Buffer | Uint8Array>,
programId: PublicKey
): {
publicKey: PublicKey;
nonce: number;
} {
const [publicKey, nonce] = PublicKey.findProgramAddressSync(seeds, programId);
return { publicKey, nonce };
}

export function getATAAddress(
owner: PublicKey,
mint: PublicKey,
programId?: PublicKey
): {
publicKey: PublicKey;
nonce: number;
} {
return findProgramAddress(
[
owner.toBuffer(),
(programId ?? TOKEN_PROGRAM_ID).toBuffer(),
mint.toBuffer(),
],
new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL')
);
}
42 changes: 42 additions & 0 deletions src/common/transaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {
Transaction,
TransactionInstruction,
PublicKey,
sendAndConfirmTransaction,
Connection,
Keypair,
} from '@solana/web3.js';
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';

export const printSimulate = (owner: PublicKey, transaction: Transaction) => {
transaction.feePayer = owner;
transaction.recentBlockhash = TOKEN_PROGRAM_ID.toBase58();

return transaction
.serialize({ requireAllSignatures: false, verifySignatures: false })
.toString('base64');
};

export const sendAndConfirm = async (props: {
connection: Connection;
owner: Keypair;
instructions: TransactionInstruction[];
}) => {
const { connection, owner, instructions } = props;

const transaction = new Transaction();
instructions.forEach(ins => {
transaction.add(ins);
});

let error: string | undefined;
try {
await sendAndConfirmTransaction(connection, transaction, [owner], {
commitment: 'confirmed',
});
} catch (e) {
error = (e as any).message;
}

return { error, transaction };
};
45 changes: 45 additions & 0 deletions src/cpmm/base/interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { PublicKey } from '@solana/web3.js';
import BN from 'bn.js';

export interface CpmmConfigInfoInterface {
bump: number;
disableCreatePool: boolean;
index: number;
tradeFeeRate: BN;
protocolFeeRate: BN;
fundFeeRate: BN;
createPoolFee: BN;

protocolOwner: PublicKey;
fundOwner: PublicKey;
}

export interface CpmmPoolInfoInterface {
configId: PublicKey;
poolCreator: PublicKey;
vaultA: PublicKey;
vaultB: PublicKey;

mintLp: PublicKey;
mintA: PublicKey;
mintB: PublicKey;

mintProgramA: PublicKey;
mintProgramB: PublicKey;

observationId: PublicKey;

bump: number;
status: number;

lpDecimals: number;
mintDecimalA: number;
mintDecimalB: number;

lpAmount: BN;
protocolFeesMintA: BN;
protocolFeesMintB: BN;
fundFeesMintA: BN;
fundFeesMintB: BN;
openTime: BN;
}
51 changes: 51 additions & 0 deletions src/cpmm/base/layout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { struct, seq, blob } from 'buffer-layout';
import { publicKey, u64, u8, u16, bool } from '@project-serum/borsh';

export const CpmmConfigInfoLayout = struct([
blob(8),
u8('bump'),
bool('disableCreatePool'),
u16('index'),
u64('tradeFeeRate'),
u64('protocolFeeRate'),
u64('fundFeeRate'),
u64('createPoolFee'),

publicKey('protocolOwner'),
publicKey('fundOwner'),
seq(u64(), 16),
]);

export const CpmmPoolInfoLayout = struct([
blob(8),

publicKey('configId'),
publicKey('poolCreator'),
publicKey('vaultA'),
publicKey('vaultB'),

publicKey('mintLp'),
publicKey('mintA'),
publicKey('mintB'),

publicKey('mintProgramA'),
publicKey('mintProgramB'),

publicKey('observationId'),

u8('bump'),
u8('status'),

u8('lpDecimals'),
u8('mintDecimalA'),
u8('mintDecimalB'),

u64('lpAmount'),
u64('protocolFeesMintA'),
u64('protocolFeesMintB'),
u64('fundFeesMintA'),
u64('fundFeesMintB'),
u64('openTime'),

seq(u64(), 32),
]);
Loading

0 comments on commit 0fb2bc0

Please sign in to comment.