Skip to content

Commit

Permalink
Update docs
Browse files Browse the repository at this point in the history
  • Loading branch information
Comp0te committed Nov 20, 2024
1 parent 70d418f commit f47c8cd
Show file tree
Hide file tree
Showing 4 changed files with 322 additions and 44 deletions.
152 changes: 109 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,60 +1,126 @@
# CasperLabs SDK for JavaScript
# Casper JS SDK

## Installation
The Casper JS SDK provides a convenient way to interact with the Casper Network using JavaScript.

## Get started

```bash
# Basic Node.JS installation
npm install casper-js-sdk --save
```

## Documentation
## Base usage

Documentation generated by [TypeDoc](https://typedoc.org/) is available on [here](https://casper-ecosystem.github.io/casper-js-sdk).
### RPC client

## Tests
Provides access to the exported methods of RPC Client and data structures where the response is serialized. [See more details here](src/rpc/README.md)

```bash
npm run test
Example:

```ts
import { HttpHandler, RpcClient } from 'casper-js-sdk';

const rpcHandler = new HttpHandler('http://<Node Address>:7777/rpc');
const rpcCient = new RpcClient(rpcHandler);
const deployHash =
'3facbc4133e722c5c5630b6ad2331383ba849ef719da582cc026e9dd85e72ac9';

try {
const deployResult = await rpcCient.getDeploy(deployHash);
} catch (e) {}
```

### SSE

Provides basic functionality to work with Casper events that streamed by SSE server. [See more details here](src/sse/README.md)

Example:

```ts
import { SseClient, EventType } from 'casper-js-sdk';

const sseClient = new SseClient(
'http://<Node Address>:9999/events/main'
);
sseClient.registerHandler(
EventType.DeployProcessedEventType,
async rawEvent => {
try {
const deployEvent = rawEvent.parseAsDeployProcessedEvent();
console.log(
`Deploy hash: ${deployEvent.deployProcessed.deployHash}`
);
} catch (error) {
console.error('Error processing event:', error);
}
}
);

// Start the client with the last known event ID
const lastEventID = 1234;

sseClient.start(lastEventID).catch(error => {
console.error('Error starting SSE client:', error);
});
```

## Examples

Basic library usage can be found below files:

- CLValues
- [CLUnit](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/Unit.test.ts)
- [CLAccountHash](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/AccountHash.test.ts)
- [CLTuple](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/Tuple.test.ts)
- [Numeric (CLU8, CLU32, CLU64 ...)](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/Numeric.test.ts)
- [CLKey](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/Key.test.ts)
- [CLPublicKey](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/PublicKey.test.ts)
- [CLURef](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/URef.test.ts)
- [CLString](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/String.test.ts)
- [CLBool](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/Bool.test.ts)
- [CLResult](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/Result.test.ts)
- [CLMap](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/Map.test.ts)
- [CLByteArray](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/ByteArray.test.ts)
- [CLOption](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/Option.test.ts)
- [CLList](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CLValue/List.test.ts)
- [HDKeys](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CasperHDKeys)
- [CasperHDKey](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CasperHDKeys/CasperHDKey.test.ts)
- [Ed25519HDKey](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CasperHDKeys/Ed25519HDKey.test.ts)
- [Secp256K1HDKey](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/CasperHDKeys/Secp256K1HDKey.test.ts)
- [Keys - Ed25519, Secp256K1](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/e2e/lib/Keys.test.ts)
- [CasperServiceByJsonRPC](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/e2e/rpc/RPC.test.ts)
- [CasperClient](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/e2e/lib/CasperClient.test.ts)
- [EventStream](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/e2e/services/EventStream.test.ts)
- [Contracts](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/Contracts.test.ts)
- [RuntimeArgs](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/RuntimeArgs.test.ts)
- [DeployUtil](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/DeployUtil.test.ts)
- [SignedMessage](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/SignedMessage.test.ts)
- [StoredValue](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/StoredValue.test.ts)
- [ByteConverters](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/ByteConverters.test.ts)
- [ChecksummedHex](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/ChecksummedHex.test.ts)
- [Serialization](https://github.com/casper-ecosystem/casper-js-sdk/tree/dev/src/lib/Serialization.test.ts)
### Work with Casper types

Example of how to construct a deploy and push it to the network:

```ts
import {
Deploy,
DeployHeader,
ExecutableDeployItem,
HttpHandler,
PublicKey,
RpcClient,
TransferDeployItem
} from 'casper-js-sdk';
import { KeyAlgorithm } from 'casper-js-sdk/dist/types/keypair/Algorithm';
import { PrivateKey } from 'casper-js-sdk/dist/types/keypair/PrivateKey';

const rpcHandler = new HttpHandler('http://<Node Address>:7777/rpc');
const rpcClient = new RpcClient(rpcHandler);

const senderKey = await PrivateKey.generate(KeyAlgorithm.ED25519);
const recipientKey = PublicKey.fromHex(
'010068920746ecf5870e18911EE1fC5db975E0e97fFFcBBF52f5045Ad6C9838D2F'
);
const paymentAmount = '10000000000000';
const transferAmount = '10';
const transferId = 35;

const session = new ExecutableDeployItem();

session.transfer = TransferDeployItem.newTransfer(
transferAmount,
recipientKey,
undefined,
transferId
);

const payment = ExecutableDeployItem.standardPayment(paymentAmount);

const deployHeader = DeployHeader.default();
deployHeader.account = senderKey.publicKey;
deployHeader.chainName = 'casper-test';

const deploy = Deploy.fromHeaderAndItems(
deployHeader,
payment,
session
);
await deploy.sign(senderKey);

const result = await rpcClient.putDeploy(deploy);

console.log(`Deploy Hash: ${result.deployHash}`);
```

## Migration guides

### v2 to v3

Please see [v2-v3 migration guide](./resources/migration-guide_v2-v3.md).
In progress...
154 changes: 154 additions & 0 deletions src/rpc/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# RPC
Provides access to the exported methods of RPC Client and data structures where serialized response.

The `RpcClient` implements RPC methods according to [spec](https://docs.casperlabs.io/developers/json-rpc/json-rpc-informational/).
`RpcClient` unites implementation of `ClientInformational` interface related to [spec](https://docs.casperlabs.io/developers/json-rpc/json-rpc-informational/) and `ClientPOS` interface related to [spec](https://docs.casperlabs.io/developers/json-rpc/json-rpc-pos/).


## Usage

The configuration is flexible, and caller can provide custom configurations, the most common usage is to create `RpcClient` which depends on `HttpHandler` interface.
```ts
import { HttpHandler, RpcClient } from 'casper-js-sdk';

const rpcHandler = new HttpHandler('http://<Node Address>:7777/rpc');
const rpcCient = new RpcClient(rpcHandler);
const deployHash = '3facbc4133e722c5c5630b6ad2331383ba849ef719da582cc026e9dd85e72ac9';
```


## Methods

The `RpcClient` combines the functionalities of `ClientPOS`, `ClientInformational`, and `ClientTransactional`.


### [`ClientPOS`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/client.ts#L40)

The `ClientPOS` interface includes methods related to the Proof-of-Stake functionality of the Casper network.

- **`getLatestAuctionInfo()`**
Returns the latest auction information.
**Returns:** [`StateGetAuctionInfoResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L55)


- **`getAuctionInfoByHash(blockHash: string)`**
Retrieves auction information for a specific block by hash.
**Returns:** [`StateGetAuctionInfoResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L55)


- **`getAuctionInfoByHeight(height: number)`**
Retrieves auction information for a specific block by height.
**Returns:** [`StateGetAuctionInfoResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L55)


- **`getEraInfoLatest()`**
Fetches the latest era information.
**Returns:** [`ChainGetEraInfoResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L433)


- **`getEraInfoByBlockHeight(height: number)`**
Fetches era information for a specific block by height.
**Returns:** [`ChainGetEraInfoResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L433)


- **`getEraInfoByBlockHash(hash: string)`**
Fetches era information for a specific block by hash.
**Returns:** [`ChainGetEraInfoResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L433)


- **`getValidatorChangesInfo()`**
Retrieves validator status changes during an era.
**Returns:** [`InfoGetValidatorChangesResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L572)


### [`ClientInformational`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/client.ts#L52)

The `ClientInformational` interface provides methods for querying node-specific and network-wide information.

#### Balance Queries

- **`getLatestBalance(purseURef: string)`**
Retrieves the latest balance for a given purse.
**Returns:** [`StateGetBalanceResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L66)


- **`getBalanceByStateRootHash(purseURef: string, stateRootHash: string)`**
Retrieves the balance for a specific state root hash.
**Returns:** [`StateGetBalanceResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L66)

#### Deploy Queries

- **`getDeploy(hash: string)`**
Retrieves a deploy by its hash.
**Returns:** [`InfoGetDeployResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L223)


- **`getDeployFinalizedApproval(hash: string)`**
Retrieves a deploy with finalized approvals.
**Returns:** [`InfoGetDeployResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L223)

#### Transaction Queries

- **`getTransactionByTransactionHash(transactionHash: string)`**
Retrieves a transaction by its hash.
**Returns:** [`InfoGetTransactionResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L253)


- **`getTransactionByDeployHash(deployHash: string)`**
Retrieves a transaction by its deploy hash.
**Returns:** [`InfoGetTransactionResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L253)

#### Dictionary Queries

- **`getDictionaryItem(stateRootHash: string | null, uref: string, key: string)`**
Retrieves an item from a dictionary.
**Returns:** [`StateGetDictionaryResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L455)


- **`getDictionaryItemByIdentifier(stateRootHash: string | null, identifier: ParamDictionaryIdentifier)`**
Retrieves an item using a dictionary identifier.
**Returns:** [`StateGetDictionaryResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L455)

#### Global State Queries

- **`queryLatestGlobalState(key: string, path: string[])`**
Queries the latest global state.
**Returns:** [`QueryGlobalStateResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L892)

#### Account Queries

- **`getAccountInfoByBlockHash(blockHash: string, pub: PublicKey)`**
Retrieves account information using a block hash.
**Returns:** [`StateGetAccountInfo`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L82)

#### Block Queries

- **`getLatestBlock()`**
Retrieves the latest block.
**Returns:** [`ChainGetBlockResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L134)

#### Era Summary Queries

- **`getEraSummaryLatest()`**
Fetches the latest era summary.
**Returns:** [`ChainGetEraSummaryResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L212)

#### Status and Peers

- **`getStatus()`**
Fetches the node's current status.
**Returns:** [`InfoGetStatusResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L583)


### [`ClientTransactional`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/client.ts#L227)

The `ClientTransactional` interface provides methods for deploying transactions to the network.

- **`putDeploy(deploy: Deploy)`**
Sends a deploy to the network.
**Returns:** [`PutDeployResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L685)


- **`putTransactionV1(transaction: TransactionV1)`**
Sends a transaction (v1) to the network.
**Returns:** [`PutTransactionResult`](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/rpc/response.ts#L707)
58 changes: 58 additions & 0 deletions src/sse/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# SSE client

Provide basic functionality to work with Casper events that streamed by SSE server. It connects to the server and collect events, from other side consumers obtain this stream and delegate the process to specific handlers.

## Usage

```ts
import { SseClient, EventType } from 'casper-js-sdk';

const sseClient = new SseClient(
'http://<Node Address>:9999/events/main'
);
sseClient.registerHandler(
EventType.DeployProcessedEventType,
async rawEvent => {
try {
const deployEvent = rawEvent.parseAsDeployProcessedEvent();
console.log(
`Deploy hash: ${deployEvent.deployProcessed.deployHash}`
);
} catch (error) {
console.error('Error processing event:', error);
}
}
);

// Start the client with the last known event ID
const lastEventID = 1234;

sseClient.start(lastEventID).catch(error => {
console.error('Error starting SSE client:', error);
});
```

## Events List

- [ApiVersion](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L138)
- [BlockAdded](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L162)
- [DeployProcessed](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L287)
- [DeployAccepted](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L296)
- [DeployExpired](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L313)
- [TransactionProcessed](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L114)
- [TransactionAccepted](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L328)
- [TransactionExpired](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L382)
- [FinalitySignature](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L674)
- [Step](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L766)
- [Fault](https://github.com/casper-ecosystem/casper-js-sdk/blob/573b563d0bc038e46b07f12789286d336536f8c9/src/sse/event.ts#L748)

## Key components

- `SseClient` is a facade that provide convenient interface to process data stream, and unites `Streamer` and `Consumer` under implementation.
- `Streamer` fills the events' channel
- `HttpConnection` establish, controls and watches connections, throw error (notify stream) if connection broken
- `StreamReader` read bytes lines from the response stream, detect data messages and corespondent ID
- `EventParser` parse event type from byte data, return event type and raw data
-
- `Consumer` read events stream and delegate to process each to the specific handler
- `Handler` accepts `RawEvent` for certain type, parse body, provide business logic
2 changes: 1 addition & 1 deletion src/sse/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { EventType, RawEvent } from "./event";

type Middleware = (handler: HandlerFunc) => HandlerFunc;

export class Client {
export class SseClient {
private streamer: Streamer;
private consumer: Consumer;

Expand Down

0 comments on commit f47c8cd

Please sign in to comment.