From c5b412670e3c586b823669ecb18b052b1fc9bca8 Mon Sep 17 00:00:00 2001 From: Oleksandr Myshchyshyn Date: Thu, 23 Jan 2025 17:36:15 +0200 Subject: [PATCH 1/3] Update migration guide from v2 to v5 --- README.md | 2 +- .../casper-2.0.md | 25 +- resources/migration-guide-v2-v5.md | 402 ++++++++++++++++++ 3 files changed, 405 insertions(+), 24 deletions(-) rename migration-guide-v2-v5.md => resources/casper-2.0.md (79%) create mode 100644 resources/migration-guide-v2-v5.md diff --git a/README.md b/README.md index ebe64139..13fdc18a 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ npm install casper-js-sdk --save ## Migration guides -### [v2 to v5](./migration-guide-v2-v5.md) +### [v2 to v5](resources/migration-guide-v2-v5.md) ## Usage examples diff --git a/migration-guide-v2-v5.md b/resources/casper-2.0.md similarity index 79% rename from migration-guide-v2-v5.md rename to resources/casper-2.0.md index 22ce3f34..fd5e6427 100644 --- a/migration-guide-v2-v5.md +++ b/resources/casper-2.0.md @@ -1,25 +1,4 @@ -# V2 to V5 Migration Guide - -`Casper JS SDK V5` makes many **breaking changes** to the SDK behavior, effectively rewriting it from scratch. - -The purpose of these changes is to improve and simplify the SDK, as well as to bring the Casper JS SDK to the same look and behavior as the Casper SDK in other languages. - -Also added new functionality to work with the Casper 2.0 (Condor) update - -## Changes - -- `CasperServiceByJsonRPC` and `CasperClient` become [RpcClient](./src/rpc/rpc_client.ts). The `RpcClient` is much broader in functionality and is the main place to interact with the rpc. [See more details here](src/rpc/README.md) -- `EventStream` become [SseClient](./src/sse/client.ts). The `SseClient` is the main place to interact with Casper events. [See more details here](src/sse/README.md) -- `AsymmetricKey` was splitted into to classes [PrivateKey](./src/types/keypair/PrivateKey.ts)` and [PublicKey](./src/types/keypair/PublicKey.ts). -- `CLPublicKey` become [PublicKey](./src/types/keypair/PublicKey.ts). -- `RuntimeArgs` become [Args](./src/types/Args.ts) -- Most classes that previously was in `src/lib` folder was redesigned and you can find them in `src/types` folder -- Functionality for deploy creation `DeployUtil` become [Deploy](./src/types/Deploy.ts) class with static methods. [See how to create Deploy here](./README.md#creating-a-legacy-deploy-1) -- Instead of `CLValueBuilder` it's possible to use `CLValue` constructors. For example `CLValueBuilder.bool(false)` become `new CLValueBool(false)` -- `CasperHDKey`now deprecated and out of scope of this lib. You can use `@scure/bip39` lib to achieve same result as in previous SKD version. -- Injected `CasperWallet` provider now out of scope of this lib. - -## Casper 2.0 (Condor) +# Casper 2.0 (Condor) ### Overview @@ -267,7 +246,7 @@ const result = await rpcClient.putTransactionV1(transaction); console.log(`Transaction Hash: ${result.transactionHash}`); ``` -## Using [TransactionBuilder](./src/types/TransactionBuilder.md) +## Using [TransactionBuilder](../src/types/TransactionBuilder.md) The `TransactionBuilder` is a base class used to create various types of transactions. By extending this class, you can build custom transaction types with specific methods and properties. diff --git a/resources/migration-guide-v2-v5.md b/resources/migration-guide-v2-v5.md new file mode 100644 index 00000000..afd09586 --- /dev/null +++ b/resources/migration-guide-v2-v5.md @@ -0,0 +1,402 @@ +# V2 to V5 Migration Guide + +`Casper JS SDK V5` introduces significant **breaking changes**, essentially rewriting the SDK from the ground up to enhance usability, align it with Casper SDKs in other languages, and incorporate new features for the Casper 2.0 (Condor) update. + +This guide will walk you through the key changes and provide detailed examples to help you transition your code seamlessly. + +--- + +## Key Highlights of the Migration + +1. Simplified APIs and modular design. +2. Improved alignment with Casper SDKs in other languages. +3. Enhanced functionality for Casper 2.0. +4. Transition from deploy-based operations to transaction-based architecture. + +--- + +## Changes and Migration Steps + +### 1. **`CasperServiceByJsonRPC` and `CasperClient` Replaced with `RpcClient`** + +#### Overview + +- The `CasperServiceByJsonRPC` and `CasperClient` classes have been **removed**. +- Introduced the new `RpcClient` class as their replacement. + +#### Migration Example + +##### Old Syntax (2.x) + +```typescript +const client = new CasperServiceByJsonRPC( + 'http://:7777/rpc' +); +const stateRootHash = await client.getStateRootHash(); +``` + +##### New Syntax (5.x) + +```typescript +import { HttpHandler, RpcClient } from 'casper-js-sdk'; + +const rpcHandler = new HttpHandler('http://:7777/rpc'); +const rpcClient = new RpcClient(rpcHandler); + +try { + const stateRootHash = await rpcClient.getLatestBlock(); + console.log(stateRootHash); +} catch (error) { + console.error(error); +} +``` + +For details on `RpcClient` methods, refer to the [documentation](https://github.com/casper-ecosystem/casper-js-sdk/blob/feat-5.0.0/src/rpc/README.md). + +--- + +### 2. **`CLValueBuilder` Replaced by `CLValue` Constructors** + +#### Overview + +- The `CLValueBuilder` class has been **removed**. +- Use `CLValue` constructors like `newCL..` methods. + +#### Migration Example + +##### Old Syntax (2.x) + +```typescript +const list = CLValueBuilder.list([ + CLValueBuilder.u32(1), + CLValueBuilder.u32(2), + CLValueBuilder.u32(3) +]); +const bool = CLValueBuilder.bool(false); +``` + +##### New Syntax (5.x) + +```typescript +import { + CLValueList, + CLValueUInt32, + CLValueBool +} from 'casper-js-sdk'; + +const list = CLValueList.newCLList(CLTypeUInt32, [ + CLValueUInt32.newCLUInt32(1), + CLValueUInt32.newCLUInt32(2), + CLValueUInt32.newCLUInt32(3) +]); +const bool = CLValueBool.newCLValueBool(false); +``` + +More examples are available in the [unit tests](https://github.com/casper-ecosystem/casper-js-sdk/tree/feat-5.0.0/src/types/clvalue). + +--- + +### 3. **`CLPublicKey` Renamed to `PublicKey`** + +#### Overview + +- `CLPublicKey` is now `PublicKey` with added features for better cryptographic key management. + +#### Migration Example + +```typescript +import { Args, CLValue, PublicKey } from 'casper-js-sdk'; + +const args = Args.fromMap({ + target: CLValue.newCLPublicKey(PublicKey.fromHex('0202f5a92ab6...')) +}); +``` + +Detailed documentation is available [here](https://github.com/casper-ecosystem/casper-js-sdk/blob/feat-5.0.0/src/types/keypair/PublicKey.ts). + +--- + +### 4. **Changes to Deploy Management** + +#### Overview + +- The `DeployUtil` module is now replaced by the `Deploy` class with static methods. +- Serialization/deserialization now uses `TypedJSON`. + +#### Migration Example + +##### Old Syntax (2.x) + +```typescript +const deploy = DeployUtil.makeDeploy(deployHeader, payment, session); +DeployUtil.signDeploy(deploy, keyPair); +``` + +##### New Syntax (5.x) + +```typescript +import { Deploy } from 'casper-js-sdk'; + +const deploy = Deploy.makeDeploy(deployHeader, payment, session); +deploy.sign(privateKey); +``` + +For details, refer to the [Deploy class documentation](https://github.com/casper-ecosystem/casper-js-sdk/blob/feat-5.0.0/src/types/Deploy.ts). + +--- + +### 5. **Key Management Overhaul** + +#### Overview + +- The `Keys` class from the old SDK (located in src/lib/Keys.ts) has been replaced with separate classes for `PublicKey` and `PrivateKey`, each based on the specific cryptographic algorithm. +- These new classes are located in the [keypair folder](https://github.com/casper-ecosystem/casper-js-sdk/tree/feat-5.0.0/src/types/keypair). +- AsymmetricKey was splitted into to classes [PrivateKey](../src/types/keypair/PrivateKey.ts) and [PublicKey](../src/types/keypair/PublicKey.ts). + +#### Key Differences + +1. **Structure**: + - Old Keys class included functionality for both public and private keys in a single class. + - New structure separates concerns into distinct PublicKey and PrivateKey classes. +2. **Enhanced Features**: + - The new classes provide extended functionality and better alignment with modern cryptographic standards. + - Includes support for additional key generation, validation, and serialization methods. + +#### Migration Example + +#### Old Syntax (2.x): + +```tsx +import { Keys } from 'casper-js-sdk'; + +const keyPair = Keys.Ed25519.new(); +const publicKey = keyPair.publicKey.toHex(); +const privateKey = keyPair.privateKey; +``` + +#### New Syntax (5.x): + +```tsx +import { PublicKey, PrivateKey, KeyAlgorithm } from 'casper-js-sdk'; + +// Generating a new key pair +const keys = await PrivateKey.generate(KeyAlgorithm.ED25519); +const publicKey = keys.publicKey.toHex(); + +// Serialization +console.log('Public Key (Hex):', publicKey.toHex()); +console.log('Private Key (PEM):', privateKey.toPem()); +``` + +Refer to the [keypair folder](https://github.com/casper-ecosystem/casper-js-sdk/tree/feat-5.0.0/src/types/keypair) for detailed implementation and examples. + +--- + +### 6. **`PurseIdentifier` Enum Replaced with a Class** + +### Changes + +- The PurseIdentifier enum has been replaced by a class with the same name, offering more flexibility and functionality. +- The new class is located in the [request.ts](https://github.com/casper-ecosystem/casper-js-sdk/blob/feat-5.0.0/src/rpc/request.ts#L542) file. + +#### Migration Example + +#### Old Syntax (2.x): + +```tsx +import { PurseIdentifier } from 'casper-js-sdk'; + +const balanceByPublicKey = await client.queryBalance( + PurseIdentifier.MainPurseUnderPublicKey, + privateKey.publicKey.toHex(false) +); + +const balanceByAccountHash = await client.queryBalance( + PurseIdentifier.MainPurseUnderAccountHash, + privateKey.publicKey.toAccountHashStr() +); +``` + +#### New Syntax (5.x): + +```tsx +import { + PurseIdentifier, + RpcClient, + HttpHandler +} from 'casper-js-sdk'; + +const rpcHandler = new HttpHandler('http://:7777/rpc'); +const rpcClient = new RpcClient(rpcHandler); + +try { + const balanceByPublicKey = await rpcClient.queryLatestBalance( + PurseIdentifier.fromPublicKey(privateKey.publicKey.toHex(false)) + ); + + const balanceByAccountHash = await rpcClient.queryLatestBalance( + PurseIdentifier.fromAccountHash( + privateKey.publicKey.accountHash() + ) + ); +} catch (e) {} +``` + +Explore the new PurseIdentifier class [here](https://github.com/casper-ecosystem/casper-js-sdk/blob/feat-5.0.0/src/rpc/request.ts#L542). + +--- + +### 7. **`DeployUtil` to `Deploy`** + +The `DeployUtil` module in the previous versions of casper-js-sdk has been replaced with the `Deploy` class in version 5.x. Functionality for deploy creation `DeployUtil` become [Deploy](../src/types/Deploy.ts) class with static methods. [See how to create Deploy here](../README.md#creating-a-legacy-deploy-1) + +### Key Differences + +1. **Module Structure**: + - The old DeployUtil module had multiple static utility methods. + - The new Deploy class organizes these functionalities as methods on a single object. +2. **Serialization and Deserialization**: + - The new module uses TypedJSON for serialization/deserialization, ensuring type safety. +3. **Improved Method Organization**: + - Methods are grouped logically, providing a cleaner and more intuitive API. + +### Additional Notes + +- The new Deploy class provides a more type-safe and modular approach, reducing errors and improving code readability. +- Refer to the [Deploy Class Documentation](https://github.com/casper-ecosystem/casper-js-sdk/blob/feat-5.0.0/src/types/Deploy.ts) for a complete list of available methods. +- Ensure that you update your dependencies and verify compatibility with the 5.x SDK before migrating. + +--- + +### 8. **`Contracts` Abstraction Removed** + +In the newer version of `casper-js-sdk`, we’ve removed the abstraction previously used for interacting with smart contracts. To provide greater flexibility and clarity, we have introduced two distinct classes: `ContractHash` and `ContractPackageHash`. These allow developers to directly install and call smart contracts with greater control. Below are two popular examples to help you transition smoothly: + +**Example 1: Installing a Smart Contract on the Casper Network.** + +This example demonstrates how to install a new smart contract using the new SDK structure. You can now directly work with `ExecutableDeployItem.newModuleBytes()` to include your `.wasm` file and deployment arguments. + +```tsx +import { + PrivateKey, + PublicKey, + Args, + DeployHeader, + ExecutableDeployItem, + Deploy, + DEFAULT_DEPLOY_TTL, + StoredContractByHash, + ContractHash +} from 'casper-js-sdk'; + +// Install a smart contract on a Casper Network +export const install = ( + wasm: Uint8Array, + args: Args, + paymentAmount: string, + sender: PublicKey, + chainName: string, + signingKey: PrivateKey +): Deploy => { + const deployHeader = DeployHeader.default(); + deployHeader.account = sender; + deployHeader.chainName = chainName; + + const payment = ExecutableDeployItem.standardPayment(paymentAmount); + const deploy = Deploy.makeDeploy( + deployHeader, + payment, + ExecutableDeployItem.newModuleBytes(wasm, args) + ); + const signedDeploy = deploy.sign(signingKeys); + + return signedDeploy; +}; +``` + +**Example 2: Calling a Smart Contract Entrypoint.** + +In this example, you can see how to call an entrypoint of a smart contract using the new `ContractHash` class. This approach removes the dependency on previous abstractions, making your code easier to manage and more explicit. + +Key Changes + +- Removed Abstraction: The Contracts abstraction has been replaced with the explicit use of ContractHash and ContractPackageHash. +- Direct Control: Developers now have full control over contract installation and entry point calls. +- Improved Clarity: The separation of logic enhances readability and reduces confusion. + +```tsx +import { + PrivateKey, + PublicKey, + Args, + DeployHeader, + ExecutableDeployItem, + Deploy, + DEFAULT_DEPLOY_TTL, + StoredContractByHash, + ContractHash +} from 'casper-js-sdk'; + +// Call an entrypoint of a smart contract. +export const callEntrypoint = ( + entryPoint: string, + args: Args, + sender: PublicKey, + chainName: string, + paymentAmount: string, + signingKeys: PrivateKey, + ttl: number = DEFAULT_DEPLOY_TTL +): Deploy => { + const deployHeader = DeployHeader.default(); + deployHeader.account = sender; + deployHeader.chainName = chainName; + deployHeader.ttl = ttl; + deployHeader.gasPrice = 1; + + const session = new ExecutableDeployItem(); + session.storedContractByHash = new StoredContractByHash( + ContractHash.newContract( + '93d923e336b20a4c4ca14d592b60e5bd3fe330775618290104f9beb326db7ae2' + ), + entryPoint, + args + ); + + const payment = ExecutableDeployItem.standardPayment(paymentAmount); + const deploy = Deploy.makeDeploy(deployHeader, payment, session); + const signedDeploy = deploy.sign(signingKeys); + + return signedDeploy; +}; +``` + +--- + +### 9. **Introduction of Casper 2.0 Transactions** + +#### Overview + +Casper 2.0 replaces deploys with a robust transaction-based system. Key components include: + +- `TransactionEntryPoint` +- `TransactionTarget` +- `TransactionScheduling` +- `PricingMode` + +Refer to the [full guide](./casper-2.0.md) for detailed examples and explanations. + +--- + +### 10. **Miscellaneous Changes** + +- `EventStream` become [SseClient](../src/sse/client.ts). The `SseClient` is the main place to interact with Casper events. [See more details here](../src/sse/README.md) +- `RuntimeArgs` become [Args](../src/types/Args.ts) +- `CasperHDKey`now deprecated and out of scope of this lib. You can use `@scure/bip39` lib to achieve same result as in previous SKD version. +- Injected `CasperWallet` provider now out of scope of this lib. +- Most classes that previously was in `src/lib` folder was redesigned and you can find them in `src/types` folder + +--- + +For any issues, feel free to open a discussion or create a ticket in the [repository](https://github.com/casper-ecosystem/casper-js-sdk/issues). + +--- From 00612cf02364ced391a15faf9fab681c9141eda4 Mon Sep 17 00:00:00 2001 From: Oleksandr Myshchyshyn Date: Fri, 24 Jan 2025 13:00:38 +0200 Subject: [PATCH 2/3] Addressed PR comments and applied fixes --- CHANGELOG.md | 2 +- .../types => resources}/TransactionBuilder.md | 2 +- resources/casper-2.0.md | 291 ------------------ resources/migration-guide-v2-v5.md | 190 +++++++----- 4 files changed, 118 insertions(+), 367 deletions(-) rename {src/types => resources}/TransactionBuilder.md (99%) delete mode 100644 resources/casper-2.0.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cde5d0e..e69df041 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -148,7 +148,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Added -- Basic documentation for Casper 2.0 (Condor) +- Basic documentation for Casper 2.0 - **Enhanced `CLValue.newCLOption` Method**: - Automatic resolution of the option type from `inner` when provided. - Optional `clType` parameter when `inner` is present. diff --git a/src/types/TransactionBuilder.md b/resources/TransactionBuilder.md similarity index 99% rename from src/types/TransactionBuilder.md rename to resources/TransactionBuilder.md index 5d76e229..d5137238 100644 --- a/src/types/TransactionBuilder.md +++ b/resources/TransactionBuilder.md @@ -20,7 +20,7 @@ TransactionBuilder contains classes and methods for building and managing Casper ## Overview -The provided classes allow developers to build, customize, and execute transactions on the Casper blockchain. By using builder patterns, developers can chain methods to configure each aspect of the transaction before calling `build()` to create the final [Transaction](./Transaction.ts) instance. +The provided classes allow developers to build, customize, and execute transactions on the Casper blockchain. By using builder patterns, developers can chain methods to configure each aspect of the transaction before calling `build()` to create the final [Transaction](../src/types/Transaction.ts) instance. ## Classes diff --git a/resources/casper-2.0.md b/resources/casper-2.0.md deleted file mode 100644 index fd5e6427..00000000 --- a/resources/casper-2.0.md +++ /dev/null @@ -1,291 +0,0 @@ -# Casper 2.0 (Condor) - -### Overview - -Casper 2.0 introduces a robust transaction system to replace deploys, simplifying blockchain interactions while enhancing flexibility, scalability, and extensibility. This SDK allows developers to create, configure, and manage transactions on the Casper blockchain seamlessly. - ---- - -## Table of Contents - -1. [Introduction](#introduction) -2. [Core Components](#core-components) - - [InitiatorAddr](#initiatoraddr) - - [TransactionEntryPoint](#transactionentrypoint) - - [TransactionTarget](#transactiontarget) - - [TransactionScheduling](#transactionscheduling) - - [PricingMode](#pricingmode) -3. [Creating a Transaction](#creating-a-transaction) -4. [Serialization and JSON Interoperability](#serialization-and-json-interoperability) -5. [Examples](#examples) -6. [Resources](#resources) - ---- - -## Introduction - -Casper 2.0 transitions from deploys to transactions, creating a more standardized approach to blockchain operations. Transactions are now encapsulated in a modular architecture, enabling simpler implementation and future expansion. - ---- - -## Core Components - -### 1. **InitiatorAddr** - -Represents the address of the transaction initiator. - -#### Example: - -```typescript -const privateKey = await PrivateKey.generate(KeyAlgorithm.ED25519); -const initiatorAddr = new InitiatorAddr(privateKey.publicKey); -``` - ---- - -### 2. **TransactionEntryPoint** - -Represents a transaction entry point, which defines an action to be executed within the system. All entry points defined in `TransactionEntryPointEnum` - -#### Example: - -```typescript -const entryPoint = new TransactionEntryPoint( - TransactionEntryPointEnum.Transfer -); -``` - ---- - -### 3. **TransactionTarget** - -Defines the transaction's target, which could be: - -- **Native**: For simple transfers. -- **Stored**: For invoking stored contracts. -- **Session**: For session-specific logic. - -#### Examples: - -- **Native Target**: - -```typescript -const nativeTarget = new TransactionTarget({}); -``` - -- **Stored Contract Target**: - -```typescript -const stored = new StoredTarget(); -const invocationTarget = new TransactionInvocationTarget(); -invocationTarget.byHash = new Hash(Uint8Array.from([])); // an example of hash -storedTarget.runtime = TransactionRuntime.vmCasperV1(); // an example of runtime -storedTarget.id = invocationTarget; - -const storedTransactionTarget = new TransactionTarget( - undefined, - stored -); - -// OR -const storedTransactionTarget1 = new TransactionTarget(); -storedTransactionTarget1.stored = stored; -``` - -- **Session Target**: - -```typescript -const sessionTarget = new SessionTarget(); -sessionTarget.moduleBytes = Uint8Array.from([]); // an example of module bytes -sessionTarget.runtime = TransactionRuntime.vmCasperV1(); // an example of runtime -sessionTarget.isInstallUpgrade = true; // an example of isInstallUpgrade - -const sessionTransactionTarget = new TransactionTarget( - undefined, - undefined, - sessionTarget -); - -// OR -const sessionTransactionTarget1 = new TransactionTarget(); -sessionTransactionTarget1.session = sessionTarget; -``` - ---- - -### 4. **TransactionScheduling** - -Configures when and how a transaction is executed, allowing for prioritization. - -#### Examples: - -- **Standard Scheduling**: - -```typescript -const standardScheduling = new TransactionScheduling({}); -``` - ---- - -### 5. **PricingMode** - -Specifies how transaction fees are calculated. Supports three modes: - -- **PaymentLimitedMode**: Classic pricing with limits. -- **FixedMode**: Uses fixed gas pricing with an optional computation factor. -- **PrepaidMode**: Receipt-based prepaid pricing. - -#### Examples: - -- **PaymentLimitedMode**: - -```typescript -const paymentLimited = new PaymentLimitedMode(); -paymentLimited.standardPayment = true; -paymentLimited.paymentAmount = '250000000'; -paymentLimited.gasPriceTolerance = 1; -``` - -- **Assign Pricing Mode**: - -```typescript -const pricingMode = new PricingMode(); -pricingMode.paymentLimited = paymentLimited; -``` - ---- - -## Creating a Transaction - -### Steps: - -1. **Initialize the RPC Client**: - -```typescript -const rpcHandler = new HttpHandler('http://:7777/rpc'); -const rpcClient = new RpcClient(rpcHandler); -``` - -2. **Generate Keys**: - -```typescript -const privateKey = await PrivateKey.generate(KeyAlgorithm.ED25519); -const publicKey = privateKey.publicKey; -``` - -3. **Define Runtime Arguments**: - -```typescript -const args = Args.fromMap({ - target: CLValue.newCLPublicKey( - PublicKey.fromHex('') - ), - amount: CLValueUInt512.newCLUInt512('2000000000') // 2 CSPR -}); -``` - -4. **Configure Components**: - -- **Target**: - -```typescript -const transactionTarget = new TransactionTarget({}); // Native target; -``` - -- **Entry Point**: - -```typescript -const entryPoint = new TransactionEntryPoint( - TransactionEntryPointEnum.Transfer -); -``` - -- **Scheduling**: - -```typescript -const scheduling = new TransactionScheduling({}); // Standard; -``` - -- **Pricing Mode**: - -```typescript -const pricingMode = new PricingMode(); -const paymentLimitedMode = new PaymentLimitedMode(); -paymentLimitedMode.gasPriceTolerance = 1; -paymentLimitedMode.paymentAmount = paymentAmount; -paymentLimitedMode.standardPayment = true; - -pricingMode.paymentLimited = paymentLimitedMode; -``` - -5. **Create and Sign Transaction**: - -```typescript -const transactionPayload = TransactionV1Payload.build({ - initiatorAddr: new InitiatorAddr(publicKey), - ttl: new Duration(1800000), - args, - timestamp: new Timestamp(new Date()), - entryPoint, - scheduling, - transactionTarget, - chainName: 'casper-net-1', - pricingMode -}); - -const transaction = TransactionV1.makeTransactionV1( - transactionPayload -); -transaction.sign(privateKey); -``` - -6. **Submit Transaction**: - -```typescript -const result = await rpcClient.putTransactionV1(transaction); -console.log(`Transaction Hash: ${result.transactionHash}`); -``` - -## Using [TransactionBuilder](../src/types/TransactionBuilder.md) - -The `TransactionBuilder` is a base class used to create various types of transactions. By extending this class, you can build custom transaction types with specific methods and properties. - -#### Example of how to construct a transaction with TransactionBuilder and push it to the network: - -```ts -import { - HttpHandler, - RpcClient, - NativeTransferBuilder, - PrivateKey, - KeyAlgorithm, - PublicKey -} from 'casper-js-sdk'; - -const rpcHandler = new HttpHandler('http://:7777/rpc'); -const rpcClient = new RpcClient(rpcHandler); - -const privateKey = await PrivateKey.generate(KeyAlgorithm.ED25519); - -const transaction = new NativeTransferBuilder() - .from(sender.publicKey) - .target( - PublicKey.fromHex( - '0202f5a92ab6da536e7b1a351406f3744224bec85d7acbab1497b65de48a1a707b64' - ) - ) - .amount('25000000000') // Amount in motes - .id(Date.now()) - .chainName('casper-net-1') - .payment(100_000_000) - .build(); - -transaction.sign(privateKey); - -try { - const result = await rpcClient.putTransaction(transaction); - console.log(`Transaction Hash: ${result.transactionHash}`); -} catch (e) { - console.error(e); -} -``` diff --git a/resources/migration-guide-v2-v5.md b/resources/migration-guide-v2-v5.md index afd09586..82cba8ef 100644 --- a/resources/migration-guide-v2-v5.md +++ b/resources/migration-guide-v2-v5.md @@ -1,6 +1,6 @@ # V2 to V5 Migration Guide -`Casper JS SDK V5` introduces significant **breaking changes**, essentially rewriting the SDK from the ground up to enhance usability, align it with Casper SDKs in other languages, and incorporate new features for the Casper 2.0 (Condor) update. +`Casper JS SDK V5` introduces significant **breaking changes**, essentially rewriting the SDK from the ground up to enhance usability, align it with Casper SDKs in other languages, and incorporate new features for the Casper 2.0 update. This guide will walk you through the key changes and provide detailed examples to help you transition your code seamlessly. @@ -40,11 +40,11 @@ const stateRootHash = await client.getStateRootHash(); ```typescript import { HttpHandler, RpcClient } from 'casper-js-sdk'; -const rpcHandler = new HttpHandler('http://:7777/rpc'); -const rpcClient = new RpcClient(rpcHandler); +const httpHandler = new HttpHandler('http://:7777/rpc'); +const rpcClient = new RpcClient(httpHandler); try { - const stateRootHash = await rpcClient.getLatestBlock(); + const stateRootHash = await rpcClient.getStateRootHashLatest(); console.log(stateRootHash); } catch (error) { console.error(error); @@ -116,50 +116,21 @@ Detailed documentation is available [here](https://github.com/casper-ecosystem/c --- -### 4. **Changes to Deploy Management** +### 4. **Key Management Overhaul** #### Overview -- The `DeployUtil` module is now replaced by the `Deploy` class with static methods. -- Serialization/deserialization now uses `TypedJSON`. - -#### Migration Example - -##### Old Syntax (2.x) - -```typescript -const deploy = DeployUtil.makeDeploy(deployHeader, payment, session); -DeployUtil.signDeploy(deploy, keyPair); -``` - -##### New Syntax (5.x) - -```typescript -import { Deploy } from 'casper-js-sdk'; - -const deploy = Deploy.makeDeploy(deployHeader, payment, session); -deploy.sign(privateKey); -``` - -For details, refer to the [Deploy class documentation](https://github.com/casper-ecosystem/casper-js-sdk/blob/feat-5.0.0/src/types/Deploy.ts). - ---- - -### 5. **Key Management Overhaul** - -#### Overview - -- The `Keys` class from the old SDK (located in src/lib/Keys.ts) has been replaced with separate classes for `PublicKey` and `PrivateKey`, each based on the specific cryptographic algorithm. +- The `Keys` class from the old SDK (located in `src/lib/Keys.ts`) has been replaced with separate classes for `PublicKey` and `PrivateKey`, each tailored to specific cryptographic algorithms. - These new classes are located in the [keypair folder](https://github.com/casper-ecosystem/casper-js-sdk/tree/feat-5.0.0/src/types/keypair). -- AsymmetricKey was splitted into to classes [PrivateKey](../src/types/keypair/PrivateKey.ts) and [PublicKey](../src/types/keypair/PublicKey.ts). +- AsymmetricKey was split into two classes: [PrivateKey](../src/types/keypair/PrivateKey.ts) and [PublicKey](../src/types/keypair/PublicKey.ts). #### Key Differences 1. **Structure**: - - Old Keys class included functionality for both public and private keys in a single class. - - New structure separates concerns into distinct PublicKey and PrivateKey classes. + - Old `Keys` class included functionality for both public and private keys in a single class. + - New structure separates concerns into distinct `PublicKey` and `PrivateKey` classes. 2. **Enhanced Features**: - - The new classes provide extended functionality and better alignment with modern cryptographic standards. + - The new classes provide extended functionality, and better alignment with modern cryptographic standards. - Includes support for additional key generation, validation, and serialization methods. #### Migration Example @@ -192,7 +163,7 @@ Refer to the [keypair folder](https://github.com/casper-ecosystem/casper-js-sdk/ --- -### 6. **`PurseIdentifier` Enum Replaced with a Class** +### 5. **`PurseIdentifier` Enum Replaced with a Class** ### Changes @@ -226,8 +197,8 @@ import { HttpHandler } from 'casper-js-sdk'; -const rpcHandler = new HttpHandler('http://:7777/rpc'); -const rpcClient = new RpcClient(rpcHandler); +const httpHandler = new HttpHandler('http://:7777/rpc'); +const rpcClient = new RpcClient(httpHandler); try { const balanceByPublicKey = await rpcClient.queryLatestBalance( @@ -246,35 +217,111 @@ Explore the new PurseIdentifier class [here](https://github.com/casper-ecosystem --- -### 7. **`DeployUtil` to `Deploy`** +### 6. **`DeployUtil` to `Deploy`** The `DeployUtil` module in the previous versions of casper-js-sdk has been replaced with the `Deploy` class in version 5.x. Functionality for deploy creation `DeployUtil` become [Deploy](../src/types/Deploy.ts) class with static methods. [See how to create Deploy here](../README.md#creating-a-legacy-deploy-1) ### Key Differences 1. **Module Structure**: - - The old DeployUtil module had multiple static utility methods. - - The new Deploy class organizes these functionalities as methods on a single object. + - The old `DeployUtil` module had multiple static utility methods. + - The new `Deploy` class organizes these functionalities as methods on a single object. 2. **Serialization and Deserialization**: - - The new module uses TypedJSON for serialization/deserialization, ensuring type safety. + - The new module uses `TypedJSON` for serialization/deserialization, ensuring type safety. 3. **Improved Method Organization**: - Methods are grouped logically, providing a cleaner and more intuitive API. +#### Migration Examples + +##### Old Syntax: Creating a Deploy (2.x) + +```typescript +import { DeployUtil } from 'casper-js-sdk'; + +const deployParams = new DeployUtil.DeployParams( + senderKey.publicKey, + 'casper-test' +); +const session = DeployUtil.ExecutableDeployItem.newTransfer( + 10, + recipientKey.publicKey, + undefined, + 1 +); +const payment = DeployUtil.standardPayment(10000000000000); +let deploy = DeployUtil.makeDeploy(deployParams, session, payment); +deploy = DeployUtil.signDeploy(deploy, senderKey); + +return deploy; +``` + +##### New Syntax: Creating a Deploy (5.x) + +```typescript +import { + Deploy, + DeployHeader, + ExecutableDeployItem +} from 'casper-js-sdk'; + +const session = new ExecutableDeployItem(); + +session.transfer = TransferDeployItem.newTransfer( + 10, + recipientKey.publicKey, + undefined, + 1 +); + +const deployHeader = DeployHeader.default(); +deployHeader.account = senderKey.publicKey; +deployHeader.chainName = 'casper-test'; + +const payment = ExecutableDeployItem.standardPayment(10000000000000); +const deploy = Deploy.makeDeploy(deployHeader, payment, session); +deploy.sign(senderKey); +``` + +##### Old Syntax: Serialization and Deserialization (2.x) + +```typescript +import { DeployUtil } from 'casper-js-sdk'; + +const deployJson = DeployUtil.deployToJson(deploy); +const deployFromJson = DeployUtil.deployFromJson(deployJson); +``` + +##### New Syntax: Serialization and Deserialization (5.x) + +```typescript +import { Deploy } from 'casper-js-sdk'; + +const deployJson = Deploy.toJSON(deploy); +const deployFromJson = Deploy.fromJSON(deployJson); +``` + ### Additional Notes -- The new Deploy class provides a more type-safe and modular approach, reducing errors and improving code readability. -- Refer to the [Deploy Class Documentation](https://github.com/casper-ecosystem/casper-js-sdk/blob/feat-5.0.0/src/types/Deploy.ts) for a complete list of available methods. +- The new `Deploy` class provides a more type-safe and modular approach, reducing errors and improving code readability. +- Refer to the [Deploy Class Documentation](../src/types/Deploy.ts) for a complete list of available methods. - Ensure that you update your dependencies and verify compatibility with the 5.x SDK before migrating. --- -### 8. **`Contracts` Abstraction Removed** +### 7. **`Contracts` Abstraction Removed** + +With the release of version 5.0 of the `casper-js-sdk`, we removed the old abstraction for creating and interacting with deploys, including the functions `install` and `callEntrypoint`. This guide provides detailed steps for migrating from the old abstraction to the new approach using the SDK's updated API. -In the newer version of `casper-js-sdk`, we’ve removed the abstraction previously used for interacting with smart contracts. To provide greater flexibility and clarity, we have introduced two distinct classes: `ContractHash` and `ContractPackageHash`. These allow developers to directly install and call smart contracts with greater control. Below are two popular examples to help you transition smoothly: +#### Key Changes: + +- Removed Custom Abstractions: Functions like `install` and `callEntrypoint` are no longer provided as utilities. Instead, the updated SDK expects developers to directly work with the core primitives of the SDK, offering more flexibility and transparency. +- Direct Use of Deploy Utilities: Developers now work directly with the SDK's deploy and contract management primitives, such as `DeployHeader`, `ExecutableDeployItem`, and `Deploy`. + +Below are examples to help you transition smoothly: **Example 1: Installing a Smart Contract on the Casper Network.** -This example demonstrates how to install a new smart contract using the new SDK structure. You can now directly work with `ExecutableDeployItem.newModuleBytes()` to include your `.wasm` file and deployment arguments. +The install function, used for deploying a smart contract to the Casper Network, can be replaced by following these steps: ```tsx import { @@ -302,25 +349,23 @@ export const install = ( deployHeader.account = sender; deployHeader.chainName = chainName; + const session = ExecutableDeployItem.newModuleBytes(wasm, args); const payment = ExecutableDeployItem.standardPayment(paymentAmount); - const deploy = Deploy.makeDeploy( - deployHeader, - payment, - ExecutableDeployItem.newModuleBytes(wasm, args) - ); - const signedDeploy = deploy.sign(signingKeys); + const deploy = Deploy.makeDeploy(deployHeader, payment, session); - return signedDeploy; + deploy.sign(signingKey); + + return deploy; }; ``` **Example 2: Calling a Smart Contract Entrypoint.** -In this example, you can see how to call an entrypoint of a smart contract using the new `ContractHash` class. This approach removes the dependency on previous abstractions, making your code easier to manage and more explicit. +The `callEntrypoint` function, used for invoking an entry point in a stored contract, can be replaced using the updated API as shown below: Key Changes -- Removed Abstraction: The Contracts abstraction has been replaced with the explicit use of ContractHash and ContractPackageHash. +- `ExecutableDeployItem` used with additional wrapper classes (`StoredContractByHash`, etc.). - Direct Control: Developers now have full control over contract installation and entry point calls. - Improved Clarity: The separation of logic enhances readability and reduces confusion. @@ -364,30 +409,27 @@ export const callEntrypoint = ( const payment = ExecutableDeployItem.standardPayment(paymentAmount); const deploy = Deploy.makeDeploy(deployHeader, payment, session); - const signedDeploy = deploy.sign(signingKeys); - return signedDeploy; + deploy.sign(signingKeys); + + return deploy; }; ``` ---- - -### 9. **Introduction of Casper 2.0 Transactions** +#### Once you have created and signed a deploy, you can send it to the network using the new RpcClient API. -#### Overview - -Casper 2.0 replaces deploys with a robust transaction-based system. Key components include: +```tsx +const httpHandler = new HttpHandler('http://:7777/rpc'); +const rpcClient = new RpcClient(httpHandler); -- `TransactionEntryPoint` -- `TransactionTarget` -- `TransactionScheduling` -- `PricingMode` +const result = await rpcClient.putDeploy(deploy); -Refer to the [full guide](./casper-2.0.md) for detailed examples and explanations. +console.log(`Deploy Hash: ${result.deployHash}`); +``` --- -### 10. **Miscellaneous Changes** +### 8. **Miscellaneous Changes** - `EventStream` become [SseClient](../src/sse/client.ts). The `SseClient` is the main place to interact with Casper events. [See more details here](../src/sse/README.md) - `RuntimeArgs` become [Args](../src/types/Args.ts) From 428746304b6139a157d4eb95e5fbe086fa19f41e Mon Sep 17 00:00:00 2001 From: Oleksandr Myshchyshyn Date: Wed, 29 Jan 2025 14:17:21 +0200 Subject: [PATCH 3/3] Update documentation due to PR comments --- resources/migration-guide-v2-v5.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/resources/migration-guide-v2-v5.md b/resources/migration-guide-v2-v5.md index 82cba8ef..206f56ae 100644 --- a/resources/migration-guide-v2-v5.md +++ b/resources/migration-guide-v2-v5.md @@ -17,7 +17,7 @@ This guide will walk you through the key changes and provide detailed examples t ## Changes and Migration Steps -### 1. **`CasperServiceByJsonRPC` and `CasperClient` Replaced with `RpcClient`** +### 1. **`CasperServiceByJsonRPC` and `CasperClient` replaced with `RpcClient`** #### Overview @@ -55,7 +55,7 @@ For details on `RpcClient` methods, refer to the [documentation](https://github. --- -### 2. **`CLValueBuilder` Replaced by `CLValue` Constructors** +### 2. **`CLValueBuilder` replaced by `CLValue` Constructors** #### Overview @@ -163,7 +163,7 @@ Refer to the [keypair folder](https://github.com/casper-ecosystem/casper-js-sdk/ --- -### 5. **`PurseIdentifier` Enum Replaced with a Class** +### 5. **`PurseIdentifier` Enum replaced with a Class** ### Changes @@ -310,12 +310,15 @@ const deployFromJson = Deploy.fromJSON(deployJson); ### 7. **`Contracts` Abstraction Removed** -With the release of version 5.0 of the `casper-js-sdk`, we removed the old abstraction for creating and interacting with deploys, including the functions `install` and `callEntrypoint`. This guide provides detailed steps for migrating from the old abstraction to the new approach using the SDK's updated API. +With the release of version 5.0 of the `casper-js-sdk`, we removed the old abstraction for creating and interacting with deploys, including the functions `install` and `callEntrypoint`. +This guide provides detailed steps for migrating from the old abstraction to the new approach using the SDK's updated API. #### Key Changes: -- Removed Custom Abstractions: Functions like `install` and `callEntrypoint` are no longer provided as utilities. Instead, the updated SDK expects developers to directly work with the core primitives of the SDK, offering more flexibility and transparency. -- Direct Use of Deploy Utilities: Developers now work directly with the SDK's deploy and contract management primitives, such as `DeployHeader`, `ExecutableDeployItem`, and `Deploy`. +- **Removed Custom Abstractions**: Functions like `install` and `callEntrypoint` are no longer provided as utilities. Instead, the updated SDK expects developers to directly work with the core primitives of the SDK, offering more flexibility and transparency. +- **Direct Use of Deploy Utilities**: Developers now work directly with the SDK's deploy and contract management primitives, such as `DeployHeader`, `ExecutableDeployItem`, and `Deploy`. +- **Deploy Builders for Common Contracts**: For frequently used contracts such as **auction, CEP-18 (fungible tokens), and CEP-78 (NFTs)**, the SDK provides specific **deploy builders** to streamline the deployment and interaction process. These utilities simplify common contract interactions while maintaining flexibility. + You can find these deploy builders in the [utils directory](../src/utils). Below are examples to help you transition smoothly: