A working example of generating Typescript types from Near Protocol smart contract written in Rust
Explore other examples
·
Report Bug
Near Ukrainians Guild is a fast-growing guild aimed at providing high-quality educational content and assistance to grow a strong community of Ukrainian developers/entrepreneurs in the Near Protocol ecosystem
This example demonstrates the process of generating TypeScript typed files based on Near Protocol smart contract
-
main
branch contains plain contract with an example of generator usage -
only_generator
branch contains script for generating types & example of output in/type_generator/example/typescript
- Contract public functions are automatically generated
- Output type file contains
Contract
class with all functions
- Custom
struct
andenum
must be decorated with proc macro#[witgen]
- Type
&str
is not supported (but you can useString
)
💡 Before you begin, make sure you have the following installed
Follow these simple instructions to setup the required dependencies before usage
- Clone the repo
git clone https://github.com/nearuaguild/near-rust-contract-types-generator.git
- Checkout to branch
only_generator
git switch only_generator
- Copy the folder to your project
cp /type_generator/ /PATH_TO_YOUR_PROJECT_ROOT/
- Add
witgen
lib to your dependencies inCargo.toml
[dependencies] witgen = "0.15.0"
- Install
witme
packagecargo install witme --version 0.2.6 --force
Follow these simple instructions to generate Typescript interface files
-
Import
witgen
crate tolib.rs
use witgen::witgen;
-
Decorate with
#[witgen]
macro your contract types (example in/src/lib.rs
)#[witgen] #[derive(BorshSerialize, BorshDeserialize, Clone)] pub enum Kind { OK { code: u8 }, FAIL { code: u8, text: String }, }
#[derive(BorshSerialize, BorshDeserialize, PanicOnDefault, Clone)] #[witgen] pub struct Config { number: u16, kind: Kind, }
-
Execute script from the root smart contract folder
./type_generator/generate.sh
-
Copy generated types to your TypeScript project
cp ./type_generator/typescript/ /PATH_TO_TYPESCRIPT_PROJECT/
To create an ABI for a rust smart contract, follow these instructions:
-
Build the contract. In this example, create a new folder named /res, compile the smart contract into a wasm file by running
./build.sh
-
Deploy the contract
near dev-deploy res/contract.wasm
-
Create the ABI
cargo near abi
This will have created an ABI in the location target/near/near_rust_contract_types_generator_abi.json If you want to use this ABI to interact with the contract quickly, you can use Pagoda. To do this, link the account that you have deployed the contract to then attach the ABI
Distributed under the MIT License. See LICENSE.txt
for more information.