Skip to content

Commit 8a7ac89

Browse files
0xDazzergbarkhatov
andauthored
feat: add babylon sdk (#32)
* feat: add babylon sdk * chore: add imports * chore: prettier * chore: build-proto format * chore: scripts * chore: update readme * chore: format:fix --------- Co-authored-by: Govard Barkhatov <[email protected]>
1 parent c45e532 commit 8a7ac89

File tree

14 files changed

+948
-81
lines changed

14 files changed

+948
-81
lines changed

package-lock.json

Lines changed: 377 additions & 47 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
node_modules
2+
dist
3+
build
4+
coverage
5+
.circleci
6+
.husky
7+
.next
8+
docs
9+
public
10+
README.md
11+
src/generated
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"semi": true,
3+
"singleQuote": false,
4+
"tabWidth": 2,
5+
"useTabs": false,
6+
"plugins": ["prettier-plugin-organize-imports"]
7+
}

packages/babylon-proto-ts/README.md

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,138 @@
1515
npm i @babylonlabs-io/babylon-proto-ts
1616
```
1717

18+
## 🚀 Quick Start
19+
20+
This library provides TypeScript bindings for the Babylon Bitcoin Staking Protocol, offering both low-level protobuf exports and high-level client abstractions.
21+
22+
### Basic Usage
23+
24+
Use the SDK to access the client, messages, and utilities:
25+
26+
```typescript
27+
import { createBabylonSDK } from "@babylonlabs-io/babylon-proto-ts";
28+
29+
const sdk = createBabylonSDK({ rpcUrl: "https://babylon-rpc.example.com" });
30+
31+
// Connect the client
32+
await sdk.connect();
33+
34+
// Query rewards for an address
35+
const rewards = await sdk.client.getRewards("bbn1...");
36+
37+
// Query balance
38+
const balance = await sdk.client.getBalance("bbn1...", "ubbn");
39+
40+
// Get Bitcoin tip height
41+
const btcTipHeight = await sdk.client.getBTCTipHeight();
42+
```
43+
44+
### Wallet Integration
45+
46+
For applications that need to create and sign transactions, use the provided registry and amino types:
47+
48+
```typescript
49+
import { createBabylonSDK } from "@babylonlabs-io/babylon-proto-ts";
50+
import { SigningStargateClient } from "@cosmjs/stargate";
51+
52+
const sdk = createBabylonSDK({ rpcUrl: "https://babylon-rpc.example.com" });
53+
54+
// Create signing client with Babylon support
55+
const client = await SigningStargateClient.connectWithSigner(
56+
rpc,
57+
offlineSigner as OfflineSigner,
58+
{
59+
registry: sdk.utils.createRegistry(),
60+
aminoTypes: sdk.utils.createAminoTypes(),
61+
},
62+
);
63+
64+
// Create messages using the SDK
65+
const withdrawMsg = sdk.messages.createWithdrawRewardMsg("bbn1...");
66+
67+
// Sign and broadcast
68+
const result = await client.signAndBroadcast("bbn1...", [withdrawMsg], "auto");
69+
```
70+
71+
### Direct Protobuf Access
72+
73+
For advanced use cases, you can import protobuf types directly:
74+
75+
```typescript
76+
import { btcstaking, incentivequery } from "@babylonlabs-io/babylon-proto-ts"
77+
78+
// Use protobuf types directly
79+
const stakingParams = btcstaking.Params.fromPartial({...})
80+
const rewardQuery = incentivequery.QueryRewardGaugesRequest.fromPartial({...})
81+
```
82+
83+
## 📚 API Reference
84+
85+
### SDK Functions
86+
87+
#### `createBabylonSDK(config: BabylonConfig): BabylonSDK`
88+
89+
Creates a comprehensive SDK instance with client, messages, and utilities.
90+
91+
- **Parameters:**
92+
- `config.rpcUrl`: RPC endpoint URL for the Babylon network
93+
- **Returns:** SDK object with `client`, `messages`, `utils`, and `connect()` method
94+
95+
### SDK Methods
96+
97+
#### `sdk.connect(): Promise<void>`
98+
99+
Initializes the client connection to the Babylon network.
100+
101+
### Client Methods (via sdk.client)
102+
103+
#### `sdk.client.getRewards(address: string): Promise<number>`
104+
105+
Retrieves the total rewards for a given address.
106+
107+
- **Parameters:**
108+
- `address`: The Babylon address to query
109+
- **Returns:** Total rewards amount (number)
110+
111+
#### `sdk.client.getBalance(address: string, denom?: string): Promise<number>`
112+
113+
Gets the balance of a specific token for an address.
114+
115+
- **Parameters:**
116+
- `address`: The Babylon address to query
117+
- `denom`: Token denomination (defaults to "ubbn")
118+
- **Returns:** Balance amount (number)
119+
120+
#### `sdk.client.getBTCTipHeight(): Promise<number>`
121+
122+
Retrieves the current Bitcoin blockchain tip height.
123+
124+
- **Returns:** Bitcoin tip height (number)
125+
126+
### SDK Messages
127+
128+
#### `sdk.messages.createWithdrawRewardMsg(address: string)`
129+
130+
Creates a message for withdrawing rewards from Bitcoin staking.
131+
132+
- **Parameters:**
133+
- `address`: The Babylon address to withdraw rewards for
134+
- **Returns:** Message object with proper typeUrl and value, ready for signing and broadcasting
135+
136+
### SDK Utilities
137+
138+
#### `sdk.utils.createRegistry(): Registry`
139+
140+
Creates a CosmJS registry with all Babylon message types registered.
141+
142+
#### `sdk.utils.createAminoTypes(): AminoTypes`
143+
144+
Creates amino types for Babylon messages, required for hardware wallet compatibility.
145+
146+
### Protobuf Exports
147+
148+
The library exports all generated protobuf types directly, allowing for advanced use cases
149+
18150
## 📝 Commit Format & Automated Releases
19151

20152
This project uses [**Conventional Commits**](https://www.conventionalcommits.org/en/v1.0.0/)

packages/babylon-proto-ts/package.json

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@
44
"main": "./dist/index.js",
55
"types": "./dist/index.d.ts",
66
"scripts": {
7-
"build-proto": "node scripts/build-proto.js"
7+
"build": "tsc && node scripts/build-proto.js",
8+
"prepublishOnly": "npm run build",
9+
"prepare": "husky",
10+
"format": "prettier --check \"src/**/*.ts\"",
11+
"format:fix": "prettier --write \"src/**/*.ts\""
812
},
913
"files": [
1014
"dist",
@@ -20,10 +24,16 @@
2024
"description": "",
2125
"devDependencies": {
2226
"@bufbuild/buf": "^1.45.0",
23-
"shelljs": "^0.8.5"
27+
"prettier": "^3.2.5",
28+
"prettier-plugin-organize-imports": "^4.1.0",
29+
"shelljs": "^0.8.5",
30+
"typescript": "^5.6.3"
2431
},
2532
"dependencies": {
26-
"@bufbuild/protobuf": "^2.2.0"
33+
"@bufbuild/protobuf": "^2.2.0",
34+
"@cosmjs/proto-signing": "^0.33.1",
35+
"@cosmjs/stargate": "^0.33.1",
36+
"@cosmjs/tendermint-rpc": "^0.33.1"
2737
},
2838
"publishConfig": {
2939
"access": "public"
Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,39 @@
11
// scripts/build-proto.js
2-
const shell = require("shelljs")
2+
const shell = require("shelljs");
33

4-
const BABYLON_REPO_URL = "https://github.com/babylonlabs-io/babylon.git"
5-
const BABYLON_REPO_DIR = "babylon"
6-
const PROTO_DIR = "proto"
4+
const BABYLON_REPO_URL = "https://github.com/babylonlabs-io/babylon.git";
5+
const BABYLON_REPO_DIR = "babylon";
6+
const PROTO_DIR = "proto";
77

88
const BABYLON_REPO_TAG = "v1.0.0";
99

1010
const generateProto = async () => {
1111
try {
1212
// Clone the Babylon repository
13-
console.log("Cloning the Babylon repository...")
14-
shell.exec(`git clone --depth 1 --branch ${BABYLON_REPO_TAG} ${BABYLON_REPO_URL} ${BABYLON_REPO_DIR}`)
13+
console.log("Cloning the Babylon repository...");
14+
shell.exec(
15+
`git clone --depth 1 --branch ${BABYLON_REPO_TAG} ${BABYLON_REPO_URL} ${BABYLON_REPO_DIR}`,
16+
);
1517

1618
// Copy the proto files
17-
console.log("Copying proto files...")
18-
shell.mkdir("-p", PROTO_DIR)
19-
shell.cp("-R", `${BABYLON_REPO_DIR}/proto/*`, PROTO_DIR)
19+
console.log("Copying proto files...");
20+
shell.mkdir("-p", PROTO_DIR);
21+
shell.cp("-R", `${BABYLON_REPO_DIR}/proto/*`, PROTO_DIR);
2022

2123
// Generate TypeScript code using buf
22-
console.log("Generating TypeScript code...")
23-
shell.exec("npx buf generate proto")
24+
console.log("Generating TypeScript code...");
25+
shell.exec("npx buf generate proto");
2426

2527
// Clean up
26-
console.log("Cleaning up...")
27-
shell.rm("-rf", PROTO_DIR)
28-
shell.rm("-rf", BABYLON_REPO_DIR)
28+
console.log("Cleaning up...");
29+
shell.rm("-rf", PROTO_DIR);
30+
shell.rm("-rf", BABYLON_REPO_DIR);
2931

30-
console.log("Build completed successfully.")
32+
console.log("Build completed successfully.");
3133
} catch (error) {
32-
console.error("Error during build:", error)
33-
process.exit(1)
34+
console.error("Error during build:", error);
35+
process.exit(1);
3436
}
35-
}
37+
};
3638

37-
generateProto()
39+
generateProto();
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export const REWARD_GAUGE_KEY_BTC_DELEGATION = "BTC_STAKER";
2+
export const BTC_STAKER = "btc_staker";
3+
export const REGISTRY_TYPE_URLS = {
4+
MsgCreateBTCDelegation: "/babylon.btcstaking.v1.MsgCreateBTCDelegation",
5+
MsgWithdrawReward: "/babylon.incentive.MsgWithdrawReward",
6+
};
Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1-
export * as btcstakingtx from './generated/babylon/btcstaking/v1/tx';
2-
export * as btcstaking from './generated/babylon/btcstaking/v1/btcstaking';
3-
export * as btcstakingpop from './generated/babylon/btcstaking/v1/pop';
4-
export * as btccheckpoint from './generated/babylon/btccheckpoint/v1/btccheckpoint';
5-
export * as epochingtx from './generated/babylon/epoching/v1/tx';
6-
export * as epochingquery from './generated/babylon/epoching/v1/query';
7-
export * as incentivetx from './generated/babylon/incentive/tx';
8-
export * as incentivequery from './generated/babylon/incentive/query';
9-
export * as btclightclient from './generated/babylon/btclightclient/v1/btclightclient';
10-
export * as btclightclientquery from './generated/babylon/btclightclient/v1/query';
11-
export * as cosmosstakingtx from './generated/cosmos/staking/v1beta1/tx';
12-
export * as cosmosstaking from './generated/cosmos/staking/v1beta1/staking';
1+
export * as btccheckpoint from "./generated/babylon/btccheckpoint/v1/btccheckpoint";
2+
export * as btclightclient from "./generated/babylon/btclightclient/v1/btclightclient";
3+
export * as btclightclientquery from "./generated/babylon/btclightclient/v1/query";
4+
export * as btcstaking from "./generated/babylon/btcstaking/v1/btcstaking";
5+
export * as btcstakingpop from "./generated/babylon/btcstaking/v1/pop";
6+
export * as btcstakingtx from "./generated/babylon/btcstaking/v1/tx";
7+
export * as epochingquery from "./generated/babylon/epoching/v1/query";
8+
export * as epochingtx from "./generated/babylon/epoching/v1/tx";
9+
export * as incentivequery from "./generated/babylon/incentive/query";
10+
export * as incentivetx from "./generated/babylon/incentive/tx";
11+
export * as cosmosstaking from "./generated/cosmos/staking/v1beta1/staking";
12+
export * as cosmosstakingtx from "./generated/cosmos/staking/v1beta1/tx";
13+
14+
export * from "./lib/sdk";

0 commit comments

Comments
 (0)