diff --git a/Cargo.lock b/Cargo.lock index 5d5ae9e..65e4d13 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -353,6 +353,48 @@ dependencies = [ "term", ] +[[package]] +name = "askama" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4744ed2eef2645831b441d8f5459689ade2ab27c854488fbab1fbe94fce1a7" +dependencies = [ + "askama_derive", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama_derive" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d661e0f57be36a5c14c48f78d09011e67e0cb618f269cca9f2fd8d15b68c46ac" +dependencies = [ + "askama_parser", + "basic-toml", + "memchr", + "proc-macro2", + "quote", + "rustc-hash 2.1.1", + "serde", + "serde_derive", + "syn 2.0.106", +] + +[[package]] +name = "askama_parser" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf315ce6524c857bb129ff794935cf6d42c82a6cff60526fe2a63593de4d0d4f" +dependencies = [ + "memchr", + "serde", + "serde_derive", + "winnow", +] + [[package]] name = "assert_matches" version = "1.5.0" @@ -553,6 +595,15 @@ version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba" +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + [[package]] name = "bit-set" version = "0.8.0" @@ -909,24 +960,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "cbindgen" -version = "0.27.0" -source = "git+https://github.com/Larkooo/cbindgen?branch=no-c-forward-enum#1df076f7559fbfeb3f9d5c9968c1c1630363ebc8" -dependencies = [ - "clap", - "heck 0.4.1", - "indexmap 2.11.3", - "log", - "proc-macro2", - "quote", - "serde", - "serde_json", - "syn 2.0.106", - "tempfile", - "toml", -] - [[package]] name = "cc" version = "1.2.37" @@ -1028,6 +1061,15 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "colored" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e" +dependencies = [ + "windows-sys 0.59.0", +] + [[package]] name = "combine" version = "4.6.7" @@ -1329,6 +1371,62 @@ dependencies = [ "subtle", ] +[[package]] +name = "diplomat" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced081520ee8cf2b8c5b64a1a901eccd7030ece670dac274afe64607d6499b71" +dependencies = [ + "diplomat_core", + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "diplomat-runtime" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "098f9520ec5c190943b083bca3ea4cc4e67dc5f85a37062e528ecf1d25f04eb4" + +[[package]] +name = "diplomat-tool" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d288eb6055935a8afa84caf60975a075163c9f3778365ff08b11cfc91ad4398e" +dependencies = [ + "askama", + "clap", + "colored", + "diplomat_core", + "displaydoc", + "heck 0.5.0", + "indenter", + "itertools 0.14.0", + "pulldown-cmark", + "quote", + "serde", + "syn 2.0.106", + "syn-inline-mod", + "toml", +] + +[[package]] +name = "diplomat_core" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad619d9fdee0e731bb6f8f7d797b6ecfdc2395e363f554d2f6377155955171eb" +dependencies = [ + "displaydoc", + "either", + "proc-macro2", + "quote", + "serde", + "smallvec", + "strck", + "syn 2.0.106", +] + [[package]] name = "directories" version = "6.0.0" @@ -1370,9 +1468,11 @@ dependencies = [ "axum 0.8.4", "base64 0.22.1", "cainome", - "cbindgen", "chrono", "crypto-bigint", + "diplomat", + "diplomat-runtime", + "diplomat-tool", "directories", "dojo-types", "dojo-world", @@ -1790,6 +1890,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "getopts" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df" +dependencies = [ + "unicode-width", +] + [[package]] name = "getrandom" version = "0.2.16" @@ -2369,6 +2478,12 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "indenter" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5" + [[package]] name = "indexmap" version = "1.9.3" @@ -3344,6 +3459,25 @@ dependencies = [ "psl-types", ] +[[package]] +name = "pulldown-cmark" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e8bbe1a966bd2f362681a44f6edce3c2310ac21e4d5067a6e7ec396297a6ea0" +dependencies = [ + "bitflags 2.9.4", + "getopts", + "memchr", + "pulldown-cmark-escape", + "unicase", +] + +[[package]] +name = "pulldown-cmark-escape" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae" + [[package]] name = "quick-error" version = "1.2.3" @@ -4594,6 +4728,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strck" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42316e70da376f3d113a68d138a60d8a9883c604fe97942721ec2068dab13a9f" +dependencies = [ + "unicode-ident", +] + [[package]] name = "stream-cancel" version = "0.8.2" @@ -4670,6 +4813,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn-inline-mod" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fa6dca1fdb7b2ed46dd534a326725419d4fb10f23d8c85a8b2860e5eb25d0f9" +dependencies = [ + "proc-macro2", + "syn 2.0.106", +] + [[package]] name = "sync_wrapper" version = "0.1.2" @@ -5479,6 +5632,12 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" +[[package]] +name = "unicase" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" + [[package]] name = "unicode-bidi" version = "0.3.18" @@ -5506,6 +5665,12 @@ version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + [[package]] name = "unicode-xid" version = "0.2.6" diff --git a/Cargo.toml b/Cargo.toml index 794e429..17735e8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,8 @@ stream-cancel = "0.8.2" cainome = "0.10.0" lazy_static = "1.5.0" account_sdk = { git = "https://github.com/cartridge-gg/controller-rs", rev = "ab1282b00afdf0a4b330793f1362aee066b1a0c9" } +diplomat = "0.12.0" +diplomat-runtime = "0.12.0" serde-wasm-bindgen = "0.6.3" wasm-bindgen-futures = "0.4.39" @@ -66,11 +68,7 @@ base64 = "0.22.1" [build-dependencies] -# this addresses issue with cyclical dependencies when generating C header -# see. https://github.com/mozilla/cbindgen/issues/43 -# cbindgen = { git = "https://github.com/flaviojs/cbindgen_tmp", branch = "resolve-order-dependencies-clike" } -# cbindgen = "0.29" -cbindgen = { git = "https://github.com/Larkooo/cbindgen", branch = "no-c-forward-enum" } +diplomat-tool = "0.12.0" [dev-dependencies] diff --git a/DIPLOMAT_IMPLEMENTATION_PLAN.md b/DIPLOMAT_IMPLEMENTATION_PLAN.md new file mode 100644 index 0000000..8c3a28a --- /dev/null +++ b/DIPLOMAT_IMPLEMENTATION_PLAN.md @@ -0,0 +1,210 @@ +# Diplomat Implementation Plan + +## Phase 1: Foundation Types ✅ COMPLETE +- [x] DojoError +- [x] FieldElement +- [x] U256 +- [x] Call, CallList +- [x] Signature +- [x] SigningKey, VerifyingKey +- [x] TypedData +- [x] ToriiClient (basic) +- [x] Provider +- [x] Account +- [x] Subscription + +## Phase 2: Enum Types (Simple) +- [ ] BlockTag (Latest, PreConfirmed) +- [ ] ContractType (WORLD, ERC20, ERC721, ERC1155, UDC, OTHER) +- [ ] PaginationDirection (Forward, Backward) +- [ ] OrderDirection (Asc, Desc) +- [ ] PatternMatching (FixedLen, VariableLen) +- [ ] LogicalOperator (And, Or) +- [ ] ComparisonOperator (Eq, Neq, Gt, Gte, Lt, Lte, In, NotIn, Contains, etc.) +- [ ] CallType (Execute, ExecuteFromOutside) + +## Phase 3: Wrapper Types +- [ ] BlockId (enum: Hash, Number, Tag) +- [ ] OrderBy (struct with field, direction) +- [ ] Pagination (struct with cursor, limit, direction, order_by) + +## Phase 4: Query Types +- [ ] KeysClause +- [ ] MemberValue (enum: Primitive, String, List) +- [ ] MemberClause +- [ ] CompositeClause +- [ ] Clause (enum: HashedKeys, Keys, Member, Composite) +- [ ] Query (main query struct) + +## Phase 5: Schema Types (Complex) +- [ ] Primitive (enum with all primitive types) +- [ ] EnumOption +- [ ] Enum +- [ ] Member +- [ ] Struct +- [ ] FixedSizeArray +- [ ] Ty (recursive enum) + +## Phase 6: Entity & World Types +- [ ] Entity +- [ ] Model +- [ ] World +- [ ] Event + +## Phase 7: Token Types +- [ ] Token +- [ ] TokenBalance +- [ ] TokenContract +- [ ] TokenTransfer +- [ ] AttributeFilter +- [ ] TokenQuery +- [ ] TokenBalanceQuery +- [ ] TokenContractQuery +- [ ] TokenTransferQuery + +## Phase 8: Transaction Types +- [ ] TransactionCall +- [ ] Transaction +- [ ] TransactionFilter +- [ ] TransactionQuery + +## Phase 9: Contract Types +- [ ] Contract +- [ ] ContractQuery + +## Phase 10: Controller Types ⏸️ SKIPPED (not core Dojo) +- [~] Controller +- [~] ControllerQuery +- [~] Policy + +## Phase 11: Aggregation Types +- [ ] AggregationEntry +- [ ] AggregationQuery + +## Phase 12: Activity Types +- [ ] ActionCount +- [ ] Activity +- [ ] ActivityQuery + +## Phase 13: Achievement Types +- [ ] AchievementTask +- [ ] Achievement +- [ ] AchievementQuery +- [ ] TaskProgress +- [ ] PlayerAchievementStats +- [ ] PlayerAchievementProgress +- [ ] PlayerAchievementEntry +- [ ] PlayerAchievementQuery +- [ ] AchievementProgression + +## Phase 14: Message Types +- [ ] Message + +## Phase 15: Page Wrapper +- [ ] Page generic wrapper for paginated results + +## Phase 16: ToriiClient Methods - Entity Operations +- [ ] entities() +- [ ] event_messages() +- [ ] on_entity_state_update() +- [ ] update_entity_subscription() + +## Phase 17: ToriiClient Methods - World Operations +- [ ] worlds() + +## Phase 18: ToriiClient Methods - Transaction Operations +- [ ] transactions() +- [ ] on_transaction() + +## Phase 19: ToriiClient Methods - Token Operations +- [ ] tokens() +- [ ] token_balances() +- [ ] token_contracts() +- [ ] token_transfers() +- [ ] on_token_update() +- [ ] on_token_balance_update() +- [ ] update_token_balance_subscription() +- [ ] on_token_transfer_update() +- [ ] update_token_transfer_subscription() + +## Phase 20: ToriiClient Methods - Contract Operations +- [ ] contracts() +- [ ] on_contract_update() + +## Phase 21: ToriiClient Methods - Controller Operations ⏸️ SKIPPED +- [~] controllers() + +## Phase 22: ToriiClient Methods - Aggregation Operations +- [ ] aggregations() +- [ ] on_aggregation_update() +- [ ] update_aggregation_subscription() + +## Phase 23: ToriiClient Methods - Achievement Operations +- [ ] achievements() +- [ ] player_achievements() +- [ ] on_achievement_progression_update() +- [ ] update_achievement_progression_subscription() + +## Phase 24: ToriiClient Methods - Activity Operations +- [ ] activities() +- [ ] on_activity_update() +- [ ] update_activity_subscription() + +## Phase 25: ToriiClient Methods - Event Operations +- [ ] on_event_message_update() +- [ ] update_event_message_subscription() +- [ ] on_starknet_event() + +## Phase 26: ToriiClient Methods - Message Operations +- [ ] publish_message() (already exists, needs enhancement) +- [ ] publish_message_batch() + +## Phase 27: Account Methods (Extended) ⏸️ SKIPPED (not core Dojo) +- [~] deploy_burner() +- [~] set_block_id() + +## Phase 28: Provider Methods (Extended) ⏸️ SKIPPED +- [ ] call() +- [ ] block_number() (already exists) +- [ ] chain_id() (already exists) + +## Phase 29: Controller Account Types & Methods ⏸️ SKIPPED (not core Dojo) +- [~] ControllerAccount opaque type +- [~] connect() +- [~] account() +- [~] clear() +- [~] username() +- [~] address() +- [~] chain_id() +- [~] nonce() +- [~] execute_raw() +- [~] execute_from_outside() + +## Phase 30: Utility Functions Module +- [ ] bytearray_serialize() +- [ ] bytearray_deserialize() +- [ ] poseidon_hash() +- [ ] pedersen_hash() (already exists) +- [ ] get_selector_from_name() (already exists) +- [ ] get_selector_from_tag() +- [ ] starknet_keccak() +- [ ] cairo_short_string_to_felt() +- [ ] parse_cairo_short_string() +- [ ] compute_contract_address() (already exists) + +## Phase 31: Testing & Examples +- [ ] Test basic types +- [ ] Test client operations +- [ ] Test subscriptions +- [ ] Update C example +- [ ] Update JavaScript example +- [ ] Create C++ example + +## Notes +- Each opaque type will have automatic Drop implementation via diplomat +- String outputs use DiplomatWrite +- String inputs use DiplomatStr +- Arrays will need special handling (may use slices where possible) +- Callbacks for subscriptions need special consideration +- Page may need to be concrete types (PageEntity, PageToken, etc.) since diplomat doesn't support generics + diff --git a/DIPLOMAT_MIGRATION.md b/DIPLOMAT_MIGRATION.md new file mode 100644 index 0000000..36547c1 --- /dev/null +++ b/DIPLOMAT_MIGRATION.md @@ -0,0 +1,295 @@ +# Diplomat Migration Guide + +This document describes the migration of dojo.c from `cbindgen`/`wasm-bindgen` to `diplomat` for FFI generation. + +## Overview + +The codebase has been restructured to use [Diplomat](https://github.com/rust-diplomat/diplomat), a Rust FFI tool that generates bindings for C, C++, and JavaScript from a single source. + +## Architecture Changes + +### Before (cbindgen/wasm-bindgen) +``` +src/ +├── c/ # C FFI with manual raw pointers +│ ├── mod.rs # 80+ extern "C" functions +│ └── types.rs # 2000+ lines of #[repr(C)] structs +├── wasm/ # Separate WASM bindings +│ ├── mod.rs # wasm-bindgen functions +│ └── types.rs # TypeScript types +└── lib.rs +``` + +### After (diplomat) +``` +src/ +├── ffi/ # Unified diplomat FFI bridge +│ ├── mod.rs # Module exports +│ ├── error.rs # Error types +│ ├── types.rs # Core types (FieldElement, U256, Call, etc.) +│ ├── crypto.rs # Cryptographic operations +│ ├── client.rs # Torii client +│ ├── account.rs # Starknet accounts +│ ├── query.rs # Query types +│ └── subscription.rs # Subscriptions +├── c/ # Legacy (kept for reference) +├── wasm/ # Legacy (kept for reference) +└── lib.rs # Exports diplomat modules +``` + +## Key Diplomat Patterns + +### 1. Module Structure +```rust +#[diplomat::bridge] +pub mod ffi { + // All FFI types and functions go here +} +``` + +### 2. Opaque Types +Instead of `#[repr(C)]` structs, use opaque wrappers: + +```rust +// OLD (cbindgen) +#[repr(C)] +pub struct FieldElement { + pub data: [u8; 32], +} + +// NEW (diplomat) +#[diplomat::opaque] +pub struct FieldElement(pub Felt); +``` + +### 3. String Handling +- **Input**: Use `DiplomatStr` instead of `*const c_char` +- **Output**: Use `DiplomatWrite` instead of returning `*const c_char` + +```rust +// OLD +pub unsafe extern "C" fn felt_to_hex(felt: FieldElement) -> *const c_char { + let hex = format!("{:#x}", felt.0); + CString::new(hex).unwrap().into_raw() +} + +// NEW +impl FieldElement { + pub fn to_hex(&self, result: &mut DiplomatWrite) { + write!(result, "{:#x}", self.0).unwrap(); + } +} +``` + +### 4. Error Handling +Use `Result>`: + +```rust +#[diplomat::opaque] +pub struct DojoError { + pub(crate) error_type: ErrorType, + pub(crate) message: String, +} + +pub enum ErrorType { + ClientError, + ParseError, + // ... +} + +impl FieldElement { + pub fn new_from_hex(hex: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(hex)?; + let felt = Felt::from_hex(s).map_err(|e| { + DojoError::new(ErrorType::ParseError, &format!("Invalid felt hex: {}", e)) + })?; + Ok(Box::new(FieldElement(felt))) + } +} +``` + +### 5. Async Operations +Use a lazy_static runtime: + +```rust +lazy_static! { + static ref RUNTIME: Arc = + Arc::new(Runtime::new().expect("Failed to create Tokio runtime")); +} + +impl ToriiClient { + pub fn new(torii_url: &DiplomatStr) -> Result, Box> { + let url = std::str::from_utf8(torii_url)?.to_string(); + let client = RUNTIME.block_on(TClient::new(url)) + .map_err(|e| DojoError::new(ErrorType::ClientError, &e.to_string()))?; + Ok(Box::new(ToriiClient { inner: Arc::new(client) })) + } +} +``` + +### 6. Collections +- Use `&[Box]` for input arrays +- Create wrapper types for output collections + +```rust +#[diplomat::opaque] +pub struct CallList { + pub(crate) calls: Vec, +} + +impl CallList { + pub fn new() -> Box { + Box::new(CallList { calls: Vec::new() }) + } + + pub fn add_call(&mut self, call: &Call) { + self.calls.push(call.0.clone()); + } +} +``` + +## Generated Bindings + +Diplomat automatically generates bindings in three languages: + +### C Bindings (`bindings/c/`) +```c +#include "ToriiClient.h" + +ToriiClient_new_result client_result = ToriiClient_new("http://localhost:8080"); +if (client_result.is_ok) { + ToriiClient* client = client_result.ok; + // Use client... + ToriiClient_destroy(client); +} +``` + +### C++ Bindings (`bindings/cpp/`) +```cpp +#include "ToriiClient.hpp" + +auto client = ToriiClient::new_("http://localhost:8080"); +if (client.is_ok()) { + auto& c = client.ok(); + // Use client... +} +``` + +### JavaScript Bindings (`bindings/js/`) +```typescript +import { ToriiClient } from './bindings/js/index.mjs'; + +const client = ToriiClient.new_("http://localhost:8080"); +const info = client.info(); +console.log(info); +``` + +## Build Configuration + +### Cargo.toml +```toml +[dependencies] +diplomat = "0.12.0" +diplomat-runtime = "0.12.0" + +[build-dependencies] +diplomat-tool = "0.12.0" +``` + +### build.rs +```rust +use diplomat_tool::{config::{Config, SharedConfig}, DocsUrlGenerator}; + +pub fn main() { + // Generate C bindings + diplomat_tool::gen( + Path::new("src/lib.rs"), + "c", + Path::new("bindings/c"), + &DocsUrlGenerator::default(), + Config { + shared_config: SharedConfig { + lib_name: Some("dojo_c".to_string()), + ..Default::default() + }, + ..Config::default() + }, + false, + ).unwrap(); + + // Similar for C++ and JS... +} +``` + +## Migration Checklist + +- [x] Add diplomat dependencies to Cargo.toml +- [x] Create ffi module structure +- [x] Implement core types (FieldElement, U256, Call, Signature) +- [x] Implement error handling +- [x] Implement crypto operations (SigningKey, VerifyingKey) +- [x] Implement Torii client +- [x] Implement account management +- [x] Update build.rs to use diplomat-tool +- [x] Generate bindings for C, C++, and JavaScript +- [ ] Port remaining 80+ functions from old C module +- [ ] Add comprehensive entity query APIs +- [ ] Add token and event query APIs +- [ ] Add subscription management +- [ ] Update examples +- [ ] Update tests +- [ ] Update documentation + +## Next Steps + +### 1. Port Remaining Functions +The old `src/c/mod.rs` has 80+ functions. Continue migrating them following the patterns above: + +- Entity queries (`client_get_entities`, etc.) +- Model operations +- Event subscriptions +- Token operations +- Controller/Session management + +### 2. Add Entity Types +Create diplomat types for: +- `Entity` +- `Model` +- `Event` +- `Token` +- `TokenBalance` +- etc. + +### 3. Testing +- Create integration tests +- Test C bindings with example C program +- Test C++ bindings +- Test JavaScript bindings in browser and Node.js + +### 4. Documentation +- Generate API documentation +- Create usage examples for each language +- Document breaking changes from old API + +## Benefits of Diplomat + +1. **Single Source of Truth**: One Rust API generates bindings for all languages +2. **Type Safety**: Automatic memory management and type checking +3. **Better Error Handling**: Proper Result types instead of error codes +4. **Cleaner API**: No manual pointer management in Rust code +5. **Documentation**: Comments are automatically included in generated bindings +6. **Maintainability**: Much easier to add new functions and types + +## Breaking Changes + +1. **String handling**: All strings now use UTF-8 by default (was C-style null-terminated) +2. **Error handling**: Functions return Result types instead of custom Result enum +3. **Memory management**: Opaque types instead of #[repr(C)] structs +4. **API naming**: Some functions renamed to follow Rust conventions + +## Resources + +- [Diplomat Documentation](https://rust-diplomat.github.io/diplomat/) +- [Diplomat GitHub](https://github.com/rust-diplomat/diplomat) +- [Example controller.c project](../controller.c) - Reference implementation + diff --git a/README.md b/README.md index b99ca31..31d38f8 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,158 @@ # dojo.c -This package provides C and low-level Wasm32 bindings for the Torii Client SDK, as well as for the starknet-rs library. +This package provides C, C++, and JavaScript bindings for the Torii Client SDK and starknet-rs library using [Diplomat](https://github.com/rust-diplomat/diplomat). -The approach is to generate a C client using `cbindgen` and a wasm module using `wasm-bindgen` that are interropeable in applications exporting to both native platforms and web browsers. +**⚠️ Migration Notice**: This project has been migrated from `cbindgen`/`wasm-bindgen` to `diplomat` for unified FFI generation. See [DIPLOMAT_MIGRATION.md](DIPLOMAT_MIGRATION.md) for details. + +## Features + +- **Unified FFI**: Single Rust API generates bindings for C, C++, and JavaScript +- **Type-Safe**: Automatic memory management and type checking +- **Modern**: Clean API with proper error handling +- **Well-Documented**: Auto-generated documentation for all languages ## Building +### Prerequisites +```bash +cargo install diplomat-tool +``` + +### Build Library and Generate Bindings ```bash -# Build for current platform +# Build Rust library and generate C/C++/JS bindings cargo build --release + +# Bindings are automatically generated in: +# - bindings/c/ (C headers) +# - bindings/cpp/ (C++ headers) +# - bindings/js/ (JavaScript/TypeScript modules) ``` -### Native platform +### Platform-Specific Builds +#### Linux ```bash rustup target add x86_64-unknown-linux-gnu cargo build --release --target x86_64-unknown-linux-gnu ``` -### Wasm +#### macOS (Apple Silicon) +```bash +cargo build --release +``` +#### WebAssembly ```bash -# Building wasm32 binary cargo build --release --target wasm32-unknown-unknown -# Building using wasm-pack -cd pkg && bunx wasm-pack build --release +# JS bindings support both native and WASM targets +``` + +## Usage Examples + +### C +```c +#include "bindings/c/ToriiClient.h" +#include "bindings/c/SigningKey.h" + +// Create a Torii client +ToriiClient_new_result result = ToriiClient_new("http://localhost:8080"); +if (result.is_ok) { + ToriiClient* client = result.ok; + // Use client... + ToriiClient_destroy(client); +} +``` + +See [examples/diplomat_example.c](examples/diplomat_example.c) for a complete example. + +### C++ +```cpp +#include "bindings/cpp/ToriiClient.hpp" +#include "bindings/cpp/SigningKey.hpp" + +auto client = ToriiClient::new_("http://localhost:8080"); +if (client.is_ok()) { + // Use client... +} +``` + +### JavaScript/TypeScript +```javascript +import { ToriiClient, SigningKey } from './bindings/js/index.mjs'; + +const client = ToriiClient.new_("http://localhost:8080"); +const info = client.info(); +console.log(info); ``` -## Running +See [examples/diplomat_example.js](examples/diplomat_example.js) for a complete example. + +## Building Examples +### C Example ```bash -# Building dojo.c cargo build --release -# Linking dojo.c and building example -clang example/main.c target/release/libdojo_c.dylib -# Running example -./a.out +clang examples/diplomat_example.c \ + -I bindings/c \ + -L target/release \ + -ldojo_c \ + -o diplomat_example + +# Run (macOS) +DYLD_LIBRARY_PATH=target/release ./diplomat_example + +# Run (Linux) +LD_LIBRARY_PATH=target/release ./diplomat_example +``` + +### JavaScript Example +```bash +node examples/diplomat_example.js ``` + +## API Documentation + +Generated bindings include inline documentation. Key modules: + +- **ToriiClient**: Torii server client for querying entities +- **SigningKey/VerifyingKey**: Cryptographic key management +- **FieldElement**: Starknet field element operations +- **Account**: Starknet account management +- **Provider**: JSON-RPC provider for blockchain interaction + +## Migration Guide + +If you're migrating from the old `cbindgen`/`wasm-bindgen` API, see [DIPLOMAT_MIGRATION.md](DIPLOMAT_MIGRATION.md) for: +- Architecture changes +- API differences +- Migration patterns +- Breaking changes + +## Project Status + +✅ **Completed**: +- Core types (FieldElement, U256, Call, Signature) +- Cryptographic operations +- Basic Torii client +- Account management +- Provider integration +- C/C++/JavaScript binding generation + +🚧 **In Progress**: +- Entity query APIs +- Event subscriptions +- Token operations +- Comprehensive examples +- Full test coverage + +## Contributing + +When adding new FFI functions: + +1. Add to appropriate module in `src/ffi/` +2. Use `#[diplomat::bridge]` and `#[diplomat::opaque]` annotations +3. Run `cargo build` to regenerate bindings +4. Test in target language (C/C++/JS) + +See [DIPLOMAT_MIGRATION.md](DIPLOMAT_MIGRATION.md) for patterns and best practices. diff --git a/bindings/c/Account.d.h b/bindings/c/Account.d.h new file mode 100644 index 0000000..d3cc572 --- /dev/null +++ b/bindings/c/Account.d.h @@ -0,0 +1,19 @@ +#ifndef Account_D_H +#define Account_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Account Account; + + + + +#endif // Account_D_H diff --git a/bindings/c/Account.h b/bindings/c/Account.h new file mode 100644 index 0000000..93fc7b0 --- /dev/null +++ b/bindings/c/Account.h @@ -0,0 +1,41 @@ +#ifndef Account_H +#define Account_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "CallList.d.h" +#include "DojoError.d.h" +#include "FieldElement.d.h" +#include "Provider.d.h" +#include "SigningKey.d.h" + +#include "Account.d.h" + + + + + + +Account* Account_new(const Provider* provider, const SigningKey* signer, const FieldElement* address, const FieldElement* chain_id); + +void Account_address(const Account* self, DiplomatWrite* write); + +void Account_chain_id(const Account* self, DiplomatWrite* write); + +typedef struct Account_execute_result {union { DojoError* err;}; bool is_ok;} Account_execute_result; +Account_execute_result Account_execute(const Account* self, const CallList* calls, DiplomatWrite* write); + +typedef struct Account_nonce_result {union {uint64_t ok; DojoError* err;}; bool is_ok;} Account_nonce_result; +Account_nonce_result Account_nonce(const Account* self); + +void Account_destroy(Account* self); + + + + + +#endif // Account_H diff --git a/bindings/c/Achievement.d.h b/bindings/c/Achievement.d.h new file mode 100644 index 0000000..c63c9b2 --- /dev/null +++ b/bindings/c/Achievement.d.h @@ -0,0 +1,19 @@ +#ifndef Achievement_D_H +#define Achievement_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Achievement Achievement; + + + + +#endif // Achievement_D_H diff --git a/bindings/c/Achievement.h b/bindings/c/Achievement.h new file mode 100644 index 0000000..a044e19 --- /dev/null +++ b/bindings/c/Achievement.h @@ -0,0 +1,47 @@ +#ifndef Achievement_H +#define Achievement_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Achievement.d.h" + + + + + + +void Achievement_id(const Achievement* self, DiplomatWrite* write); + +void Achievement_world_address(const Achievement* self, DiplomatWrite* write); + +void Achievement_namespace(const Achievement* self, DiplomatWrite* write); + +void Achievement_title(const Achievement* self, DiplomatWrite* write); + +void Achievement_description(const Achievement* self, DiplomatWrite* write); + +bool Achievement_hidden(const Achievement* self); + +void Achievement_icon(const Achievement* self, DiplomatWrite* write); + +uint32_t Achievement_points(const Achievement* self); + +typedef struct Achievement_from_json_result {union {Achievement* ok; DojoError* err;}; bool is_ok;} Achievement_from_json_result; +Achievement_from_json_result Achievement_from_json(DiplomatStringView json); + +typedef struct Achievement_to_json_result {union { DojoError* err;}; bool is_ok;} Achievement_to_json_result; +Achievement_to_json_result Achievement_to_json(const Achievement* self, DiplomatWrite* write); + +void Achievement_destroy(Achievement* self); + + + + + +#endif // Achievement_H diff --git a/bindings/c/Activity.d.h b/bindings/c/Activity.d.h new file mode 100644 index 0000000..2f09d70 --- /dev/null +++ b/bindings/c/Activity.d.h @@ -0,0 +1,19 @@ +#ifndef Activity_D_H +#define Activity_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Activity Activity; + + + + +#endif // Activity_D_H diff --git a/bindings/c/Activity.h b/bindings/c/Activity.h new file mode 100644 index 0000000..0c05de4 --- /dev/null +++ b/bindings/c/Activity.h @@ -0,0 +1,47 @@ +#ifndef Activity_H +#define Activity_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Activity.d.h" + + + + + + +void Activity_id(const Activity* self, DiplomatWrite* write); + +void Activity_world_address(const Activity* self, DiplomatWrite* write); + +void Activity_namespace(const Activity* self, DiplomatWrite* write); + +void Activity_caller_address(const Activity* self, DiplomatWrite* write); + +uint64_t Activity_session_start(const Activity* self); + +uint64_t Activity_session_end(const Activity* self); + +uint32_t Activity_action_count(const Activity* self); + +uint64_t Activity_updated_at(const Activity* self); + +typedef struct Activity_from_json_result {union {Activity* ok; DojoError* err;}; bool is_ok;} Activity_from_json_result; +Activity_from_json_result Activity_from_json(DiplomatStringView json); + +typedef struct Activity_to_json_result {union { DojoError* err;}; bool is_ok;} Activity_to_json_result; +Activity_to_json_result Activity_to_json(const Activity* self, DiplomatWrite* write); + +void Activity_destroy(Activity* self); + + + + + +#endif // Activity_H diff --git a/bindings/c/AggregationEntry.d.h b/bindings/c/AggregationEntry.d.h new file mode 100644 index 0000000..a857a5c --- /dev/null +++ b/bindings/c/AggregationEntry.d.h @@ -0,0 +1,19 @@ +#ifndef AggregationEntry_D_H +#define AggregationEntry_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct AggregationEntry AggregationEntry; + + + + +#endif // AggregationEntry_D_H diff --git a/bindings/c/AggregationEntry.h b/bindings/c/AggregationEntry.h new file mode 100644 index 0000000..02f8a47 --- /dev/null +++ b/bindings/c/AggregationEntry.h @@ -0,0 +1,49 @@ +#ifndef AggregationEntry_H +#define AggregationEntry_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "AggregationEntry.d.h" + + + + + + +void AggregationEntry_id(const AggregationEntry* self, DiplomatWrite* write); + +void AggregationEntry_aggregator_id(const AggregationEntry* self, DiplomatWrite* write); + +void AggregationEntry_entity_id(const AggregationEntry* self, DiplomatWrite* write); + +void AggregationEntry_model_id(const AggregationEntry* self, DiplomatWrite* write); + +void AggregationEntry_value(const AggregationEntry* self, DiplomatWrite* write); + +void AggregationEntry_display_value(const AggregationEntry* self, DiplomatWrite* write); + +uint64_t AggregationEntry_position(const AggregationEntry* self); + +uint64_t AggregationEntry_created_at(const AggregationEntry* self); + +uint64_t AggregationEntry_updated_at(const AggregationEntry* self); + +typedef struct AggregationEntry_from_json_result {union {AggregationEntry* ok; DojoError* err;}; bool is_ok;} AggregationEntry_from_json_result; +AggregationEntry_from_json_result AggregationEntry_from_json(DiplomatStringView json); + +typedef struct AggregationEntry_to_json_result {union { DojoError* err;}; bool is_ok;} AggregationEntry_to_json_result; +AggregationEntry_to_json_result AggregationEntry_to_json(const AggregationEntry* self, DiplomatWrite* write); + +void AggregationEntry_destroy(AggregationEntry* self); + + + + + +#endif // AggregationEntry_H diff --git a/bindings/c/BlockId.d.h b/bindings/c/BlockId.d.h new file mode 100644 index 0000000..6d76922 --- /dev/null +++ b/bindings/c/BlockId.d.h @@ -0,0 +1,19 @@ +#ifndef BlockId_D_H +#define BlockId_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct BlockId BlockId; + + + + +#endif // BlockId_D_H diff --git a/bindings/c/BlockId.h b/bindings/c/BlockId.h new file mode 100644 index 0000000..c75e931 --- /dev/null +++ b/bindings/c/BlockId.h @@ -0,0 +1,32 @@ +#ifndef BlockId_H +#define BlockId_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "BlockTag.d.h" +#include "FieldElement.d.h" + +#include "BlockId.d.h" + + + + + + +BlockId* BlockId_from_hash(const FieldElement* hash); + +BlockId* BlockId_from_number(uint64_t number); + +BlockId* BlockId_from_tag(BlockTag tag); + +void BlockId_destroy(BlockId* self); + + + + + +#endif // BlockId_H diff --git a/bindings/c/BlockTag.d.h b/bindings/c/BlockTag.d.h new file mode 100644 index 0000000..7095426 --- /dev/null +++ b/bindings/c/BlockTag.d.h @@ -0,0 +1,23 @@ +#ifndef BlockTag_D_H +#define BlockTag_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum BlockTag { + BlockTag_Latest = 0, + BlockTag_PreConfirmed = 1, +} BlockTag; + +typedef struct BlockTag_option {union { BlockTag ok; }; bool is_ok; } BlockTag_option; + + + +#endif // BlockTag_D_H diff --git a/bindings/c/BlockTag.h b/bindings/c/BlockTag.h new file mode 100644 index 0000000..7bf87c2 --- /dev/null +++ b/bindings/c/BlockTag.h @@ -0,0 +1,22 @@ +#ifndef BlockTag_H +#define BlockTag_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "BlockTag.d.h" + + + + + + + + + + +#endif // BlockTag_H diff --git a/bindings/c/Call.d.h b/bindings/c/Call.d.h new file mode 100644 index 0000000..27ccd8f --- /dev/null +++ b/bindings/c/Call.d.h @@ -0,0 +1,19 @@ +#ifndef Call_D_H +#define Call_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Call Call; + + + + +#endif // Call_D_H diff --git a/bindings/c/Call.h b/bindings/c/Call.h new file mode 100644 index 0000000..eb5ebd6 --- /dev/null +++ b/bindings/c/Call.h @@ -0,0 +1,33 @@ +#ifndef Call_H +#define Call_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" +#include "FieldElement.d.h" + +#include "Call.d.h" + + + + + + +Call* Call_new(const FieldElement* to, const FieldElement* selector); + +void Call_push_calldata(Call* self, const FieldElement* felt); + +typedef struct Call_new_from_selector_name_result {union {Call* ok; DojoError* err;}; bool is_ok;} Call_new_from_selector_name_result; +Call_new_from_selector_name_result Call_new_from_selector_name(const FieldElement* to, DiplomatStringView selector_name); + +void Call_destroy(Call* self); + + + + + +#endif // Call_H diff --git a/bindings/c/CallList.d.h b/bindings/c/CallList.d.h new file mode 100644 index 0000000..916ca61 --- /dev/null +++ b/bindings/c/CallList.d.h @@ -0,0 +1,19 @@ +#ifndef CallList_D_H +#define CallList_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct CallList CallList; + + + + +#endif // CallList_D_H diff --git a/bindings/c/CallList.h b/bindings/c/CallList.h new file mode 100644 index 0000000..34802d7 --- /dev/null +++ b/bindings/c/CallList.h @@ -0,0 +1,31 @@ +#ifndef CallList_H +#define CallList_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "Call.d.h" + +#include "CallList.d.h" + + + + + + +CallList* CallList_new(void); + +void CallList_add_call(CallList* self, const Call* call); + +size_t CallList_len(const CallList* self); + +void CallList_destroy(CallList* self); + + + + + +#endif // CallList_H diff --git a/bindings/c/CallType.d.h b/bindings/c/CallType.d.h new file mode 100644 index 0000000..9ce9aae --- /dev/null +++ b/bindings/c/CallType.d.h @@ -0,0 +1,23 @@ +#ifndef CallType_D_H +#define CallType_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum CallType { + CallType_Execute = 0, + CallType_ExecuteFromOutside = 1, +} CallType; + +typedef struct CallType_option {union { CallType ok; }; bool is_ok; } CallType_option; + + + +#endif // CallType_D_H diff --git a/bindings/c/CallType.h b/bindings/c/CallType.h new file mode 100644 index 0000000..509278c --- /dev/null +++ b/bindings/c/CallType.h @@ -0,0 +1,22 @@ +#ifndef CallType_H +#define CallType_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "CallType.d.h" + + + + + + + + + + +#endif // CallType_H diff --git a/bindings/c/Clause.d.h b/bindings/c/Clause.d.h new file mode 100644 index 0000000..366c3b9 --- /dev/null +++ b/bindings/c/Clause.d.h @@ -0,0 +1,19 @@ +#ifndef Clause_D_H +#define Clause_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Clause Clause; + + + + +#endif // Clause_D_H diff --git a/bindings/c/Clause.h b/bindings/c/Clause.h new file mode 100644 index 0000000..0c03078 --- /dev/null +++ b/bindings/c/Clause.h @@ -0,0 +1,24 @@ +#ifndef Clause_H +#define Clause_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "Clause.d.h" + + + + + + +void Clause_destroy(Clause* self); + + + + + +#endif // Clause_H diff --git a/bindings/c/ComparisonOperator.d.h b/bindings/c/ComparisonOperator.d.h new file mode 100644 index 0000000..0ee3abf --- /dev/null +++ b/bindings/c/ComparisonOperator.d.h @@ -0,0 +1,35 @@ +#ifndef ComparisonOperator_D_H +#define ComparisonOperator_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum ComparisonOperator { + ComparisonOperator_Eq = 0, + ComparisonOperator_Neq = 1, + ComparisonOperator_Gt = 2, + ComparisonOperator_Gte = 3, + ComparisonOperator_Lt = 4, + ComparisonOperator_Lte = 5, + ComparisonOperator_In = 6, + ComparisonOperator_NotIn = 7, + ComparisonOperator_Contains = 8, + ComparisonOperator_ContainsAll = 9, + ComparisonOperator_ContainsAny = 10, + ComparisonOperator_ArrayLengthEq = 11, + ComparisonOperator_ArrayLengthGt = 12, + ComparisonOperator_ArrayLengthLt = 13, +} ComparisonOperator; + +typedef struct ComparisonOperator_option {union { ComparisonOperator ok; }; bool is_ok; } ComparisonOperator_option; + + + +#endif // ComparisonOperator_D_H diff --git a/bindings/c/ComparisonOperator.h b/bindings/c/ComparisonOperator.h new file mode 100644 index 0000000..8914207 --- /dev/null +++ b/bindings/c/ComparisonOperator.h @@ -0,0 +1,22 @@ +#ifndef ComparisonOperator_H +#define ComparisonOperator_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "ComparisonOperator.d.h" + + + + + + + + + + +#endif // ComparisonOperator_H diff --git a/bindings/c/Contract.d.h b/bindings/c/Contract.d.h new file mode 100644 index 0000000..8eb8839 --- /dev/null +++ b/bindings/c/Contract.d.h @@ -0,0 +1,19 @@ +#ifndef Contract_D_H +#define Contract_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Contract Contract; + + + + +#endif // Contract_D_H diff --git a/bindings/c/Contract.h b/bindings/c/Contract.h new file mode 100644 index 0000000..56fa96a --- /dev/null +++ b/bindings/c/Contract.h @@ -0,0 +1,43 @@ +#ifndef Contract_H +#define Contract_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Contract.d.h" + + + + + + +void Contract_contract_address(const Contract* self, DiplomatWrite* write); + +void Contract_contract_type(const Contract* self, DiplomatWrite* write); + +uint64_t Contract_head(const Contract* self); + +uint64_t Contract_tps(const Contract* self); + +uint64_t Contract_created_at(const Contract* self); + +uint64_t Contract_updated_at(const Contract* self); + +typedef struct Contract_from_json_result {union {Contract* ok; DojoError* err;}; bool is_ok;} Contract_from_json_result; +Contract_from_json_result Contract_from_json(DiplomatStringView json); + +typedef struct Contract_to_json_result {union { DojoError* err;}; bool is_ok;} Contract_to_json_result; +Contract_to_json_result Contract_to_json(const Contract* self, DiplomatWrite* write); + +void Contract_destroy(Contract* self); + + + + + +#endif // Contract_H diff --git a/bindings/c/ContractType.d.h b/bindings/c/ContractType.d.h new file mode 100644 index 0000000..bf098bd --- /dev/null +++ b/bindings/c/ContractType.d.h @@ -0,0 +1,27 @@ +#ifndef ContractType_D_H +#define ContractType_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum ContractType { + ContractType_WORLD = 0, + ContractType_ERC20 = 1, + ContractType_ERC721 = 2, + ContractType_ERC1155 = 3, + ContractType_UDC = 4, + ContractType_OTHER = 5, +} ContractType; + +typedef struct ContractType_option {union { ContractType ok; }; bool is_ok; } ContractType_option; + + + +#endif // ContractType_D_H diff --git a/bindings/c/ContractType.h b/bindings/c/ContractType.h new file mode 100644 index 0000000..865acab --- /dev/null +++ b/bindings/c/ContractType.h @@ -0,0 +1,22 @@ +#ifndef ContractType_H +#define ContractType_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "ContractType.d.h" + + + + + + + + + + +#endif // ContractType_H diff --git a/bindings/c/DojoError.d.h b/bindings/c/DojoError.d.h new file mode 100644 index 0000000..5fa8465 --- /dev/null +++ b/bindings/c/DojoError.d.h @@ -0,0 +1,19 @@ +#ifndef DojoError_D_H +#define DojoError_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct DojoError DojoError; + + + + +#endif // DojoError_D_H diff --git a/bindings/c/DojoError.h b/bindings/c/DojoError.h new file mode 100644 index 0000000..06fb9cd --- /dev/null +++ b/bindings/c/DojoError.h @@ -0,0 +1,31 @@ +#ifndef DojoError_H +#define DojoError_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "ErrorType.d.h" + +#include "DojoError.d.h" + + + + + + +DojoError* DojoError_new(ErrorType error_type, DiplomatStringView message); + +void DojoError_message(const DojoError* self, DiplomatWrite* write); + +ErrorType DojoError_error_type(const DojoError* self); + +void DojoError_destroy(DojoError* self); + + + + + +#endif // DojoError_H diff --git a/bindings/c/Entity.d.h b/bindings/c/Entity.d.h new file mode 100644 index 0000000..a47baca --- /dev/null +++ b/bindings/c/Entity.d.h @@ -0,0 +1,19 @@ +#ifndef Entity_D_H +#define Entity_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Entity Entity; + + + + +#endif // Entity_D_H diff --git a/bindings/c/Entity.h b/bindings/c/Entity.h new file mode 100644 index 0000000..0c9fde0 --- /dev/null +++ b/bindings/c/Entity.h @@ -0,0 +1,41 @@ +#ifndef Entity_H +#define Entity_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Entity.d.h" + + + + + + +void Entity_hashed_keys(const Entity* self, DiplomatWrite* write); + +uint32_t Entity_models_count(const Entity* self); + +uint64_t Entity_created_at(const Entity* self); + +uint64_t Entity_updated_at(const Entity* self); + +uint64_t Entity_executed_at(const Entity* self); + +typedef struct Entity_from_json_result {union {Entity* ok; DojoError* err;}; bool is_ok;} Entity_from_json_result; +Entity_from_json_result Entity_from_json(DiplomatStringView json); + +typedef struct Entity_to_json_result {union { DojoError* err;}; bool is_ok;} Entity_to_json_result; +Entity_to_json_result Entity_to_json(const Entity* self, DiplomatWrite* write); + +void Entity_destroy(Entity* self); + + + + + +#endif // Entity_H diff --git a/bindings/c/EntityQuery.d.h b/bindings/c/EntityQuery.d.h new file mode 100644 index 0000000..e8ba32f --- /dev/null +++ b/bindings/c/EntityQuery.d.h @@ -0,0 +1,19 @@ +#ifndef EntityQuery_D_H +#define EntityQuery_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct EntityQuery EntityQuery; + + + + +#endif // EntityQuery_D_H diff --git a/bindings/c/EntityQuery.h b/bindings/c/EntityQuery.h new file mode 100644 index 0000000..18b1c0c --- /dev/null +++ b/bindings/c/EntityQuery.h @@ -0,0 +1,30 @@ +#ifndef EntityQuery_H +#define EntityQuery_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "EntityQuery.d.h" + + + + + + +EntityQuery* EntityQuery_new(void); + +void EntityQuery_set_limit(EntityQuery* self, uint32_t limit); + +void EntityQuery_set_offset(EntityQuery* self, uint32_t offset); + +void EntityQuery_destroy(EntityQuery* self); + + + + + +#endif // EntityQuery_H diff --git a/bindings/c/Enum.d.h b/bindings/c/Enum.d.h new file mode 100644 index 0000000..07ca707 --- /dev/null +++ b/bindings/c/Enum.d.h @@ -0,0 +1,19 @@ +#ifndef Enum_D_H +#define Enum_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Enum Enum; + + + + +#endif // Enum_D_H diff --git a/bindings/c/Enum.h b/bindings/c/Enum.h new file mode 100644 index 0000000..bfdbdbb --- /dev/null +++ b/bindings/c/Enum.h @@ -0,0 +1,37 @@ +#ifndef Enum_H +#define Enum_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Enum.d.h" + + + + + + +void Enum_name(const Enum* self, DiplomatWrite* write); + +uint8_t Enum_option(const Enum* self); + +uint32_t Enum_options_count(const Enum* self); + +typedef struct Enum_from_json_result {union {Enum* ok; DojoError* err;}; bool is_ok;} Enum_from_json_result; +Enum_from_json_result Enum_from_json(DiplomatStringView json); + +typedef struct Enum_to_json_result {union { DojoError* err;}; bool is_ok;} Enum_to_json_result; +Enum_to_json_result Enum_to_json(const Enum* self, DiplomatWrite* write); + +void Enum_destroy(Enum* self); + + + + + +#endif // Enum_H diff --git a/bindings/c/EnumOption.d.h b/bindings/c/EnumOption.d.h new file mode 100644 index 0000000..0261e2f --- /dev/null +++ b/bindings/c/EnumOption.d.h @@ -0,0 +1,19 @@ +#ifndef EnumOption_D_H +#define EnumOption_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct EnumOption EnumOption; + + + + +#endif // EnumOption_D_H diff --git a/bindings/c/EnumOption.h b/bindings/c/EnumOption.h new file mode 100644 index 0000000..661242c --- /dev/null +++ b/bindings/c/EnumOption.h @@ -0,0 +1,26 @@ +#ifndef EnumOption_H +#define EnumOption_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "EnumOption.d.h" + + + + + + +void EnumOption_name(const EnumOption* self, DiplomatWrite* write); + +void EnumOption_destroy(EnumOption* self); + + + + + +#endif // EnumOption_H diff --git a/bindings/c/ErrorType.d.h b/bindings/c/ErrorType.d.h new file mode 100644 index 0000000..0565244 --- /dev/null +++ b/bindings/c/ErrorType.d.h @@ -0,0 +1,34 @@ +#ifndef ErrorType_D_H +#define ErrorType_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum ErrorType { + ErrorType_ClientError = 0, + ErrorType_ParseError = 1, + ErrorType_EntityError = 2, + ErrorType_QueryError = 3, + ErrorType_SubscriptionError = 4, + ErrorType_TransactionError = 5, + ErrorType_AccountError = 6, + ErrorType_SigningError = 7, + ErrorType_ProviderError = 8, + ErrorType_StorageError = 9, + ErrorType_ControllerError = 10, + ErrorType_InvalidInput = 11, + ErrorType_RuntimeError = 12, +} ErrorType; + +typedef struct ErrorType_option {union { ErrorType ok; }; bool is_ok; } ErrorType_option; + + + +#endif // ErrorType_D_H diff --git a/bindings/c/ErrorType.h b/bindings/c/ErrorType.h new file mode 100644 index 0000000..123c5b1 --- /dev/null +++ b/bindings/c/ErrorType.h @@ -0,0 +1,22 @@ +#ifndef ErrorType_H +#define ErrorType_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "ErrorType.d.h" + + + + + + + + + + +#endif // ErrorType_H diff --git a/bindings/c/Event.d.h b/bindings/c/Event.d.h new file mode 100644 index 0000000..b1d1fb4 --- /dev/null +++ b/bindings/c/Event.d.h @@ -0,0 +1,19 @@ +#ifndef Event_D_H +#define Event_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Event Event; + + + + +#endif // Event_D_H diff --git a/bindings/c/Event.h b/bindings/c/Event.h new file mode 100644 index 0000000..c423fdd --- /dev/null +++ b/bindings/c/Event.h @@ -0,0 +1,37 @@ +#ifndef Event_H +#define Event_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Event.d.h" + + + + + + +void Event_keys(const Event* self, DiplomatWrite* write); + +void Event_data(const Event* self, DiplomatWrite* write); + +void Event_transaction_hash(const Event* self, DiplomatWrite* write); + +typedef struct Event_from_json_result {union {Event* ok; DojoError* err;}; bool is_ok;} Event_from_json_result; +Event_from_json_result Event_from_json(DiplomatStringView json); + +typedef struct Event_to_json_result {union { DojoError* err;}; bool is_ok;} Event_to_json_result; +Event_to_json_result Event_to_json(const Event* self, DiplomatWrite* write); + +void Event_destroy(Event* self); + + + + + +#endif // Event_H diff --git a/bindings/c/FieldElement.d.h b/bindings/c/FieldElement.d.h new file mode 100644 index 0000000..62b1d67 --- /dev/null +++ b/bindings/c/FieldElement.d.h @@ -0,0 +1,19 @@ +#ifndef FieldElement_D_H +#define FieldElement_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct FieldElement FieldElement; + + + + +#endif // FieldElement_D_H diff --git a/bindings/c/FieldElement.h b/bindings/c/FieldElement.h new file mode 100644 index 0000000..3a1a813 --- /dev/null +++ b/bindings/c/FieldElement.h @@ -0,0 +1,34 @@ +#ifndef FieldElement_H +#define FieldElement_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "FieldElement.d.h" + + + + + + +typedef struct FieldElement_new_from_hex_result {union {FieldElement* ok; DojoError* err;}; bool is_ok;} FieldElement_new_from_hex_result; +FieldElement_new_from_hex_result FieldElement_new_from_hex(DiplomatStringView hex); + +FieldElement* FieldElement_new_from_bytes(DiplomatU8View bytes); + +void FieldElement_to_hex(const FieldElement* self, DiplomatWrite* write); + +void FieldElement_to_bytes(const FieldElement* self, DiplomatU8ViewMut result); + +void FieldElement_destroy(FieldElement* self); + + + + + +#endif // FieldElement_H diff --git a/bindings/c/KeysClause.d.h b/bindings/c/KeysClause.d.h new file mode 100644 index 0000000..780bbba --- /dev/null +++ b/bindings/c/KeysClause.d.h @@ -0,0 +1,19 @@ +#ifndef KeysClause_D_H +#define KeysClause_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct KeysClause KeysClause; + + + + +#endif // KeysClause_D_H diff --git a/bindings/c/KeysClause.h b/bindings/c/KeysClause.h new file mode 100644 index 0000000..425dfa5 --- /dev/null +++ b/bindings/c/KeysClause.h @@ -0,0 +1,33 @@ +#ifndef KeysClause_H +#define KeysClause_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" +#include "FieldElement.d.h" + +#include "KeysClause.d.h" + + + + + + +KeysClause* KeysClause_new(void); + +void KeysClause_add_key(KeysClause* self, const FieldElement* key); + +typedef struct KeysClause_add_model_result {union { DojoError* err;}; bool is_ok;} KeysClause_add_model_result; +KeysClause_add_model_result KeysClause_add_model(KeysClause* self, DiplomatStringView model); + +void KeysClause_destroy(KeysClause* self); + + + + + +#endif // KeysClause_H diff --git a/bindings/c/LogicalOperator.d.h b/bindings/c/LogicalOperator.d.h new file mode 100644 index 0000000..b534c41 --- /dev/null +++ b/bindings/c/LogicalOperator.d.h @@ -0,0 +1,23 @@ +#ifndef LogicalOperator_D_H +#define LogicalOperator_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum LogicalOperator { + LogicalOperator_And = 0, + LogicalOperator_Or = 1, +} LogicalOperator; + +typedef struct LogicalOperator_option {union { LogicalOperator ok; }; bool is_ok; } LogicalOperator_option; + + + +#endif // LogicalOperator_D_H diff --git a/bindings/c/LogicalOperator.h b/bindings/c/LogicalOperator.h new file mode 100644 index 0000000..cedaeff --- /dev/null +++ b/bindings/c/LogicalOperator.h @@ -0,0 +1,22 @@ +#ifndef LogicalOperator_H +#define LogicalOperator_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "LogicalOperator.d.h" + + + + + + + + + + +#endif // LogicalOperator_H diff --git a/bindings/c/Member.d.h b/bindings/c/Member.d.h new file mode 100644 index 0000000..cddd5a2 --- /dev/null +++ b/bindings/c/Member.d.h @@ -0,0 +1,19 @@ +#ifndef Member_D_H +#define Member_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Member Member; + + + + +#endif // Member_D_H diff --git a/bindings/c/Member.h b/bindings/c/Member.h new file mode 100644 index 0000000..9f2ad6e --- /dev/null +++ b/bindings/c/Member.h @@ -0,0 +1,28 @@ +#ifndef Member_H +#define Member_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "Member.d.h" + + + + + + +void Member_name(const Member* self, DiplomatWrite* write); + +bool Member_is_key(const Member* self); + +void Member_destroy(Member* self); + + + + + +#endif // Member_H diff --git a/bindings/c/Model.d.h b/bindings/c/Model.d.h new file mode 100644 index 0000000..a41c68f --- /dev/null +++ b/bindings/c/Model.d.h @@ -0,0 +1,19 @@ +#ifndef Model_D_H +#define Model_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Model Model; + + + + +#endif // Model_D_H diff --git a/bindings/c/Model.h b/bindings/c/Model.h new file mode 100644 index 0000000..2e2e91f --- /dev/null +++ b/bindings/c/Model.h @@ -0,0 +1,47 @@ +#ifndef Model_H +#define Model_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Model.d.h" + + + + + + +void Model_name(const Model* self, DiplomatWrite* write); + +void Model_namespace(const Model* self, DiplomatWrite* write); + +void Model_selector(const Model* self, DiplomatWrite* write); + +void Model_class_hash(const Model* self, DiplomatWrite* write); + +void Model_contract_address(const Model* self, DiplomatWrite* write); + +uint32_t Model_packed_size(const Model* self); + +uint32_t Model_unpacked_size(const Model* self); + +bool Model_use_legacy_store(const Model* self); + +typedef struct Model_from_json_result {union {Model* ok; DojoError* err;}; bool is_ok;} Model_from_json_result; +Model_from_json_result Model_from_json(DiplomatStringView json); + +typedef struct Model_to_json_result {union { DojoError* err;}; bool is_ok;} Model_to_json_result; +Model_to_json_result Model_to_json(const Model* self, DiplomatWrite* write); + +void Model_destroy(Model* self); + + + + + +#endif // Model_H diff --git a/bindings/c/ModelQuery.d.h b/bindings/c/ModelQuery.d.h new file mode 100644 index 0000000..b66c6d5 --- /dev/null +++ b/bindings/c/ModelQuery.d.h @@ -0,0 +1,19 @@ +#ifndef ModelQuery_D_H +#define ModelQuery_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct ModelQuery ModelQuery; + + + + +#endif // ModelQuery_D_H diff --git a/bindings/c/ModelQuery.h b/bindings/c/ModelQuery.h new file mode 100644 index 0000000..700ba37 --- /dev/null +++ b/bindings/c/ModelQuery.h @@ -0,0 +1,30 @@ +#ifndef ModelQuery_H +#define ModelQuery_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "ModelQuery.d.h" + + + + + + +ModelQuery* ModelQuery_new(void); + +typedef struct ModelQuery_add_model_result {union { DojoError* err;}; bool is_ok;} ModelQuery_add_model_result; +ModelQuery_add_model_result ModelQuery_add_model(ModelQuery* self, DiplomatStringView model_name); + +void ModelQuery_destroy(ModelQuery* self); + + + + + +#endif // ModelQuery_H diff --git a/bindings/c/OrderBy.d.h b/bindings/c/OrderBy.d.h new file mode 100644 index 0000000..b4dc909 --- /dev/null +++ b/bindings/c/OrderBy.d.h @@ -0,0 +1,19 @@ +#ifndef OrderBy_D_H +#define OrderBy_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct OrderBy OrderBy; + + + + +#endif // OrderBy_D_H diff --git a/bindings/c/OrderBy.h b/bindings/c/OrderBy.h new file mode 100644 index 0000000..c241015 --- /dev/null +++ b/bindings/c/OrderBy.h @@ -0,0 +1,29 @@ +#ifndef OrderBy_H +#define OrderBy_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" +#include "OrderDirection.d.h" + +#include "OrderBy.d.h" + + + + + + +typedef struct OrderBy_new_result {union {OrderBy* ok; DojoError* err;}; bool is_ok;} OrderBy_new_result; +OrderBy_new_result OrderBy_new(DiplomatStringView field, OrderDirection direction); + +void OrderBy_destroy(OrderBy* self); + + + + + +#endif // OrderBy_H diff --git a/bindings/c/OrderDirection.d.h b/bindings/c/OrderDirection.d.h new file mode 100644 index 0000000..1232258 --- /dev/null +++ b/bindings/c/OrderDirection.d.h @@ -0,0 +1,23 @@ +#ifndef OrderDirection_D_H +#define OrderDirection_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum OrderDirection { + OrderDirection_Asc = 0, + OrderDirection_Desc = 1, +} OrderDirection; + +typedef struct OrderDirection_option {union { OrderDirection ok; }; bool is_ok; } OrderDirection_option; + + + +#endif // OrderDirection_D_H diff --git a/bindings/c/OrderDirection.h b/bindings/c/OrderDirection.h new file mode 100644 index 0000000..3458761 --- /dev/null +++ b/bindings/c/OrderDirection.h @@ -0,0 +1,22 @@ +#ifndef OrderDirection_H +#define OrderDirection_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "OrderDirection.d.h" + + + + + + + + + + +#endif // OrderDirection_H diff --git a/bindings/c/Pagination.d.h b/bindings/c/Pagination.d.h new file mode 100644 index 0000000..7d9228b --- /dev/null +++ b/bindings/c/Pagination.d.h @@ -0,0 +1,19 @@ +#ifndef Pagination_D_H +#define Pagination_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Pagination Pagination; + + + + +#endif // Pagination_D_H diff --git a/bindings/c/Pagination.h b/bindings/c/Pagination.h new file mode 100644 index 0000000..4671deb --- /dev/null +++ b/bindings/c/Pagination.h @@ -0,0 +1,38 @@ +#ifndef Pagination_H +#define Pagination_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" +#include "OrderBy.d.h" +#include "PaginationDirection.d.h" + +#include "Pagination.d.h" + + + + + + +Pagination* Pagination_new(void); + +typedef struct Pagination_set_cursor_result {union { DojoError* err;}; bool is_ok;} Pagination_set_cursor_result; +Pagination_set_cursor_result Pagination_set_cursor(Pagination* self, DiplomatStringView cursor); + +void Pagination_set_limit(Pagination* self, uint32_t limit); + +void Pagination_set_direction(Pagination* self, PaginationDirection direction); + +void Pagination_add_order_by(Pagination* self, const OrderBy* order_by); + +void Pagination_destroy(Pagination* self); + + + + + +#endif // Pagination_H diff --git a/bindings/c/PaginationDirection.d.h b/bindings/c/PaginationDirection.d.h new file mode 100644 index 0000000..164861d --- /dev/null +++ b/bindings/c/PaginationDirection.d.h @@ -0,0 +1,23 @@ +#ifndef PaginationDirection_D_H +#define PaginationDirection_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum PaginationDirection { + PaginationDirection_Forward = 0, + PaginationDirection_Backward = 1, +} PaginationDirection; + +typedef struct PaginationDirection_option {union { PaginationDirection ok; }; bool is_ok; } PaginationDirection_option; + + + +#endif // PaginationDirection_D_H diff --git a/bindings/c/PaginationDirection.h b/bindings/c/PaginationDirection.h new file mode 100644 index 0000000..fbe8aa1 --- /dev/null +++ b/bindings/c/PaginationDirection.h @@ -0,0 +1,22 @@ +#ifndef PaginationDirection_H +#define PaginationDirection_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "PaginationDirection.d.h" + + + + + + + + + + +#endif // PaginationDirection_H diff --git a/bindings/c/PatternMatching.d.h b/bindings/c/PatternMatching.d.h new file mode 100644 index 0000000..bbcb17c --- /dev/null +++ b/bindings/c/PatternMatching.d.h @@ -0,0 +1,23 @@ +#ifndef PatternMatching_D_H +#define PatternMatching_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum PatternMatching { + PatternMatching_FixedLen = 0, + PatternMatching_VariableLen = 1, +} PatternMatching; + +typedef struct PatternMatching_option {union { PatternMatching ok; }; bool is_ok; } PatternMatching_option; + + + +#endif // PatternMatching_D_H diff --git a/bindings/c/PatternMatching.h b/bindings/c/PatternMatching.h new file mode 100644 index 0000000..e667b14 --- /dev/null +++ b/bindings/c/PatternMatching.h @@ -0,0 +1,22 @@ +#ifndef PatternMatching_H +#define PatternMatching_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "PatternMatching.d.h" + + + + + + + + + + +#endif // PatternMatching_H diff --git a/bindings/c/PlayerAchievementEntry.d.h b/bindings/c/PlayerAchievementEntry.d.h new file mode 100644 index 0000000..3e1e018 --- /dev/null +++ b/bindings/c/PlayerAchievementEntry.d.h @@ -0,0 +1,19 @@ +#ifndef PlayerAchievementEntry_D_H +#define PlayerAchievementEntry_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct PlayerAchievementEntry PlayerAchievementEntry; + + + + +#endif // PlayerAchievementEntry_D_H diff --git a/bindings/c/PlayerAchievementEntry.h b/bindings/c/PlayerAchievementEntry.h new file mode 100644 index 0000000..14154e6 --- /dev/null +++ b/bindings/c/PlayerAchievementEntry.h @@ -0,0 +1,45 @@ +#ifndef PlayerAchievementEntry_H +#define PlayerAchievementEntry_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "PlayerAchievementEntry.d.h" + + + + + + +void PlayerAchievementEntry_player_address(const PlayerAchievementEntry* self, DiplomatWrite* write); + +uint32_t PlayerAchievementEntry_total_points(const PlayerAchievementEntry* self); + +uint32_t PlayerAchievementEntry_completed_achievements(const PlayerAchievementEntry* self); + +uint32_t PlayerAchievementEntry_total_achievements(const PlayerAchievementEntry* self); + +double PlayerAchievementEntry_completion_percentage(const PlayerAchievementEntry* self); + +uint32_t PlayerAchievementEntry_achievements_count(const PlayerAchievementEntry* self); + +uint64_t PlayerAchievementEntry_updated_at(const PlayerAchievementEntry* self); + +typedef struct PlayerAchievementEntry_from_json_result {union {PlayerAchievementEntry* ok; DojoError* err;}; bool is_ok;} PlayerAchievementEntry_from_json_result; +PlayerAchievementEntry_from_json_result PlayerAchievementEntry_from_json(DiplomatStringView json); + +typedef struct PlayerAchievementEntry_to_json_result {union { DojoError* err;}; bool is_ok;} PlayerAchievementEntry_to_json_result; +PlayerAchievementEntry_to_json_result PlayerAchievementEntry_to_json(const PlayerAchievementEntry* self, DiplomatWrite* write); + +void PlayerAchievementEntry_destroy(PlayerAchievementEntry* self); + + + + + +#endif // PlayerAchievementEntry_H diff --git a/bindings/c/Primitive.d.h b/bindings/c/Primitive.d.h new file mode 100644 index 0000000..98768b0 --- /dev/null +++ b/bindings/c/Primitive.d.h @@ -0,0 +1,19 @@ +#ifndef Primitive_D_H +#define Primitive_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Primitive Primitive; + + + + +#endif // Primitive_D_H diff --git a/bindings/c/Primitive.h b/bindings/c/Primitive.h new file mode 100644 index 0000000..c3f51df --- /dev/null +++ b/bindings/c/Primitive.h @@ -0,0 +1,34 @@ +#ifndef Primitive_H +#define Primitive_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" +#include "PrimitiveType.d.h" + +#include "Primitive.d.h" + + + + + + +PrimitiveType Primitive_primitive_type(const Primitive* self); + +typedef struct Primitive_from_json_result {union {Primitive* ok; DojoError* err;}; bool is_ok;} Primitive_from_json_result; +Primitive_from_json_result Primitive_from_json(DiplomatStringView json); + +typedef struct Primitive_to_json_result {union { DojoError* err;}; bool is_ok;} Primitive_to_json_result; +Primitive_to_json_result Primitive_to_json(const Primitive* self, DiplomatWrite* write); + +void Primitive_destroy(Primitive* self); + + + + + +#endif // Primitive_H diff --git a/bindings/c/PrimitiveType.d.h b/bindings/c/PrimitiveType.d.h new file mode 100644 index 0000000..e01030e --- /dev/null +++ b/bindings/c/PrimitiveType.d.h @@ -0,0 +1,37 @@ +#ifndef PrimitiveType_D_H +#define PrimitiveType_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum PrimitiveType { + PrimitiveType_I8 = 0, + PrimitiveType_I16 = 1, + PrimitiveType_I32 = 2, + PrimitiveType_I64 = 3, + PrimitiveType_I128 = 4, + PrimitiveType_U8 = 5, + PrimitiveType_U16 = 6, + PrimitiveType_U32 = 7, + PrimitiveType_U64 = 8, + PrimitiveType_U128 = 9, + PrimitiveType_U256 = 10, + PrimitiveType_Bool = 11, + PrimitiveType_Felt252 = 12, + PrimitiveType_ClassHash = 13, + PrimitiveType_ContractAddress = 14, + PrimitiveType_EthAddress = 15, +} PrimitiveType; + +typedef struct PrimitiveType_option {union { PrimitiveType ok; }; bool is_ok; } PrimitiveType_option; + + + +#endif // PrimitiveType_D_H diff --git a/bindings/c/PrimitiveType.h b/bindings/c/PrimitiveType.h new file mode 100644 index 0000000..b99d401 --- /dev/null +++ b/bindings/c/PrimitiveType.h @@ -0,0 +1,22 @@ +#ifndef PrimitiveType_H +#define PrimitiveType_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "PrimitiveType.d.h" + + + + + + + + + + +#endif // PrimitiveType_H diff --git a/bindings/c/Provider.d.h b/bindings/c/Provider.d.h new file mode 100644 index 0000000..f557791 --- /dev/null +++ b/bindings/c/Provider.d.h @@ -0,0 +1,19 @@ +#ifndef Provider_D_H +#define Provider_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Provider Provider; + + + + +#endif // Provider_D_H diff --git a/bindings/c/Provider.h b/bindings/c/Provider.h new file mode 100644 index 0000000..3025fb7 --- /dev/null +++ b/bindings/c/Provider.h @@ -0,0 +1,34 @@ +#ifndef Provider_H +#define Provider_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Provider.d.h" + + + + + + +typedef struct Provider_new_result {union {Provider* ok; DojoError* err;}; bool is_ok;} Provider_new_result; +Provider_new_result Provider_new(DiplomatStringView rpc_url); + +typedef struct Provider_chain_id_result {union { DojoError* err;}; bool is_ok;} Provider_chain_id_result; +Provider_chain_id_result Provider_chain_id(const Provider* self, DiplomatWrite* write); + +typedef struct Provider_block_number_result {union {uint64_t ok; DojoError* err;}; bool is_ok;} Provider_block_number_result; +Provider_block_number_result Provider_block_number(const Provider* self); + +void Provider_destroy(Provider* self); + + + + + +#endif // Provider_H diff --git a/bindings/c/Signature.d.h b/bindings/c/Signature.d.h new file mode 100644 index 0000000..3855de8 --- /dev/null +++ b/bindings/c/Signature.d.h @@ -0,0 +1,19 @@ +#ifndef Signature_D_H +#define Signature_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Signature Signature; + + + + +#endif // Signature_D_H diff --git a/bindings/c/Signature.h b/bindings/c/Signature.h new file mode 100644 index 0000000..94b7035 --- /dev/null +++ b/bindings/c/Signature.h @@ -0,0 +1,31 @@ +#ifndef Signature_H +#define Signature_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "FieldElement.d.h" + +#include "Signature.d.h" + + + + + + +Signature* Signature_new(const FieldElement* r, const FieldElement* s); + +void Signature_r(const Signature* self, DiplomatWrite* write); + +void Signature_s(const Signature* self, DiplomatWrite* write); + +void Signature_destroy(Signature* self); + + + + + +#endif // Signature_H diff --git a/bindings/c/SigningKey.d.h b/bindings/c/SigningKey.d.h new file mode 100644 index 0000000..7ffe9a9 --- /dev/null +++ b/bindings/c/SigningKey.d.h @@ -0,0 +1,19 @@ +#ifndef SigningKey_D_H +#define SigningKey_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct SigningKey SigningKey; + + + + +#endif // SigningKey_D_H diff --git a/bindings/c/SigningKey.h b/bindings/c/SigningKey.h new file mode 100644 index 0000000..9be36b2 --- /dev/null +++ b/bindings/c/SigningKey.h @@ -0,0 +1,40 @@ +#ifndef SigningKey_H +#define SigningKey_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" +#include "FieldElement.d.h" +#include "Signature.d.h" +#include "VerifyingKey.d.h" + +#include "SigningKey.d.h" + + + + + + +typedef struct SigningKey_new_result {union {SigningKey* ok; DojoError* err;}; bool is_ok;} SigningKey_new_result; +SigningKey_new_result SigningKey_new(DiplomatStringView secret_scalar); + +SigningKey* SigningKey_from_random(void); + +void SigningKey_secret_scalar(const SigningKey* self, DiplomatWrite* write); + +typedef struct SigningKey_sign_result {union {Signature* ok; DojoError* err;}; bool is_ok;} SigningKey_sign_result; +SigningKey_sign_result SigningKey_sign(const SigningKey* self, const FieldElement* hash); + +VerifyingKey* SigningKey_verifying_key(const SigningKey* self); + +void SigningKey_destroy(SigningKey* self); + + + + + +#endif // SigningKey_H diff --git a/bindings/c/Struct.d.h b/bindings/c/Struct.d.h new file mode 100644 index 0000000..0f7b5f5 --- /dev/null +++ b/bindings/c/Struct.d.h @@ -0,0 +1,19 @@ +#ifndef Struct_D_H +#define Struct_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Struct Struct; + + + + +#endif // Struct_D_H diff --git a/bindings/c/Struct.h b/bindings/c/Struct.h new file mode 100644 index 0000000..0aae135 --- /dev/null +++ b/bindings/c/Struct.h @@ -0,0 +1,35 @@ +#ifndef Struct_H +#define Struct_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Struct.d.h" + + + + + + +void Struct_name(const Struct* self, DiplomatWrite* write); + +uint32_t Struct_children_count(const Struct* self); + +typedef struct Struct_from_json_result {union {Struct* ok; DojoError* err;}; bool is_ok;} Struct_from_json_result; +Struct_from_json_result Struct_from_json(DiplomatStringView json); + +typedef struct Struct_to_json_result {union { DojoError* err;}; bool is_ok;} Struct_to_json_result; +Struct_to_json_result Struct_to_json(const Struct* self, DiplomatWrite* write); + +void Struct_destroy(Struct* self); + + + + + +#endif // Struct_H diff --git a/bindings/c/Subscription.d.h b/bindings/c/Subscription.d.h new file mode 100644 index 0000000..e6545bc --- /dev/null +++ b/bindings/c/Subscription.d.h @@ -0,0 +1,19 @@ +#ifndef Subscription_D_H +#define Subscription_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Subscription Subscription; + + + + +#endif // Subscription_D_H diff --git a/bindings/c/Subscription.h b/bindings/c/Subscription.h new file mode 100644 index 0000000..a9bb6cd --- /dev/null +++ b/bindings/c/Subscription.h @@ -0,0 +1,26 @@ +#ifndef Subscription_H +#define Subscription_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "Subscription.d.h" + + + + + + +uint64_t Subscription_id(const Subscription* self); + +void Subscription_destroy(Subscription* self); + + + + + +#endif // Subscription_H diff --git a/bindings/c/Token.d.h b/bindings/c/Token.d.h new file mode 100644 index 0000000..d4adb3c --- /dev/null +++ b/bindings/c/Token.d.h @@ -0,0 +1,19 @@ +#ifndef Token_D_H +#define Token_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Token Token; + + + + +#endif // Token_D_H diff --git a/bindings/c/Token.h b/bindings/c/Token.h new file mode 100644 index 0000000..faa80b0 --- /dev/null +++ b/bindings/c/Token.h @@ -0,0 +1,41 @@ +#ifndef Token_H +#define Token_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Token.d.h" + + + + + + +void Token_contract_address(const Token* self, DiplomatWrite* write); + +void Token_name(const Token* self, DiplomatWrite* write); + +void Token_symbol(const Token* self, DiplomatWrite* write); + +uint8_t Token_decimals(const Token* self); + +void Token_metadata(const Token* self, DiplomatWrite* write); + +typedef struct Token_from_json_result {union {Token* ok; DojoError* err;}; bool is_ok;} Token_from_json_result; +Token_from_json_result Token_from_json(DiplomatStringView json); + +typedef struct Token_to_json_result {union { DojoError* err;}; bool is_ok;} Token_to_json_result; +Token_to_json_result Token_to_json(const Token* self, DiplomatWrite* write); + +void Token_destroy(Token* self); + + + + + +#endif // Token_H diff --git a/bindings/c/TokenBalance.d.h b/bindings/c/TokenBalance.d.h new file mode 100644 index 0000000..43edfd3 --- /dev/null +++ b/bindings/c/TokenBalance.d.h @@ -0,0 +1,19 @@ +#ifndef TokenBalance_D_H +#define TokenBalance_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct TokenBalance TokenBalance; + + + + +#endif // TokenBalance_D_H diff --git a/bindings/c/TokenBalance.h b/bindings/c/TokenBalance.h new file mode 100644 index 0000000..d2d026b --- /dev/null +++ b/bindings/c/TokenBalance.h @@ -0,0 +1,37 @@ +#ifndef TokenBalance_H +#define TokenBalance_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "TokenBalance.d.h" + + + + + + +void TokenBalance_account_address(const TokenBalance* self, DiplomatWrite* write); + +void TokenBalance_contract_address(const TokenBalance* self, DiplomatWrite* write); + +void TokenBalance_balance(const TokenBalance* self, DiplomatWrite* write); + +typedef struct TokenBalance_from_json_result {union {TokenBalance* ok; DojoError* err;}; bool is_ok;} TokenBalance_from_json_result; +TokenBalance_from_json_result TokenBalance_from_json(DiplomatStringView json); + +typedef struct TokenBalance_to_json_result {union { DojoError* err;}; bool is_ok;} TokenBalance_to_json_result; +TokenBalance_to_json_result TokenBalance_to_json(const TokenBalance* self, DiplomatWrite* write); + +void TokenBalance_destroy(TokenBalance* self); + + + + + +#endif // TokenBalance_H diff --git a/bindings/c/TokenContract.d.h b/bindings/c/TokenContract.d.h new file mode 100644 index 0000000..8821585 --- /dev/null +++ b/bindings/c/TokenContract.d.h @@ -0,0 +1,19 @@ +#ifndef TokenContract_D_H +#define TokenContract_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct TokenContract TokenContract; + + + + +#endif // TokenContract_D_H diff --git a/bindings/c/TokenContract.h b/bindings/c/TokenContract.h new file mode 100644 index 0000000..c1e4aee --- /dev/null +++ b/bindings/c/TokenContract.h @@ -0,0 +1,35 @@ +#ifndef TokenContract_H +#define TokenContract_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "TokenContract.d.h" + + + + + + +void TokenContract_contract_address(const TokenContract* self, DiplomatWrite* write); + +void TokenContract_contract_type(const TokenContract* self, DiplomatWrite* write); + +typedef struct TokenContract_from_json_result {union {TokenContract* ok; DojoError* err;}; bool is_ok;} TokenContract_from_json_result; +TokenContract_from_json_result TokenContract_from_json(DiplomatStringView json); + +typedef struct TokenContract_to_json_result {union { DojoError* err;}; bool is_ok;} TokenContract_to_json_result; +TokenContract_to_json_result TokenContract_to_json(const TokenContract* self, DiplomatWrite* write); + +void TokenContract_destroy(TokenContract* self); + + + + + +#endif // TokenContract_H diff --git a/bindings/c/TokenTransfer.d.h b/bindings/c/TokenTransfer.d.h new file mode 100644 index 0000000..e4b97a2 --- /dev/null +++ b/bindings/c/TokenTransfer.d.h @@ -0,0 +1,19 @@ +#ifndef TokenTransfer_D_H +#define TokenTransfer_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct TokenTransfer TokenTransfer; + + + + +#endif // TokenTransfer_D_H diff --git a/bindings/c/TokenTransfer.h b/bindings/c/TokenTransfer.h new file mode 100644 index 0000000..bc1d657 --- /dev/null +++ b/bindings/c/TokenTransfer.h @@ -0,0 +1,41 @@ +#ifndef TokenTransfer_H +#define TokenTransfer_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "TokenTransfer.d.h" + + + + + + +void TokenTransfer_from_address(const TokenTransfer* self, DiplomatWrite* write); + +void TokenTransfer_to_address(const TokenTransfer* self, DiplomatWrite* write); + +void TokenTransfer_contract_address(const TokenTransfer* self, DiplomatWrite* write); + +void TokenTransfer_amount(const TokenTransfer* self, DiplomatWrite* write); + +uint64_t TokenTransfer_executed_at(const TokenTransfer* self); + +typedef struct TokenTransfer_from_json_result {union {TokenTransfer* ok; DojoError* err;}; bool is_ok;} TokenTransfer_from_json_result; +TokenTransfer_from_json_result TokenTransfer_from_json(DiplomatStringView json); + +typedef struct TokenTransfer_to_json_result {union { DojoError* err;}; bool is_ok;} TokenTransfer_to_json_result; +TokenTransfer_to_json_result TokenTransfer_to_json(const TokenTransfer* self, DiplomatWrite* write); + +void TokenTransfer_destroy(TokenTransfer* self); + + + + + +#endif // TokenTransfer_H diff --git a/bindings/c/ToriiClient.d.h b/bindings/c/ToriiClient.d.h new file mode 100644 index 0000000..f886540 --- /dev/null +++ b/bindings/c/ToriiClient.d.h @@ -0,0 +1,19 @@ +#ifndef ToriiClient_D_H +#define ToriiClient_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct ToriiClient ToriiClient; + + + + +#endif // ToriiClient_D_H diff --git a/bindings/c/ToriiClient.h b/bindings/c/ToriiClient.h new file mode 100644 index 0000000..5134d1f --- /dev/null +++ b/bindings/c/ToriiClient.h @@ -0,0 +1,35 @@ +#ifndef ToriiClient_H +#define ToriiClient_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" +#include "FieldElement.d.h" + +#include "ToriiClient.d.h" + + + + + + +typedef struct ToriiClient_new_result {union {ToriiClient* ok; DojoError* err;}; bool is_ok;} ToriiClient_new_result; +ToriiClient_new_result ToriiClient_new(DiplomatStringView torii_url); + +typedef struct ToriiClient_info_result {union { DojoError* err;}; bool is_ok;} ToriiClient_info_result; +ToriiClient_info_result ToriiClient_info(const ToriiClient* self, DiplomatWrite* write); + +typedef struct ToriiClient_publish_message_result {union { DojoError* err;}; bool is_ok;} ToriiClient_publish_message_result; +ToriiClient_publish_message_result ToriiClient_publish_message(const ToriiClient* self, DiplomatStringView message_json, const FieldElement* signature_r, const FieldElement* signature_s, const FieldElement* world_address, DiplomatWrite* write); + +void ToriiClient_destroy(ToriiClient* self); + + + + + +#endif // ToriiClient_H diff --git a/bindings/c/Transaction.d.h b/bindings/c/Transaction.d.h new file mode 100644 index 0000000..2b26794 --- /dev/null +++ b/bindings/c/Transaction.d.h @@ -0,0 +1,19 @@ +#ifndef Transaction_D_H +#define Transaction_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct Transaction Transaction; + + + + +#endif // Transaction_D_H diff --git a/bindings/c/Transaction.h b/bindings/c/Transaction.h new file mode 100644 index 0000000..77b501e --- /dev/null +++ b/bindings/c/Transaction.h @@ -0,0 +1,45 @@ +#ifndef Transaction_H +#define Transaction_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "Transaction.d.h" + + + + + + +void Transaction_transaction_hash(const Transaction* self, DiplomatWrite* write); + +void Transaction_sender_address(const Transaction* self, DiplomatWrite* write); + +void Transaction_max_fee(const Transaction* self, DiplomatWrite* write); + +void Transaction_signature(const Transaction* self, DiplomatWrite* write); + +void Transaction_nonce(const Transaction* self, DiplomatWrite* write); + +uint64_t Transaction_block_timestamp(const Transaction* self); + +uint64_t Transaction_block_number(const Transaction* self); + +typedef struct Transaction_from_json_result {union {Transaction* ok; DojoError* err;}; bool is_ok;} Transaction_from_json_result; +Transaction_from_json_result Transaction_from_json(DiplomatStringView json); + +typedef struct Transaction_to_json_result {union { DojoError* err;}; bool is_ok;} Transaction_to_json_result; +Transaction_to_json_result Transaction_to_json(const Transaction* self, DiplomatWrite* write); + +void Transaction_destroy(Transaction* self); + + + + + +#endif // Transaction_H diff --git a/bindings/c/TypedData.d.h b/bindings/c/TypedData.d.h new file mode 100644 index 0000000..4f7cdb2 --- /dev/null +++ b/bindings/c/TypedData.d.h @@ -0,0 +1,19 @@ +#ifndef TypedData_D_H +#define TypedData_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct TypedData TypedData; + + + + +#endif // TypedData_D_H diff --git a/bindings/c/TypedData.h b/bindings/c/TypedData.h new file mode 100644 index 0000000..4972e39 --- /dev/null +++ b/bindings/c/TypedData.h @@ -0,0 +1,28 @@ +#ifndef TypedData_H +#define TypedData_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "TypedData.d.h" + + + + + + +typedef struct TypedData_new_from_json_result {union {TypedData* ok; DojoError* err;}; bool is_ok;} TypedData_new_from_json_result; +TypedData_new_from_json_result TypedData_new_from_json(DiplomatStringView json); + +void TypedData_destroy(TypedData* self); + + + + + +#endif // TypedData_H diff --git a/bindings/c/U256.d.h b/bindings/c/U256.d.h new file mode 100644 index 0000000..f3f1b82 --- /dev/null +++ b/bindings/c/U256.d.h @@ -0,0 +1,19 @@ +#ifndef U256_D_H +#define U256_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct U256 U256; + + + + +#endif // U256_D_H diff --git a/bindings/c/U256.h b/bindings/c/U256.h new file mode 100644 index 0000000..ef67ccf --- /dev/null +++ b/bindings/c/U256.h @@ -0,0 +1,35 @@ +#ifndef U256_H +#define U256_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "U256.d.h" + + + + + + +typedef struct U256_new_from_hex_result {union {U256* ok; DojoError* err;}; bool is_ok;} U256_new_from_hex_result; +U256_new_from_hex_result U256_new_from_hex(DiplomatStringView hex); + +typedef struct U256_new_from_bytes_result {union {U256* ok; DojoError* err;}; bool is_ok;} U256_new_from_bytes_result; +U256_new_from_bytes_result U256_new_from_bytes(DiplomatU8View bytes); + +void U256_to_hex(const U256* self, DiplomatWrite* write); + +void U256_to_bytes(const U256* self, DiplomatU8ViewMut result); + +void U256_destroy(U256* self); + + + + + +#endif // U256_H diff --git a/bindings/c/VerifyingKey.d.h b/bindings/c/VerifyingKey.d.h new file mode 100644 index 0000000..fb90f85 --- /dev/null +++ b/bindings/c/VerifyingKey.d.h @@ -0,0 +1,19 @@ +#ifndef VerifyingKey_D_H +#define VerifyingKey_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct VerifyingKey VerifyingKey; + + + + +#endif // VerifyingKey_D_H diff --git a/bindings/c/VerifyingKey.h b/bindings/c/VerifyingKey.h new file mode 100644 index 0000000..1085459 --- /dev/null +++ b/bindings/c/VerifyingKey.h @@ -0,0 +1,32 @@ +#ifndef VerifyingKey_H +#define VerifyingKey_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" +#include "FieldElement.d.h" +#include "Signature.d.h" + +#include "VerifyingKey.d.h" + + + + + + +void VerifyingKey_scalar(const VerifyingKey* self, DiplomatWrite* write); + +typedef struct VerifyingKey_verify_result {union {bool ok; DojoError* err;}; bool is_ok;} VerifyingKey_verify_result; +VerifyingKey_verify_result VerifyingKey_verify(const VerifyingKey* self, const FieldElement* hash, const Signature* signature); + +void VerifyingKey_destroy(VerifyingKey* self); + + + + + +#endif // VerifyingKey_H diff --git a/bindings/c/World.d.h b/bindings/c/World.d.h new file mode 100644 index 0000000..cd33c80 --- /dev/null +++ b/bindings/c/World.d.h @@ -0,0 +1,19 @@ +#ifndef World_D_H +#define World_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef struct World World; + + + + +#endif // World_D_H diff --git a/bindings/c/World.h b/bindings/c/World.h new file mode 100644 index 0000000..b58038f --- /dev/null +++ b/bindings/c/World.h @@ -0,0 +1,35 @@ +#ifndef World_H +#define World_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + +#include "DojoError.d.h" + +#include "World.d.h" + + + + + + +void World_world_address(const World* self, DiplomatWrite* write); + +uint32_t World_models_count(const World* self); + +typedef struct World_from_json_result {union {World* ok; DojoError* err;}; bool is_ok;} World_from_json_result; +World_from_json_result World_from_json(DiplomatStringView json); + +typedef struct World_to_json_result {union { DojoError* err;}; bool is_ok;} World_to_json_result; +World_to_json_result World_to_json(const World* self, DiplomatWrite* write); + +void World_destroy(World* self); + + + + + +#endif // World_H diff --git a/bindings/c/diplomat_runtime.h b/bindings/c/diplomat_runtime.h new file mode 100644 index 0000000..e5d6b29 --- /dev/null +++ b/bindings/c/diplomat_runtime.h @@ -0,0 +1,82 @@ +#ifndef DIPLOMAT_RUNTIME_C_H +#define DIPLOMAT_RUNTIME_C_H + +#include +#include +#include +#include + +// These come from `uchar.h`, which is not available on all platforms. +// Redefining them in C is no problem, however in >C++11 they are fundamental +// types, which don't like being redefined. +#if !(__cplusplus >= 201100) +// https://en.cppreference.com/w/c/string/multibyte/char16_t +typedef uint_least16_t char16_t; +// https://en.cppreference.com/w/c/string/multibyte/char32_t +typedef uint_least32_t char32_t; +#endif + +static_assert(sizeof(char) == sizeof(uint8_t), "your architecture's `char` is not 8 bits"); +static_assert(sizeof(char16_t) == sizeof(uint16_t), "your architecture's `char16_t` is not 16 bits"); +static_assert(sizeof(char32_t) == sizeof(uint32_t), "your architecture's `char32_t` is not 32 bits"); + +typedef struct DiplomatWrite { + void* context; + char* buf; + size_t len; + size_t cap; + bool grow_failed; + void (*flush)(struct DiplomatWrite*); + bool (*grow)(struct DiplomatWrite*, size_t); +} DiplomatWrite; + +bool diplomat_is_str(const char* buf, size_t len); + +#define MAKE_SLICES(name, c_ty) \ + typedef struct Diplomat##name##View { \ + const c_ty* data; \ + size_t len; \ + } Diplomat##name##View; \ + typedef struct Diplomat##name##ViewMut { \ + c_ty* data; \ + size_t len; \ + } Diplomat##name##ViewMut; \ + typedef struct Diplomat##name##Array { \ + const c_ty* data; \ + size_t len; \ + } Diplomat##name##Array; + +#define MAKE_SLICES_AND_OPTIONS(name, c_ty) \ + MAKE_SLICES(name, c_ty) \ + typedef struct Option##name {union { c_ty ok; }; bool is_ok; } Option##name; \ + typedef struct Option##name##View {union { Diplomat##name##View ok; }; bool is_ok; } Option##name##View; \ + typedef struct Option##name##ViewMut {union { Diplomat##name##ViewMut ok; }; bool is_ok; } Option##name##ViewMut; \ + typedef struct Option##name##Array {union { Diplomat##name##Array ok; }; bool is_ok; } Option##name##Array; \ + +MAKE_SLICES_AND_OPTIONS(I8, int8_t) +MAKE_SLICES_AND_OPTIONS(U8, uint8_t) +MAKE_SLICES_AND_OPTIONS(I16, int16_t) +MAKE_SLICES_AND_OPTIONS(U16, uint16_t) +MAKE_SLICES_AND_OPTIONS(I32, int32_t) +MAKE_SLICES_AND_OPTIONS(U32, uint32_t) +MAKE_SLICES_AND_OPTIONS(I64, int64_t) +MAKE_SLICES_AND_OPTIONS(U64, uint64_t) +MAKE_SLICES_AND_OPTIONS(Isize, intptr_t) +MAKE_SLICES_AND_OPTIONS(Usize, size_t) +MAKE_SLICES_AND_OPTIONS(F32, float) +MAKE_SLICES_AND_OPTIONS(F64, double) +MAKE_SLICES_AND_OPTIONS(Bool, bool) +MAKE_SLICES_AND_OPTIONS(Char, char32_t) +MAKE_SLICES_AND_OPTIONS(String, char) +MAKE_SLICES_AND_OPTIONS(String16, char16_t) +MAKE_SLICES_AND_OPTIONS(Strings, DiplomatStringView) +MAKE_SLICES_AND_OPTIONS(Strings16, DiplomatString16View) + +DiplomatWrite diplomat_simple_write(char* buf, size_t buf_size); + +DiplomatWrite* diplomat_buffer_write_create(size_t cap); +char* diplomat_buffer_write_get_bytes(DiplomatWrite* t); +size_t diplomat_buffer_write_len(DiplomatWrite* t); +void diplomat_buffer_write_destroy(DiplomatWrite* t); + +#endif diff --git a/bindings/cpp/Account.d.hpp b/bindings/cpp/Account.d.hpp new file mode 100644 index 0000000..472bed7 --- /dev/null +++ b/bindings/cpp/Account.d.hpp @@ -0,0 +1,84 @@ +#ifndef Account_D_HPP +#define Account_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct CallList; } +class CallList; +namespace diplomat::capi { struct DojoError; } +class DojoError; +namespace diplomat::capi { struct FieldElement; } +class FieldElement; +namespace diplomat::capi { struct Provider; } +class Provider; +namespace diplomat::capi { struct SigningKey; } +class SigningKey; + + +namespace diplomat { +namespace capi { + struct Account; +} // namespace capi +} // namespace + +/** + * Starknet account for signing and executing transactions + */ +class Account { +public: + + /** + * Creates a new account + */ + inline static std::unique_ptr new_(const Provider& provider, const SigningKey& signer, const FieldElement& address, const FieldElement& chain_id); + + /** + * Gets the account address + */ + inline std::string address() const; + template + inline void address_write(W& writeable_output) const; + + /** + * Gets the chain ID + */ + inline std::string chain_id() const; + template + inline void chain_id_write(W& writeable_output) const; + + /** + * Executes a transaction with the given calls + */ + inline diplomat::result> execute(const CallList& calls) const; + template + inline diplomat::result> execute_write(const CallList& calls, W& writeable_output) const; + + /** + * Gets the nonce for the account + */ + inline diplomat::result> nonce() const; + + inline const diplomat::capi::Account* AsFFI() const; + inline diplomat::capi::Account* AsFFI(); + inline static const Account* FromFFI(const diplomat::capi::Account* ptr); + inline static Account* FromFFI(diplomat::capi::Account* ptr); + inline static void operator delete(void* ptr); +private: + Account() = delete; + Account(const Account&) = delete; + Account(Account&&) noexcept = delete; + Account operator=(const Account&) = delete; + Account operator=(Account&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Account_D_HPP diff --git a/bindings/cpp/Account.hpp b/bindings/cpp/Account.hpp new file mode 100644 index 0000000..d7148d2 --- /dev/null +++ b/bindings/cpp/Account.hpp @@ -0,0 +1,123 @@ +#ifndef Account_HPP +#define Account_HPP + +#include "Account.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "CallList.hpp" +#include "DojoError.hpp" +#include "FieldElement.hpp" +#include "Provider.hpp" +#include "SigningKey.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::Account* Account_new(const diplomat::capi::Provider* provider, const diplomat::capi::SigningKey* signer, const diplomat::capi::FieldElement* address, const diplomat::capi::FieldElement* chain_id); + + void Account_address(const diplomat::capi::Account* self, diplomat::capi::DiplomatWrite* write); + + void Account_chain_id(const diplomat::capi::Account* self, diplomat::capi::DiplomatWrite* write); + + typedef struct Account_execute_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Account_execute_result; + Account_execute_result Account_execute(const diplomat::capi::Account* self, const diplomat::capi::CallList* calls, diplomat::capi::DiplomatWrite* write); + + typedef struct Account_nonce_result {union {uint64_t ok; diplomat::capi::DojoError* err;}; bool is_ok;} Account_nonce_result; + Account_nonce_result Account_nonce(const diplomat::capi::Account* self); + + void Account_destroy(Account* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::unique_ptr Account::new_(const Provider& provider, const SigningKey& signer, const FieldElement& address, const FieldElement& chain_id) { + auto result = diplomat::capi::Account_new(provider.AsFFI(), + signer.AsFFI(), + address.AsFFI(), + chain_id.AsFFI()); + return std::unique_ptr(Account::FromFFI(result)); +} + +inline std::string Account::address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Account_address(this->AsFFI(), + &write); + return output; +} +template +inline void Account::address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Account_address(this->AsFFI(), + &write); +} + +inline std::string Account::chain_id() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Account_chain_id(this->AsFFI(), + &write); + return output; +} +template +inline void Account::chain_id_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Account_chain_id(this->AsFFI(), + &write); +} + +inline diplomat::result> Account::execute(const CallList& calls) const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Account_execute(this->AsFFI(), + calls.AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Account::execute_write(const CallList& calls, W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Account_execute(this->AsFFI(), + calls.AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Account::nonce() const { + auto result = diplomat::capi::Account_nonce(this->AsFFI()); + return result.is_ok ? diplomat::result>(diplomat::Ok(result.ok)) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Account* Account::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Account* Account::AsFFI() { + return reinterpret_cast(this); +} + +inline const Account* Account::FromFFI(const diplomat::capi::Account* ptr) { + return reinterpret_cast(ptr); +} + +inline Account* Account::FromFFI(diplomat::capi::Account* ptr) { + return reinterpret_cast(ptr); +} + +inline void Account::operator delete(void* ptr) { + diplomat::capi::Account_destroy(reinterpret_cast(ptr)); +} + + +#endif // Account_HPP diff --git a/bindings/cpp/Achievement.d.hpp b/bindings/cpp/Achievement.d.hpp new file mode 100644 index 0000000..81dd2d4 --- /dev/null +++ b/bindings/cpp/Achievement.d.hpp @@ -0,0 +1,109 @@ +#ifndef Achievement_D_HPP +#define Achievement_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Achievement; +} // namespace capi +} // namespace + +/** + * Represents an achievement + */ +class Achievement { +public: + + /** + * Gets the achievement ID + */ + inline std::string id() const; + template + inline void id_write(W& writeable_output) const; + + /** + * Gets the world address (hex) + */ + inline std::string world_address() const; + template + inline void world_address_write(W& writeable_output) const; + + /** + * Gets the namespace + */ + inline std::string namespace_() const; + template + inline void namespace__write(W& writeable_output) const; + + /** + * Gets the achievement title + */ + inline std::string title() const; + template + inline void title_write(W& writeable_output) const; + + /** + * Gets the achievement description + */ + inline std::string description() const; + template + inline void description_write(W& writeable_output) const; + + /** + * Gets the hidden flag + */ + inline bool hidden() const; + + /** + * Gets the icon URI + */ + inline std::string icon() const; + template + inline void icon_write(W& writeable_output) const; + + /** + * Gets the points for this achievement + */ + inline uint32_t points() const; + + /** + * Creates an achievement from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the achievement to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Achievement* AsFFI() const; + inline diplomat::capi::Achievement* AsFFI(); + inline static const Achievement* FromFFI(const diplomat::capi::Achievement* ptr); + inline static Achievement* FromFFI(diplomat::capi::Achievement* ptr); + inline static void operator delete(void* ptr); +private: + Achievement() = delete; + Achievement(const Achievement&) = delete; + Achievement(Achievement&&) noexcept = delete; + Achievement operator=(const Achievement&) = delete; + Achievement operator=(Achievement&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Achievement_D_HPP diff --git a/bindings/cpp/Achievement.hpp b/bindings/cpp/Achievement.hpp new file mode 100644 index 0000000..94b8daf --- /dev/null +++ b/bindings/cpp/Achievement.hpp @@ -0,0 +1,185 @@ +#ifndef Achievement_HPP +#define Achievement_HPP + +#include "Achievement.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Achievement_id(const diplomat::capi::Achievement* self, diplomat::capi::DiplomatWrite* write); + + void Achievement_world_address(const diplomat::capi::Achievement* self, diplomat::capi::DiplomatWrite* write); + + void Achievement_namespace(const diplomat::capi::Achievement* self, diplomat::capi::DiplomatWrite* write); + + void Achievement_title(const diplomat::capi::Achievement* self, diplomat::capi::DiplomatWrite* write); + + void Achievement_description(const diplomat::capi::Achievement* self, diplomat::capi::DiplomatWrite* write); + + bool Achievement_hidden(const diplomat::capi::Achievement* self); + + void Achievement_icon(const diplomat::capi::Achievement* self, diplomat::capi::DiplomatWrite* write); + + uint32_t Achievement_points(const diplomat::capi::Achievement* self); + + typedef struct Achievement_from_json_result {union {diplomat::capi::Achievement* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Achievement_from_json_result; + Achievement_from_json_result Achievement_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Achievement_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Achievement_to_json_result; + Achievement_to_json_result Achievement_to_json(const diplomat::capi::Achievement* self, diplomat::capi::DiplomatWrite* write); + + void Achievement_destroy(Achievement* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Achievement::id() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Achievement_id(this->AsFFI(), + &write); + return output; +} +template +inline void Achievement::id_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Achievement_id(this->AsFFI(), + &write); +} + +inline std::string Achievement::world_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Achievement_world_address(this->AsFFI(), + &write); + return output; +} +template +inline void Achievement::world_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Achievement_world_address(this->AsFFI(), + &write); +} + +inline std::string Achievement::namespace_() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Achievement_namespace(this->AsFFI(), + &write); + return output; +} +template +inline void Achievement::namespace__write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Achievement_namespace(this->AsFFI(), + &write); +} + +inline std::string Achievement::title() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Achievement_title(this->AsFFI(), + &write); + return output; +} +template +inline void Achievement::title_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Achievement_title(this->AsFFI(), + &write); +} + +inline std::string Achievement::description() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Achievement_description(this->AsFFI(), + &write); + return output; +} +template +inline void Achievement::description_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Achievement_description(this->AsFFI(), + &write); +} + +inline bool Achievement::hidden() const { + auto result = diplomat::capi::Achievement_hidden(this->AsFFI()); + return result; +} + +inline std::string Achievement::icon() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Achievement_icon(this->AsFFI(), + &write); + return output; +} +template +inline void Achievement::icon_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Achievement_icon(this->AsFFI(), + &write); +} + +inline uint32_t Achievement::points() const { + auto result = diplomat::capi::Achievement_points(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> Achievement::from_json(std::string_view json) { + auto result = diplomat::capi::Achievement_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Achievement::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Achievement::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Achievement_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Achievement::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Achievement_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Achievement* Achievement::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Achievement* Achievement::AsFFI() { + return reinterpret_cast(this); +} + +inline const Achievement* Achievement::FromFFI(const diplomat::capi::Achievement* ptr) { + return reinterpret_cast(ptr); +} + +inline Achievement* Achievement::FromFFI(diplomat::capi::Achievement* ptr) { + return reinterpret_cast(ptr); +} + +inline void Achievement::operator delete(void* ptr) { + diplomat::capi::Achievement_destroy(reinterpret_cast(ptr)); +} + + +#endif // Achievement_HPP diff --git a/bindings/cpp/Activity.d.hpp b/bindings/cpp/Activity.d.hpp new file mode 100644 index 0000000..be1e9e2 --- /dev/null +++ b/bindings/cpp/Activity.d.hpp @@ -0,0 +1,105 @@ +#ifndef Activity_D_HPP +#define Activity_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Activity; +} // namespace capi +} // namespace + +/** + * Represents an activity + */ +class Activity { +public: + + /** + * Gets the activity ID + */ + inline std::string id() const; + template + inline void id_write(W& writeable_output) const; + + /** + * Gets the world address (hex) + */ + inline std::string world_address() const; + template + inline void world_address_write(W& writeable_output) const; + + /** + * Gets the namespace + */ + inline std::string namespace_() const; + template + inline void namespace__write(W& writeable_output) const; + + /** + * Gets the caller address (hex) + */ + inline std::string caller_address() const; + template + inline void caller_address_write(W& writeable_output) const; + + /** + * Gets the session start timestamp + */ + inline uint64_t session_start() const; + + /** + * Gets the session end timestamp + */ + inline uint64_t session_end() const; + + /** + * Gets the action count + */ + inline uint32_t action_count() const; + + /** + * Gets the updated_at timestamp + */ + inline uint64_t updated_at() const; + + /** + * Creates an activity from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the activity to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Activity* AsFFI() const; + inline diplomat::capi::Activity* AsFFI(); + inline static const Activity* FromFFI(const diplomat::capi::Activity* ptr); + inline static Activity* FromFFI(diplomat::capi::Activity* ptr); + inline static void operator delete(void* ptr); +private: + Activity() = delete; + Activity(const Activity&) = delete; + Activity(Activity&&) noexcept = delete; + Activity operator=(const Activity&) = delete; + Activity operator=(Activity&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Activity_D_HPP diff --git a/bindings/cpp/Activity.hpp b/bindings/cpp/Activity.hpp new file mode 100644 index 0000000..9d1baf7 --- /dev/null +++ b/bindings/cpp/Activity.hpp @@ -0,0 +1,167 @@ +#ifndef Activity_HPP +#define Activity_HPP + +#include "Activity.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Activity_id(const diplomat::capi::Activity* self, diplomat::capi::DiplomatWrite* write); + + void Activity_world_address(const diplomat::capi::Activity* self, diplomat::capi::DiplomatWrite* write); + + void Activity_namespace(const diplomat::capi::Activity* self, diplomat::capi::DiplomatWrite* write); + + void Activity_caller_address(const diplomat::capi::Activity* self, diplomat::capi::DiplomatWrite* write); + + uint64_t Activity_session_start(const diplomat::capi::Activity* self); + + uint64_t Activity_session_end(const diplomat::capi::Activity* self); + + uint32_t Activity_action_count(const diplomat::capi::Activity* self); + + uint64_t Activity_updated_at(const diplomat::capi::Activity* self); + + typedef struct Activity_from_json_result {union {diplomat::capi::Activity* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Activity_from_json_result; + Activity_from_json_result Activity_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Activity_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Activity_to_json_result; + Activity_to_json_result Activity_to_json(const diplomat::capi::Activity* self, diplomat::capi::DiplomatWrite* write); + + void Activity_destroy(Activity* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Activity::id() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Activity_id(this->AsFFI(), + &write); + return output; +} +template +inline void Activity::id_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Activity_id(this->AsFFI(), + &write); +} + +inline std::string Activity::world_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Activity_world_address(this->AsFFI(), + &write); + return output; +} +template +inline void Activity::world_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Activity_world_address(this->AsFFI(), + &write); +} + +inline std::string Activity::namespace_() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Activity_namespace(this->AsFFI(), + &write); + return output; +} +template +inline void Activity::namespace__write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Activity_namespace(this->AsFFI(), + &write); +} + +inline std::string Activity::caller_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Activity_caller_address(this->AsFFI(), + &write); + return output; +} +template +inline void Activity::caller_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Activity_caller_address(this->AsFFI(), + &write); +} + +inline uint64_t Activity::session_start() const { + auto result = diplomat::capi::Activity_session_start(this->AsFFI()); + return result; +} + +inline uint64_t Activity::session_end() const { + auto result = diplomat::capi::Activity_session_end(this->AsFFI()); + return result; +} + +inline uint32_t Activity::action_count() const { + auto result = diplomat::capi::Activity_action_count(this->AsFFI()); + return result; +} + +inline uint64_t Activity::updated_at() const { + auto result = diplomat::capi::Activity_updated_at(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> Activity::from_json(std::string_view json) { + auto result = diplomat::capi::Activity_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Activity::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Activity::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Activity_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Activity::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Activity_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Activity* Activity::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Activity* Activity::AsFFI() { + return reinterpret_cast(this); +} + +inline const Activity* Activity::FromFFI(const diplomat::capi::Activity* ptr) { + return reinterpret_cast(ptr); +} + +inline Activity* Activity::FromFFI(diplomat::capi::Activity* ptr) { + return reinterpret_cast(ptr); +} + +inline void Activity::operator delete(void* ptr) { + diplomat::capi::Activity_destroy(reinterpret_cast(ptr)); +} + + +#endif // Activity_HPP diff --git a/bindings/cpp/AggregationEntry.d.hpp b/bindings/cpp/AggregationEntry.d.hpp new file mode 100644 index 0000000..76bf52c --- /dev/null +++ b/bindings/cpp/AggregationEntry.d.hpp @@ -0,0 +1,114 @@ +#ifndef AggregationEntry_D_HPP +#define AggregationEntry_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct AggregationEntry; +} // namespace capi +} // namespace + +/** + * Represents an aggregation entry + */ +class AggregationEntry { +public: + + /** + * Gets the aggregation ID + */ + inline std::string id() const; + template + inline void id_write(W& writeable_output) const; + + /** + * Gets the aggregator ID + */ + inline std::string aggregator_id() const; + template + inline void aggregator_id_write(W& writeable_output) const; + + /** + * Gets the entity ID + */ + inline std::string entity_id() const; + template + inline void entity_id_write(W& writeable_output) const; + + /** + * Gets the model ID + */ + inline std::string model_id() const; + template + inline void model_id_write(W& writeable_output) const; + + /** + * Gets the aggregation value + */ + inline std::string value() const; + template + inline void value_write(W& writeable_output) const; + + /** + * Gets the display value + */ + inline std::string display_value() const; + template + inline void display_value_write(W& writeable_output) const; + + /** + * Gets the position + */ + inline uint64_t position() const; + + /** + * Gets the created_at timestamp + */ + inline uint64_t created_at() const; + + /** + * Gets the updated_at timestamp + */ + inline uint64_t updated_at() const; + + /** + * Creates an aggregation entry from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the aggregation entry to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::AggregationEntry* AsFFI() const; + inline diplomat::capi::AggregationEntry* AsFFI(); + inline static const AggregationEntry* FromFFI(const diplomat::capi::AggregationEntry* ptr); + inline static AggregationEntry* FromFFI(diplomat::capi::AggregationEntry* ptr); + inline static void operator delete(void* ptr); +private: + AggregationEntry() = delete; + AggregationEntry(const AggregationEntry&) = delete; + AggregationEntry(AggregationEntry&&) noexcept = delete; + AggregationEntry operator=(const AggregationEntry&) = delete; + AggregationEntry operator=(AggregationEntry&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // AggregationEntry_D_HPP diff --git a/bindings/cpp/AggregationEntry.hpp b/bindings/cpp/AggregationEntry.hpp new file mode 100644 index 0000000..6ff37c1 --- /dev/null +++ b/bindings/cpp/AggregationEntry.hpp @@ -0,0 +1,192 @@ +#ifndef AggregationEntry_HPP +#define AggregationEntry_HPP + +#include "AggregationEntry.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void AggregationEntry_id(const diplomat::capi::AggregationEntry* self, diplomat::capi::DiplomatWrite* write); + + void AggregationEntry_aggregator_id(const diplomat::capi::AggregationEntry* self, diplomat::capi::DiplomatWrite* write); + + void AggregationEntry_entity_id(const diplomat::capi::AggregationEntry* self, diplomat::capi::DiplomatWrite* write); + + void AggregationEntry_model_id(const diplomat::capi::AggregationEntry* self, diplomat::capi::DiplomatWrite* write); + + void AggregationEntry_value(const diplomat::capi::AggregationEntry* self, diplomat::capi::DiplomatWrite* write); + + void AggregationEntry_display_value(const diplomat::capi::AggregationEntry* self, diplomat::capi::DiplomatWrite* write); + + uint64_t AggregationEntry_position(const diplomat::capi::AggregationEntry* self); + + uint64_t AggregationEntry_created_at(const diplomat::capi::AggregationEntry* self); + + uint64_t AggregationEntry_updated_at(const diplomat::capi::AggregationEntry* self); + + typedef struct AggregationEntry_from_json_result {union {diplomat::capi::AggregationEntry* ok; diplomat::capi::DojoError* err;}; bool is_ok;} AggregationEntry_from_json_result; + AggregationEntry_from_json_result AggregationEntry_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct AggregationEntry_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} AggregationEntry_to_json_result; + AggregationEntry_to_json_result AggregationEntry_to_json(const diplomat::capi::AggregationEntry* self, diplomat::capi::DiplomatWrite* write); + + void AggregationEntry_destroy(AggregationEntry* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string AggregationEntry::id() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::AggregationEntry_id(this->AsFFI(), + &write); + return output; +} +template +inline void AggregationEntry::id_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::AggregationEntry_id(this->AsFFI(), + &write); +} + +inline std::string AggregationEntry::aggregator_id() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::AggregationEntry_aggregator_id(this->AsFFI(), + &write); + return output; +} +template +inline void AggregationEntry::aggregator_id_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::AggregationEntry_aggregator_id(this->AsFFI(), + &write); +} + +inline std::string AggregationEntry::entity_id() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::AggregationEntry_entity_id(this->AsFFI(), + &write); + return output; +} +template +inline void AggregationEntry::entity_id_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::AggregationEntry_entity_id(this->AsFFI(), + &write); +} + +inline std::string AggregationEntry::model_id() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::AggregationEntry_model_id(this->AsFFI(), + &write); + return output; +} +template +inline void AggregationEntry::model_id_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::AggregationEntry_model_id(this->AsFFI(), + &write); +} + +inline std::string AggregationEntry::value() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::AggregationEntry_value(this->AsFFI(), + &write); + return output; +} +template +inline void AggregationEntry::value_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::AggregationEntry_value(this->AsFFI(), + &write); +} + +inline std::string AggregationEntry::display_value() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::AggregationEntry_display_value(this->AsFFI(), + &write); + return output; +} +template +inline void AggregationEntry::display_value_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::AggregationEntry_display_value(this->AsFFI(), + &write); +} + +inline uint64_t AggregationEntry::position() const { + auto result = diplomat::capi::AggregationEntry_position(this->AsFFI()); + return result; +} + +inline uint64_t AggregationEntry::created_at() const { + auto result = diplomat::capi::AggregationEntry_created_at(this->AsFFI()); + return result; +} + +inline uint64_t AggregationEntry::updated_at() const { + auto result = diplomat::capi::AggregationEntry_updated_at(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> AggregationEntry::from_json(std::string_view json) { + auto result = diplomat::capi::AggregationEntry_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(AggregationEntry::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> AggregationEntry::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::AggregationEntry_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> AggregationEntry::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::AggregationEntry_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::AggregationEntry* AggregationEntry::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::AggregationEntry* AggregationEntry::AsFFI() { + return reinterpret_cast(this); +} + +inline const AggregationEntry* AggregationEntry::FromFFI(const diplomat::capi::AggregationEntry* ptr) { + return reinterpret_cast(ptr); +} + +inline AggregationEntry* AggregationEntry::FromFFI(diplomat::capi::AggregationEntry* ptr) { + return reinterpret_cast(ptr); +} + +inline void AggregationEntry::operator delete(void* ptr) { + diplomat::capi::AggregationEntry_destroy(reinterpret_cast(ptr)); +} + + +#endif // AggregationEntry_HPP diff --git a/bindings/cpp/BlockId.d.hpp b/bindings/cpp/BlockId.d.hpp new file mode 100644 index 0000000..0077dbb --- /dev/null +++ b/bindings/cpp/BlockId.d.hpp @@ -0,0 +1,61 @@ +#ifndef BlockId_D_HPP +#define BlockId_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct FieldElement; } +class FieldElement; +class BlockTag; + + +namespace diplomat { +namespace capi { + struct BlockId; +} // namespace capi +} // namespace + +/** + * Block identifier (hash, number, or tag) + */ +class BlockId { +public: + + /** + * Creates a BlockId from a block hash + */ + inline static std::unique_ptr from_hash(const FieldElement& hash); + + /** + * Creates a BlockId from a block number + */ + inline static std::unique_ptr from_number(uint64_t number); + + /** + * Creates a BlockId from a block tag + */ + inline static std::unique_ptr from_tag(BlockTag tag); + + inline const diplomat::capi::BlockId* AsFFI() const; + inline diplomat::capi::BlockId* AsFFI(); + inline static const BlockId* FromFFI(const diplomat::capi::BlockId* ptr); + inline static BlockId* FromFFI(diplomat::capi::BlockId* ptr); + inline static void operator delete(void* ptr); +private: + BlockId() = delete; + BlockId(const BlockId&) = delete; + BlockId(BlockId&&) noexcept = delete; + BlockId operator=(const BlockId&) = delete; + BlockId operator=(BlockId&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // BlockId_D_HPP diff --git a/bindings/cpp/BlockId.hpp b/bindings/cpp/BlockId.hpp new file mode 100644 index 0000000..5ddb814 --- /dev/null +++ b/bindings/cpp/BlockId.hpp @@ -0,0 +1,71 @@ +#ifndef BlockId_HPP +#define BlockId_HPP + +#include "BlockId.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "BlockTag.hpp" +#include "FieldElement.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::BlockId* BlockId_from_hash(const diplomat::capi::FieldElement* hash); + + diplomat::capi::BlockId* BlockId_from_number(uint64_t number); + + diplomat::capi::BlockId* BlockId_from_tag(diplomat::capi::BlockTag tag); + + void BlockId_destroy(BlockId* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::unique_ptr BlockId::from_hash(const FieldElement& hash) { + auto result = diplomat::capi::BlockId_from_hash(hash.AsFFI()); + return std::unique_ptr(BlockId::FromFFI(result)); +} + +inline std::unique_ptr BlockId::from_number(uint64_t number) { + auto result = diplomat::capi::BlockId_from_number(number); + return std::unique_ptr(BlockId::FromFFI(result)); +} + +inline std::unique_ptr BlockId::from_tag(BlockTag tag) { + auto result = diplomat::capi::BlockId_from_tag(tag.AsFFI()); + return std::unique_ptr(BlockId::FromFFI(result)); +} + +inline const diplomat::capi::BlockId* BlockId::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::BlockId* BlockId::AsFFI() { + return reinterpret_cast(this); +} + +inline const BlockId* BlockId::FromFFI(const diplomat::capi::BlockId* ptr) { + return reinterpret_cast(ptr); +} + +inline BlockId* BlockId::FromFFI(diplomat::capi::BlockId* ptr) { + return reinterpret_cast(ptr); +} + +inline void BlockId::operator delete(void* ptr) { + diplomat::capi::BlockId_destroy(reinterpret_cast(ptr)); +} + + +#endif // BlockId_HPP diff --git a/bindings/cpp/BlockTag.d.hpp b/bindings/cpp/BlockTag.d.hpp new file mode 100644 index 0000000..c9c556e --- /dev/null +++ b/bindings/cpp/BlockTag.d.hpp @@ -0,0 +1,51 @@ +#ifndef BlockTag_D_HPP +#define BlockTag_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + enum BlockTag { + BlockTag_Latest = 0, + BlockTag_PreConfirmed = 1, + }; + + typedef struct BlockTag_option {union { BlockTag ok; }; bool is_ok; } BlockTag_option; +} // namespace capi +} // namespace + +/** + * Block tag for identifying specific blocks + */ +class BlockTag { +public: + enum Value { + Latest = 0, + PreConfirmed = 1, + }; + + BlockTag(): value(Value::Latest) {} + + // Implicit conversions between enum and ::Value + constexpr BlockTag(Value v) : value(v) {} + constexpr operator Value() const { return value; } + // Prevent usage as boolean value + explicit operator bool() const = delete; + + inline diplomat::capi::BlockTag AsFFI() const; + inline static BlockTag FromFFI(diplomat::capi::BlockTag c_enum); +private: + Value value; +}; + + +#endif // BlockTag_D_HPP diff --git a/bindings/cpp/BlockTag.hpp b/bindings/cpp/BlockTag.hpp new file mode 100644 index 0000000..cf391a1 --- /dev/null +++ b/bindings/cpp/BlockTag.hpp @@ -0,0 +1,38 @@ +#ifndef BlockTag_HPP +#define BlockTag_HPP + +#include "BlockTag.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::capi::BlockTag BlockTag::AsFFI() const { + return static_cast(value); +} + +inline BlockTag BlockTag::FromFFI(diplomat::capi::BlockTag c_enum) { + switch (c_enum) { + case diplomat::capi::BlockTag_Latest: + case diplomat::capi::BlockTag_PreConfirmed: + return static_cast(c_enum); + default: + std::abort(); + } +} +#endif // BlockTag_HPP diff --git a/bindings/cpp/Call.d.hpp b/bindings/cpp/Call.d.hpp new file mode 100644 index 0000000..eded19e --- /dev/null +++ b/bindings/cpp/Call.d.hpp @@ -0,0 +1,62 @@ +#ifndef Call_D_HPP +#define Call_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; +namespace diplomat::capi { struct FieldElement; } +class FieldElement; + + +namespace diplomat { +namespace capi { + struct Call; +} // namespace capi +} // namespace + +/** + * Represents a Starknet call + */ +class Call { +public: + + /** + * Creates a new Call + */ + inline static std::unique_ptr new_(const FieldElement& to, const FieldElement& selector); + + /** + * Adds a field element to the calldata + */ + inline void push_calldata(const FieldElement& felt); + + /** + * Creates a call from selector name + */ + inline static diplomat::result, std::unique_ptr> new_from_selector_name(const FieldElement& to, std::string_view selector_name); + + inline const diplomat::capi::Call* AsFFI() const; + inline diplomat::capi::Call* AsFFI(); + inline static const Call* FromFFI(const diplomat::capi::Call* ptr); + inline static Call* FromFFI(diplomat::capi::Call* ptr); + inline static void operator delete(void* ptr); +private: + Call() = delete; + Call(const Call&) = delete; + Call(Call&&) noexcept = delete; + Call operator=(const Call&) = delete; + Call operator=(Call&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Call_D_HPP diff --git a/bindings/cpp/Call.hpp b/bindings/cpp/Call.hpp new file mode 100644 index 0000000..8e352ac --- /dev/null +++ b/bindings/cpp/Call.hpp @@ -0,0 +1,74 @@ +#ifndef Call_HPP +#define Call_HPP + +#include "Call.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "FieldElement.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::Call* Call_new(const diplomat::capi::FieldElement* to, const diplomat::capi::FieldElement* selector); + + void Call_push_calldata(diplomat::capi::Call* self, const diplomat::capi::FieldElement* felt); + + typedef struct Call_new_from_selector_name_result {union {diplomat::capi::Call* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Call_new_from_selector_name_result; + Call_new_from_selector_name_result Call_new_from_selector_name(const diplomat::capi::FieldElement* to, diplomat::capi::DiplomatStringView selector_name); + + void Call_destroy(Call* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::unique_ptr Call::new_(const FieldElement& to, const FieldElement& selector) { + auto result = diplomat::capi::Call_new(to.AsFFI(), + selector.AsFFI()); + return std::unique_ptr(Call::FromFFI(result)); +} + +inline void Call::push_calldata(const FieldElement& felt) { + diplomat::capi::Call_push_calldata(this->AsFFI(), + felt.AsFFI()); +} + +inline diplomat::result, std::unique_ptr> Call::new_from_selector_name(const FieldElement& to, std::string_view selector_name) { + auto result = diplomat::capi::Call_new_from_selector_name(to.AsFFI(), + {selector_name.data(), selector_name.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Call::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Call* Call::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Call* Call::AsFFI() { + return reinterpret_cast(this); +} + +inline const Call* Call::FromFFI(const diplomat::capi::Call* ptr) { + return reinterpret_cast(ptr); +} + +inline Call* Call::FromFFI(diplomat::capi::Call* ptr) { + return reinterpret_cast(ptr); +} + +inline void Call::operator delete(void* ptr) { + diplomat::capi::Call_destroy(reinterpret_cast(ptr)); +} + + +#endif // Call_HPP diff --git a/bindings/cpp/CallList.d.hpp b/bindings/cpp/CallList.d.hpp new file mode 100644 index 0000000..fbf0463 --- /dev/null +++ b/bindings/cpp/CallList.d.hpp @@ -0,0 +1,60 @@ +#ifndef CallList_D_HPP +#define CallList_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct Call; } +class Call; + + +namespace diplomat { +namespace capi { + struct CallList; +} // namespace capi +} // namespace + +/** + * List of calls for batch transactions + */ +class CallList { +public: + + /** + * Creates a new empty call list + */ + inline static std::unique_ptr new_(); + + /** + * Adds a call to the list + */ + inline void add_call(const Call& call); + + /** + * Returns the number of calls in the list + */ + inline size_t len() const; + + inline const diplomat::capi::CallList* AsFFI() const; + inline diplomat::capi::CallList* AsFFI(); + inline static const CallList* FromFFI(const diplomat::capi::CallList* ptr); + inline static CallList* FromFFI(diplomat::capi::CallList* ptr); + inline static void operator delete(void* ptr); +private: + CallList() = delete; + CallList(const CallList&) = delete; + CallList(CallList&&) noexcept = delete; + CallList operator=(const CallList&) = delete; + CallList operator=(CallList&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // CallList_D_HPP diff --git a/bindings/cpp/CallList.hpp b/bindings/cpp/CallList.hpp new file mode 100644 index 0000000..3da34b8 --- /dev/null +++ b/bindings/cpp/CallList.hpp @@ -0,0 +1,70 @@ +#ifndef CallList_HPP +#define CallList_HPP + +#include "CallList.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Call.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::CallList* CallList_new(void); + + void CallList_add_call(diplomat::capi::CallList* self, const diplomat::capi::Call* call); + + size_t CallList_len(const diplomat::capi::CallList* self); + + void CallList_destroy(CallList* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::unique_ptr CallList::new_() { + auto result = diplomat::capi::CallList_new(); + return std::unique_ptr(CallList::FromFFI(result)); +} + +inline void CallList::add_call(const Call& call) { + diplomat::capi::CallList_add_call(this->AsFFI(), + call.AsFFI()); +} + +inline size_t CallList::len() const { + auto result = diplomat::capi::CallList_len(this->AsFFI()); + return result; +} + +inline const diplomat::capi::CallList* CallList::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::CallList* CallList::AsFFI() { + return reinterpret_cast(this); +} + +inline const CallList* CallList::FromFFI(const diplomat::capi::CallList* ptr) { + return reinterpret_cast(ptr); +} + +inline CallList* CallList::FromFFI(diplomat::capi::CallList* ptr) { + return reinterpret_cast(ptr); +} + +inline void CallList::operator delete(void* ptr) { + diplomat::capi::CallList_destroy(reinterpret_cast(ptr)); +} + + +#endif // CallList_HPP diff --git a/bindings/cpp/CallType.d.hpp b/bindings/cpp/CallType.d.hpp new file mode 100644 index 0000000..df810c9 --- /dev/null +++ b/bindings/cpp/CallType.d.hpp @@ -0,0 +1,51 @@ +#ifndef CallType_D_HPP +#define CallType_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + enum CallType { + CallType_Execute = 0, + CallType_ExecuteFromOutside = 1, + }; + + typedef struct CallType_option {union { CallType ok; }; bool is_ok; } CallType_option; +} // namespace capi +} // namespace + +/** + * Type of call in a transaction + */ +class CallType { +public: + enum Value { + Execute = 0, + ExecuteFromOutside = 1, + }; + + CallType(): value(Value::Execute) {} + + // Implicit conversions between enum and ::Value + constexpr CallType(Value v) : value(v) {} + constexpr operator Value() const { return value; } + // Prevent usage as boolean value + explicit operator bool() const = delete; + + inline diplomat::capi::CallType AsFFI() const; + inline static CallType FromFFI(diplomat::capi::CallType c_enum); +private: + Value value; +}; + + +#endif // CallType_D_HPP diff --git a/bindings/cpp/CallType.hpp b/bindings/cpp/CallType.hpp new file mode 100644 index 0000000..7bd9bbb --- /dev/null +++ b/bindings/cpp/CallType.hpp @@ -0,0 +1,38 @@ +#ifndef CallType_HPP +#define CallType_HPP + +#include "CallType.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::capi::CallType CallType::AsFFI() const { + return static_cast(value); +} + +inline CallType CallType::FromFFI(diplomat::capi::CallType c_enum) { + switch (c_enum) { + case diplomat::capi::CallType_Execute: + case diplomat::capi::CallType_ExecuteFromOutside: + return static_cast(c_enum); + default: + std::abort(); + } +} +#endif // CallType_HPP diff --git a/bindings/cpp/Clause.d.hpp b/bindings/cpp/Clause.d.hpp new file mode 100644 index 0000000..b79663d --- /dev/null +++ b/bindings/cpp/Clause.d.hpp @@ -0,0 +1,42 @@ +#ifndef Clause_D_HPP +#define Clause_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + struct Clause; +} // namespace capi +} // namespace + +/** + * Query clause for filtering entities + */ +class Clause { +public: + + inline const diplomat::capi::Clause* AsFFI() const; + inline diplomat::capi::Clause* AsFFI(); + inline static const Clause* FromFFI(const diplomat::capi::Clause* ptr); + inline static Clause* FromFFI(diplomat::capi::Clause* ptr); + inline static void operator delete(void* ptr); +private: + Clause() = delete; + Clause(const Clause&) = delete; + Clause(Clause&&) noexcept = delete; + Clause operator=(const Clause&) = delete; + Clause operator=(Clause&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Clause_D_HPP diff --git a/bindings/cpp/Clause.hpp b/bindings/cpp/Clause.hpp new file mode 100644 index 0000000..62afa1d --- /dev/null +++ b/bindings/cpp/Clause.hpp @@ -0,0 +1,48 @@ +#ifndef Clause_HPP +#define Clause_HPP + +#include "Clause.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Clause_destroy(Clause* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline const diplomat::capi::Clause* Clause::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Clause* Clause::AsFFI() { + return reinterpret_cast(this); +} + +inline const Clause* Clause::FromFFI(const diplomat::capi::Clause* ptr) { + return reinterpret_cast(ptr); +} + +inline Clause* Clause::FromFFI(diplomat::capi::Clause* ptr) { + return reinterpret_cast(ptr); +} + +inline void Clause::operator delete(void* ptr) { + diplomat::capi::Clause_destroy(reinterpret_cast(ptr)); +} + + +#endif // Clause_HPP diff --git a/bindings/cpp/ComparisonOperator.d.hpp b/bindings/cpp/ComparisonOperator.d.hpp new file mode 100644 index 0000000..d96a07e --- /dev/null +++ b/bindings/cpp/ComparisonOperator.d.hpp @@ -0,0 +1,75 @@ +#ifndef ComparisonOperator_D_HPP +#define ComparisonOperator_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + enum ComparisonOperator { + ComparisonOperator_Eq = 0, + ComparisonOperator_Neq = 1, + ComparisonOperator_Gt = 2, + ComparisonOperator_Gte = 3, + ComparisonOperator_Lt = 4, + ComparisonOperator_Lte = 5, + ComparisonOperator_In = 6, + ComparisonOperator_NotIn = 7, + ComparisonOperator_Contains = 8, + ComparisonOperator_ContainsAll = 9, + ComparisonOperator_ContainsAny = 10, + ComparisonOperator_ArrayLengthEq = 11, + ComparisonOperator_ArrayLengthGt = 12, + ComparisonOperator_ArrayLengthLt = 13, + }; + + typedef struct ComparisonOperator_option {union { ComparisonOperator ok; }; bool is_ok; } ComparisonOperator_option; +} // namespace capi +} // namespace + +/** + * Comparison operators for member clauses + */ +class ComparisonOperator { +public: + enum Value { + Eq = 0, + Neq = 1, + Gt = 2, + Gte = 3, + Lt = 4, + Lte = 5, + In = 6, + NotIn = 7, + Contains = 8, + ContainsAll = 9, + ContainsAny = 10, + ArrayLengthEq = 11, + ArrayLengthGt = 12, + ArrayLengthLt = 13, + }; + + ComparisonOperator(): value(Value::Eq) {} + + // Implicit conversions between enum and ::Value + constexpr ComparisonOperator(Value v) : value(v) {} + constexpr operator Value() const { return value; } + // Prevent usage as boolean value + explicit operator bool() const = delete; + + inline diplomat::capi::ComparisonOperator AsFFI() const; + inline static ComparisonOperator FromFFI(diplomat::capi::ComparisonOperator c_enum); +private: + Value value; +}; + + +#endif // ComparisonOperator_D_HPP diff --git a/bindings/cpp/ComparisonOperator.hpp b/bindings/cpp/ComparisonOperator.hpp new file mode 100644 index 0000000..b9dcff8 --- /dev/null +++ b/bindings/cpp/ComparisonOperator.hpp @@ -0,0 +1,50 @@ +#ifndef ComparisonOperator_HPP +#define ComparisonOperator_HPP + +#include "ComparisonOperator.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::capi::ComparisonOperator ComparisonOperator::AsFFI() const { + return static_cast(value); +} + +inline ComparisonOperator ComparisonOperator::FromFFI(diplomat::capi::ComparisonOperator c_enum) { + switch (c_enum) { + case diplomat::capi::ComparisonOperator_Eq: + case diplomat::capi::ComparisonOperator_Neq: + case diplomat::capi::ComparisonOperator_Gt: + case diplomat::capi::ComparisonOperator_Gte: + case diplomat::capi::ComparisonOperator_Lt: + case diplomat::capi::ComparisonOperator_Lte: + case diplomat::capi::ComparisonOperator_In: + case diplomat::capi::ComparisonOperator_NotIn: + case diplomat::capi::ComparisonOperator_Contains: + case diplomat::capi::ComparisonOperator_ContainsAll: + case diplomat::capi::ComparisonOperator_ContainsAny: + case diplomat::capi::ComparisonOperator_ArrayLengthEq: + case diplomat::capi::ComparisonOperator_ArrayLengthGt: + case diplomat::capi::ComparisonOperator_ArrayLengthLt: + return static_cast(c_enum); + default: + std::abort(); + } +} +#endif // ComparisonOperator_HPP diff --git a/bindings/cpp/Contract.d.hpp b/bindings/cpp/Contract.d.hpp new file mode 100644 index 0000000..cdbc605 --- /dev/null +++ b/bindings/cpp/Contract.d.hpp @@ -0,0 +1,91 @@ +#ifndef Contract_D_HPP +#define Contract_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Contract; +} // namespace capi +} // namespace + +/** + * Represents a contract + */ +class Contract { +public: + + /** + * Gets the contract address (hex) + */ + inline std::string contract_address() const; + template + inline void contract_address_write(W& writeable_output) const; + + /** + * Gets the contract type as string + */ + inline std::string contract_type() const; + template + inline void contract_type_write(W& writeable_output) const; + + /** + * Gets the head block number (if any) + */ + inline uint64_t head() const; + + /** + * Gets the TPS (transactions per second) if available + */ + inline uint64_t tps() const; + + /** + * Gets the created_at timestamp + */ + inline uint64_t created_at() const; + + /** + * Gets the updated_at timestamp + */ + inline uint64_t updated_at() const; + + /** + * Creates a contract from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the contract to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Contract* AsFFI() const; + inline diplomat::capi::Contract* AsFFI(); + inline static const Contract* FromFFI(const diplomat::capi::Contract* ptr); + inline static Contract* FromFFI(diplomat::capi::Contract* ptr); + inline static void operator delete(void* ptr); +private: + Contract() = delete; + Contract(const Contract&) = delete; + Contract(Contract&&) noexcept = delete; + Contract operator=(const Contract&) = delete; + Contract operator=(Contract&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Contract_D_HPP diff --git a/bindings/cpp/Contract.hpp b/bindings/cpp/Contract.hpp new file mode 100644 index 0000000..ff83e8d --- /dev/null +++ b/bindings/cpp/Contract.hpp @@ -0,0 +1,135 @@ +#ifndef Contract_HPP +#define Contract_HPP + +#include "Contract.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Contract_contract_address(const diplomat::capi::Contract* self, diplomat::capi::DiplomatWrite* write); + + void Contract_contract_type(const diplomat::capi::Contract* self, diplomat::capi::DiplomatWrite* write); + + uint64_t Contract_head(const diplomat::capi::Contract* self); + + uint64_t Contract_tps(const diplomat::capi::Contract* self); + + uint64_t Contract_created_at(const diplomat::capi::Contract* self); + + uint64_t Contract_updated_at(const diplomat::capi::Contract* self); + + typedef struct Contract_from_json_result {union {diplomat::capi::Contract* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Contract_from_json_result; + Contract_from_json_result Contract_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Contract_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Contract_to_json_result; + Contract_to_json_result Contract_to_json(const diplomat::capi::Contract* self, diplomat::capi::DiplomatWrite* write); + + void Contract_destroy(Contract* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Contract::contract_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Contract_contract_address(this->AsFFI(), + &write); + return output; +} +template +inline void Contract::contract_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Contract_contract_address(this->AsFFI(), + &write); +} + +inline std::string Contract::contract_type() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Contract_contract_type(this->AsFFI(), + &write); + return output; +} +template +inline void Contract::contract_type_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Contract_contract_type(this->AsFFI(), + &write); +} + +inline uint64_t Contract::head() const { + auto result = diplomat::capi::Contract_head(this->AsFFI()); + return result; +} + +inline uint64_t Contract::tps() const { + auto result = diplomat::capi::Contract_tps(this->AsFFI()); + return result; +} + +inline uint64_t Contract::created_at() const { + auto result = diplomat::capi::Contract_created_at(this->AsFFI()); + return result; +} + +inline uint64_t Contract::updated_at() const { + auto result = diplomat::capi::Contract_updated_at(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> Contract::from_json(std::string_view json) { + auto result = diplomat::capi::Contract_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Contract::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Contract::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Contract_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Contract::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Contract_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Contract* Contract::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Contract* Contract::AsFFI() { + return reinterpret_cast(this); +} + +inline const Contract* Contract::FromFFI(const diplomat::capi::Contract* ptr) { + return reinterpret_cast(ptr); +} + +inline Contract* Contract::FromFFI(diplomat::capi::Contract* ptr) { + return reinterpret_cast(ptr); +} + +inline void Contract::operator delete(void* ptr) { + diplomat::capi::Contract_destroy(reinterpret_cast(ptr)); +} + + +#endif // Contract_HPP diff --git a/bindings/cpp/ContractType.d.hpp b/bindings/cpp/ContractType.d.hpp new file mode 100644 index 0000000..f84fecc --- /dev/null +++ b/bindings/cpp/ContractType.d.hpp @@ -0,0 +1,59 @@ +#ifndef ContractType_D_HPP +#define ContractType_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + enum ContractType { + ContractType_WORLD = 0, + ContractType_ERC20 = 1, + ContractType_ERC721 = 2, + ContractType_ERC1155 = 3, + ContractType_UDC = 4, + ContractType_OTHER = 5, + }; + + typedef struct ContractType_option {union { ContractType ok; }; bool is_ok; } ContractType_option; +} // namespace capi +} // namespace + +/** + * Type of contract + */ +class ContractType { +public: + enum Value { + WORLD = 0, + ERC20 = 1, + ERC721 = 2, + ERC1155 = 3, + UDC = 4, + OTHER = 5, + }; + + ContractType(): value(Value::WORLD) {} + + // Implicit conversions between enum and ::Value + constexpr ContractType(Value v) : value(v) {} + constexpr operator Value() const { return value; } + // Prevent usage as boolean value + explicit operator bool() const = delete; + + inline diplomat::capi::ContractType AsFFI() const; + inline static ContractType FromFFI(diplomat::capi::ContractType c_enum); +private: + Value value; +}; + + +#endif // ContractType_D_HPP diff --git a/bindings/cpp/ContractType.hpp b/bindings/cpp/ContractType.hpp new file mode 100644 index 0000000..e927c31 --- /dev/null +++ b/bindings/cpp/ContractType.hpp @@ -0,0 +1,42 @@ +#ifndef ContractType_HPP +#define ContractType_HPP + +#include "ContractType.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::capi::ContractType ContractType::AsFFI() const { + return static_cast(value); +} + +inline ContractType ContractType::FromFFI(diplomat::capi::ContractType c_enum) { + switch (c_enum) { + case diplomat::capi::ContractType_WORLD: + case diplomat::capi::ContractType_ERC20: + case diplomat::capi::ContractType_ERC721: + case diplomat::capi::ContractType_ERC1155: + case diplomat::capi::ContractType_UDC: + case diplomat::capi::ContractType_OTHER: + return static_cast(c_enum); + default: + std::abort(); + } +} +#endif // ContractType_HPP diff --git a/bindings/cpp/DojoError.d.hpp b/bindings/cpp/DojoError.d.hpp new file mode 100644 index 0000000..8ac50c0 --- /dev/null +++ b/bindings/cpp/DojoError.d.hpp @@ -0,0 +1,58 @@ +#ifndef DojoError_D_HPP +#define DojoError_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +class ErrorType; + + +namespace diplomat { +namespace capi { + struct DojoError; +} // namespace capi +} // namespace + +/** + * Error types for Dojo operations + */ +class DojoError { +public: + + inline static diplomat::result, diplomat::Utf8Error> new_(ErrorType error_type, std::string_view message); + + /** + * Gets the error message + */ + inline std::string message() const; + template + inline void message_write(W& writeable_output) const; + + /** + * Gets the error type + */ + inline ErrorType error_type() const; + + inline const diplomat::capi::DojoError* AsFFI() const; + inline diplomat::capi::DojoError* AsFFI(); + inline static const DojoError* FromFFI(const diplomat::capi::DojoError* ptr); + inline static DojoError* FromFFI(diplomat::capi::DojoError* ptr); + inline static void operator delete(void* ptr); +private: + DojoError() = delete; + DojoError(const DojoError&) = delete; + DojoError(DojoError&&) noexcept = delete; + DojoError operator=(const DojoError&) = delete; + DojoError operator=(DojoError&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // DojoError_D_HPP diff --git a/bindings/cpp/DojoError.hpp b/bindings/cpp/DojoError.hpp new file mode 100644 index 0000000..374e5e5 --- /dev/null +++ b/bindings/cpp/DojoError.hpp @@ -0,0 +1,83 @@ +#ifndef DojoError_HPP +#define DojoError_HPP + +#include "DojoError.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "ErrorType.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::DojoError* DojoError_new(diplomat::capi::ErrorType error_type, diplomat::capi::DiplomatStringView message); + + void DojoError_message(const diplomat::capi::DojoError* self, diplomat::capi::DiplomatWrite* write); + + diplomat::capi::ErrorType DojoError_error_type(const diplomat::capi::DojoError* self); + + void DojoError_destroy(DojoError* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::result, diplomat::Utf8Error> DojoError::new_(ErrorType error_type, std::string_view message) { + if (!diplomat::capi::diplomat_is_str(message.data(), message.size())) { + return diplomat::Err(); + } + auto result = diplomat::capi::DojoError_new(error_type.AsFFI(), + {message.data(), message.size()}); + return diplomat::Ok>(std::unique_ptr(DojoError::FromFFI(result))); +} + +inline std::string DojoError::message() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::DojoError_message(this->AsFFI(), + &write); + return output; +} +template +inline void DojoError::message_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::DojoError_message(this->AsFFI(), + &write); +} + +inline ErrorType DojoError::error_type() const { + auto result = diplomat::capi::DojoError_error_type(this->AsFFI()); + return ErrorType::FromFFI(result); +} + +inline const diplomat::capi::DojoError* DojoError::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::DojoError* DojoError::AsFFI() { + return reinterpret_cast(this); +} + +inline const DojoError* DojoError::FromFFI(const diplomat::capi::DojoError* ptr) { + return reinterpret_cast(ptr); +} + +inline DojoError* DojoError::FromFFI(diplomat::capi::DojoError* ptr) { + return reinterpret_cast(ptr); +} + +inline void DojoError::operator delete(void* ptr) { + diplomat::capi::DojoError_destroy(reinterpret_cast(ptr)); +} + + +#endif // DojoError_HPP diff --git a/bindings/cpp/Entity.d.hpp b/bindings/cpp/Entity.d.hpp new file mode 100644 index 0000000..65ac8a5 --- /dev/null +++ b/bindings/cpp/Entity.d.hpp @@ -0,0 +1,84 @@ +#ifndef Entity_D_HPP +#define Entity_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Entity; +} // namespace capi +} // namespace + +/** + * Represents a Dojo entity + */ +class Entity { +public: + + /** + * Gets the hashed keys (hex) + */ + inline std::string hashed_keys() const; + template + inline void hashed_keys_write(W& writeable_output) const; + + /** + * Gets the number of models in this entity + */ + inline uint32_t models_count() const; + + /** + * Gets the created_at timestamp + */ + inline uint64_t created_at() const; + + /** + * Gets the updated_at timestamp + */ + inline uint64_t updated_at() const; + + /** + * Gets the executed_at timestamp + */ + inline uint64_t executed_at() const; + + /** + * Creates a new entity from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the entity to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Entity* AsFFI() const; + inline diplomat::capi::Entity* AsFFI(); + inline static const Entity* FromFFI(const diplomat::capi::Entity* ptr); + inline static Entity* FromFFI(diplomat::capi::Entity* ptr); + inline static void operator delete(void* ptr); +private: + Entity() = delete; + Entity(const Entity&) = delete; + Entity(Entity&&) noexcept = delete; + Entity operator=(const Entity&) = delete; + Entity operator=(Entity&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Entity_D_HPP diff --git a/bindings/cpp/Entity.hpp b/bindings/cpp/Entity.hpp new file mode 100644 index 0000000..c4a84c8 --- /dev/null +++ b/bindings/cpp/Entity.hpp @@ -0,0 +1,119 @@ +#ifndef Entity_HPP +#define Entity_HPP + +#include "Entity.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Entity_hashed_keys(const diplomat::capi::Entity* self, diplomat::capi::DiplomatWrite* write); + + uint32_t Entity_models_count(const diplomat::capi::Entity* self); + + uint64_t Entity_created_at(const diplomat::capi::Entity* self); + + uint64_t Entity_updated_at(const diplomat::capi::Entity* self); + + uint64_t Entity_executed_at(const diplomat::capi::Entity* self); + + typedef struct Entity_from_json_result {union {diplomat::capi::Entity* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Entity_from_json_result; + Entity_from_json_result Entity_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Entity_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Entity_to_json_result; + Entity_to_json_result Entity_to_json(const diplomat::capi::Entity* self, diplomat::capi::DiplomatWrite* write); + + void Entity_destroy(Entity* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Entity::hashed_keys() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Entity_hashed_keys(this->AsFFI(), + &write); + return output; +} +template +inline void Entity::hashed_keys_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Entity_hashed_keys(this->AsFFI(), + &write); +} + +inline uint32_t Entity::models_count() const { + auto result = diplomat::capi::Entity_models_count(this->AsFFI()); + return result; +} + +inline uint64_t Entity::created_at() const { + auto result = diplomat::capi::Entity_created_at(this->AsFFI()); + return result; +} + +inline uint64_t Entity::updated_at() const { + auto result = diplomat::capi::Entity_updated_at(this->AsFFI()); + return result; +} + +inline uint64_t Entity::executed_at() const { + auto result = diplomat::capi::Entity_executed_at(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> Entity::from_json(std::string_view json) { + auto result = diplomat::capi::Entity_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Entity::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Entity::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Entity_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Entity::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Entity_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Entity* Entity::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Entity* Entity::AsFFI() { + return reinterpret_cast(this); +} + +inline const Entity* Entity::FromFFI(const diplomat::capi::Entity* ptr) { + return reinterpret_cast(ptr); +} + +inline Entity* Entity::FromFFI(diplomat::capi::Entity* ptr) { + return reinterpret_cast(ptr); +} + +inline void Entity::operator delete(void* ptr) { + diplomat::capi::Entity_destroy(reinterpret_cast(ptr)); +} + + +#endif // Entity_HPP diff --git a/bindings/cpp/EntityQuery.d.hpp b/bindings/cpp/EntityQuery.d.hpp new file mode 100644 index 0000000..4875b4d --- /dev/null +++ b/bindings/cpp/EntityQuery.d.hpp @@ -0,0 +1,57 @@ +#ifndef EntityQuery_D_HPP +#define EntityQuery_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + struct EntityQuery; +} // namespace capi +} // namespace + +/** + * Entity query for retrieving entities from Torii + */ +class EntityQuery { +public: + + /** + * Creates a new entity query + */ + inline static std::unique_ptr new_(); + + /** + * Sets the limit for the query + */ + inline void set_limit(uint32_t limit); + + /** + * Sets the offset for the query + */ + inline void set_offset(uint32_t offset); + + inline const diplomat::capi::EntityQuery* AsFFI() const; + inline diplomat::capi::EntityQuery* AsFFI(); + inline static const EntityQuery* FromFFI(const diplomat::capi::EntityQuery* ptr); + inline static EntityQuery* FromFFI(diplomat::capi::EntityQuery* ptr); + inline static void operator delete(void* ptr); +private: + EntityQuery() = delete; + EntityQuery(const EntityQuery&) = delete; + EntityQuery(EntityQuery&&) noexcept = delete; + EntityQuery operator=(const EntityQuery&) = delete; + EntityQuery operator=(EntityQuery&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // EntityQuery_D_HPP diff --git a/bindings/cpp/EntityQuery.hpp b/bindings/cpp/EntityQuery.hpp new file mode 100644 index 0000000..e2fb920 --- /dev/null +++ b/bindings/cpp/EntityQuery.hpp @@ -0,0 +1,69 @@ +#ifndef EntityQuery_HPP +#define EntityQuery_HPP + +#include "EntityQuery.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::EntityQuery* EntityQuery_new(void); + + void EntityQuery_set_limit(diplomat::capi::EntityQuery* self, uint32_t limit); + + void EntityQuery_set_offset(diplomat::capi::EntityQuery* self, uint32_t offset); + + void EntityQuery_destroy(EntityQuery* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::unique_ptr EntityQuery::new_() { + auto result = diplomat::capi::EntityQuery_new(); + return std::unique_ptr(EntityQuery::FromFFI(result)); +} + +inline void EntityQuery::set_limit(uint32_t limit) { + diplomat::capi::EntityQuery_set_limit(this->AsFFI(), + limit); +} + +inline void EntityQuery::set_offset(uint32_t offset) { + diplomat::capi::EntityQuery_set_offset(this->AsFFI(), + offset); +} + +inline const diplomat::capi::EntityQuery* EntityQuery::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::EntityQuery* EntityQuery::AsFFI() { + return reinterpret_cast(this); +} + +inline const EntityQuery* EntityQuery::FromFFI(const diplomat::capi::EntityQuery* ptr) { + return reinterpret_cast(ptr); +} + +inline EntityQuery* EntityQuery::FromFFI(diplomat::capi::EntityQuery* ptr) { + return reinterpret_cast(ptr); +} + +inline void EntityQuery::operator delete(void* ptr) { + diplomat::capi::EntityQuery_destroy(reinterpret_cast(ptr)); +} + + +#endif // EntityQuery_HPP diff --git a/bindings/cpp/Enum.d.hpp b/bindings/cpp/Enum.d.hpp new file mode 100644 index 0000000..561d647 --- /dev/null +++ b/bindings/cpp/Enum.d.hpp @@ -0,0 +1,74 @@ +#ifndef Enum_D_HPP +#define Enum_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Enum; +} // namespace capi +} // namespace + +/** + * Represents a Dojo enum + */ +class Enum { +public: + + /** + * Gets the enum name + */ + inline std::string name() const; + template + inline void name_write(W& writeable_output) const; + + /** + * Gets the current option (selected variant) index + */ + inline uint8_t option() const; + + /** + * Gets the number of options (variants) + */ + inline uint32_t options_count() const; + + /** + * Creates a new enum from JSON schema + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the enum to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Enum* AsFFI() const; + inline diplomat::capi::Enum* AsFFI(); + inline static const Enum* FromFFI(const diplomat::capi::Enum* ptr); + inline static Enum* FromFFI(diplomat::capi::Enum* ptr); + inline static void operator delete(void* ptr); +private: + Enum() = delete; + Enum(const Enum&) = delete; + Enum(Enum&&) noexcept = delete; + Enum operator=(const Enum&) = delete; + Enum operator=(Enum&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Enum_D_HPP diff --git a/bindings/cpp/Enum.hpp b/bindings/cpp/Enum.hpp new file mode 100644 index 0000000..4238595 --- /dev/null +++ b/bindings/cpp/Enum.hpp @@ -0,0 +1,105 @@ +#ifndef Enum_HPP +#define Enum_HPP + +#include "Enum.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Enum_name(const diplomat::capi::Enum* self, diplomat::capi::DiplomatWrite* write); + + uint8_t Enum_option(const diplomat::capi::Enum* self); + + uint32_t Enum_options_count(const diplomat::capi::Enum* self); + + typedef struct Enum_from_json_result {union {diplomat::capi::Enum* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Enum_from_json_result; + Enum_from_json_result Enum_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Enum_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Enum_to_json_result; + Enum_to_json_result Enum_to_json(const diplomat::capi::Enum* self, diplomat::capi::DiplomatWrite* write); + + void Enum_destroy(Enum* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Enum::name() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Enum_name(this->AsFFI(), + &write); + return output; +} +template +inline void Enum::name_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Enum_name(this->AsFFI(), + &write); +} + +inline uint8_t Enum::option() const { + auto result = diplomat::capi::Enum_option(this->AsFFI()); + return result; +} + +inline uint32_t Enum::options_count() const { + auto result = diplomat::capi::Enum_options_count(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> Enum::from_json(std::string_view json) { + auto result = diplomat::capi::Enum_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Enum::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Enum::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Enum_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Enum::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Enum_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Enum* Enum::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Enum* Enum::AsFFI() { + return reinterpret_cast(this); +} + +inline const Enum* Enum::FromFFI(const diplomat::capi::Enum* ptr) { + return reinterpret_cast(ptr); +} + +inline Enum* Enum::FromFFI(diplomat::capi::Enum* ptr) { + return reinterpret_cast(ptr); +} + +inline void Enum::operator delete(void* ptr) { + diplomat::capi::Enum_destroy(reinterpret_cast(ptr)); +} + + +#endif // Enum_HPP diff --git a/bindings/cpp/EnumOption.d.hpp b/bindings/cpp/EnumOption.d.hpp new file mode 100644 index 0000000..ea9b5a4 --- /dev/null +++ b/bindings/cpp/EnumOption.d.hpp @@ -0,0 +1,49 @@ +#ifndef EnumOption_D_HPP +#define EnumOption_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + struct EnumOption; +} // namespace capi +} // namespace + +/** + * Represents a Dojo enum option (variant) + */ +class EnumOption { +public: + + /** + * Gets the option name + */ + inline std::string name() const; + template + inline void name_write(W& writeable_output) const; + + inline const diplomat::capi::EnumOption* AsFFI() const; + inline diplomat::capi::EnumOption* AsFFI(); + inline static const EnumOption* FromFFI(const diplomat::capi::EnumOption* ptr); + inline static EnumOption* FromFFI(diplomat::capi::EnumOption* ptr); + inline static void operator delete(void* ptr); +private: + EnumOption() = delete; + EnumOption(const EnumOption&) = delete; + EnumOption(EnumOption&&) noexcept = delete; + EnumOption operator=(const EnumOption&) = delete; + EnumOption operator=(EnumOption&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // EnumOption_D_HPP diff --git a/bindings/cpp/EnumOption.hpp b/bindings/cpp/EnumOption.hpp new file mode 100644 index 0000000..fd26266 --- /dev/null +++ b/bindings/cpp/EnumOption.hpp @@ -0,0 +1,64 @@ +#ifndef EnumOption_HPP +#define EnumOption_HPP + +#include "EnumOption.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void EnumOption_name(const diplomat::capi::EnumOption* self, diplomat::capi::DiplomatWrite* write); + + void EnumOption_destroy(EnumOption* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string EnumOption::name() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::EnumOption_name(this->AsFFI(), + &write); + return output; +} +template +inline void EnumOption::name_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::EnumOption_name(this->AsFFI(), + &write); +} + +inline const diplomat::capi::EnumOption* EnumOption::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::EnumOption* EnumOption::AsFFI() { + return reinterpret_cast(this); +} + +inline const EnumOption* EnumOption::FromFFI(const diplomat::capi::EnumOption* ptr) { + return reinterpret_cast(ptr); +} + +inline EnumOption* EnumOption::FromFFI(diplomat::capi::EnumOption* ptr) { + return reinterpret_cast(ptr); +} + +inline void EnumOption::operator delete(void* ptr) { + diplomat::capi::EnumOption_destroy(reinterpret_cast(ptr)); +} + + +#endif // EnumOption_HPP diff --git a/bindings/cpp/ErrorType.d.hpp b/bindings/cpp/ErrorType.d.hpp new file mode 100644 index 0000000..07b09c7 --- /dev/null +++ b/bindings/cpp/ErrorType.d.hpp @@ -0,0 +1,70 @@ +#ifndef ErrorType_D_HPP +#define ErrorType_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + enum ErrorType { + ErrorType_ClientError = 0, + ErrorType_ParseError = 1, + ErrorType_EntityError = 2, + ErrorType_QueryError = 3, + ErrorType_SubscriptionError = 4, + ErrorType_TransactionError = 5, + ErrorType_AccountError = 6, + ErrorType_SigningError = 7, + ErrorType_ProviderError = 8, + ErrorType_StorageError = 9, + ErrorType_ControllerError = 10, + ErrorType_InvalidInput = 11, + ErrorType_RuntimeError = 12, + }; + + typedef struct ErrorType_option {union { ErrorType ok; }; bool is_ok; } ErrorType_option; +} // namespace capi +} // namespace + +class ErrorType { +public: + enum Value { + ClientError = 0, + ParseError = 1, + EntityError = 2, + QueryError = 3, + SubscriptionError = 4, + TransactionError = 5, + AccountError = 6, + SigningError = 7, + ProviderError = 8, + StorageError = 9, + ControllerError = 10, + InvalidInput = 11, + RuntimeError = 12, + }; + + ErrorType(): value(Value::ClientError) {} + + // Implicit conversions between enum and ::Value + constexpr ErrorType(Value v) : value(v) {} + constexpr operator Value() const { return value; } + // Prevent usage as boolean value + explicit operator bool() const = delete; + + inline diplomat::capi::ErrorType AsFFI() const; + inline static ErrorType FromFFI(diplomat::capi::ErrorType c_enum); +private: + Value value; +}; + + +#endif // ErrorType_D_HPP diff --git a/bindings/cpp/ErrorType.hpp b/bindings/cpp/ErrorType.hpp new file mode 100644 index 0000000..8982063 --- /dev/null +++ b/bindings/cpp/ErrorType.hpp @@ -0,0 +1,49 @@ +#ifndef ErrorType_HPP +#define ErrorType_HPP + +#include "ErrorType.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::capi::ErrorType ErrorType::AsFFI() const { + return static_cast(value); +} + +inline ErrorType ErrorType::FromFFI(diplomat::capi::ErrorType c_enum) { + switch (c_enum) { + case diplomat::capi::ErrorType_ClientError: + case diplomat::capi::ErrorType_ParseError: + case diplomat::capi::ErrorType_EntityError: + case diplomat::capi::ErrorType_QueryError: + case diplomat::capi::ErrorType_SubscriptionError: + case diplomat::capi::ErrorType_TransactionError: + case diplomat::capi::ErrorType_AccountError: + case diplomat::capi::ErrorType_SigningError: + case diplomat::capi::ErrorType_ProviderError: + case diplomat::capi::ErrorType_StorageError: + case diplomat::capi::ErrorType_ControllerError: + case diplomat::capi::ErrorType_InvalidInput: + case diplomat::capi::ErrorType_RuntimeError: + return static_cast(c_enum); + default: + std::abort(); + } +} +#endif // ErrorType_HPP diff --git a/bindings/cpp/Event.d.hpp b/bindings/cpp/Event.d.hpp new file mode 100644 index 0000000..a07f5f6 --- /dev/null +++ b/bindings/cpp/Event.d.hpp @@ -0,0 +1,78 @@ +#ifndef Event_D_HPP +#define Event_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Event; +} // namespace capi +} // namespace + +/** + * Represents a Dojo event message + */ +class Event { +public: + + /** + * Gets the keys as JSON array string + */ + inline std::string keys() const; + template + inline void keys_write(W& writeable_output) const; + + /** + * Gets the data as JSON array string + */ + inline std::string data() const; + template + inline void data_write(W& writeable_output) const; + + /** + * Gets the transaction hash (hex) + */ + inline std::string transaction_hash() const; + template + inline void transaction_hash_write(W& writeable_output) const; + + /** + * Creates an event from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the event to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Event* AsFFI() const; + inline diplomat::capi::Event* AsFFI(); + inline static const Event* FromFFI(const diplomat::capi::Event* ptr); + inline static Event* FromFFI(diplomat::capi::Event* ptr); + inline static void operator delete(void* ptr); +private: + Event() = delete; + Event(const Event&) = delete; + Event(Event&&) noexcept = delete; + Event operator=(const Event&) = delete; + Event operator=(Event&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Event_D_HPP diff --git a/bindings/cpp/Event.hpp b/bindings/cpp/Event.hpp new file mode 100644 index 0000000..f43b7ef --- /dev/null +++ b/bindings/cpp/Event.hpp @@ -0,0 +1,123 @@ +#ifndef Event_HPP +#define Event_HPP + +#include "Event.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Event_keys(const diplomat::capi::Event* self, diplomat::capi::DiplomatWrite* write); + + void Event_data(const diplomat::capi::Event* self, diplomat::capi::DiplomatWrite* write); + + void Event_transaction_hash(const diplomat::capi::Event* self, diplomat::capi::DiplomatWrite* write); + + typedef struct Event_from_json_result {union {diplomat::capi::Event* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Event_from_json_result; + Event_from_json_result Event_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Event_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Event_to_json_result; + Event_to_json_result Event_to_json(const diplomat::capi::Event* self, diplomat::capi::DiplomatWrite* write); + + void Event_destroy(Event* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Event::keys() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Event_keys(this->AsFFI(), + &write); + return output; +} +template +inline void Event::keys_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Event_keys(this->AsFFI(), + &write); +} + +inline std::string Event::data() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Event_data(this->AsFFI(), + &write); + return output; +} +template +inline void Event::data_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Event_data(this->AsFFI(), + &write); +} + +inline std::string Event::transaction_hash() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Event_transaction_hash(this->AsFFI(), + &write); + return output; +} +template +inline void Event::transaction_hash_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Event_transaction_hash(this->AsFFI(), + &write); +} + +inline diplomat::result, std::unique_ptr> Event::from_json(std::string_view json) { + auto result = diplomat::capi::Event_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Event::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Event::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Event_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Event::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Event_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Event* Event::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Event* Event::AsFFI() { + return reinterpret_cast(this); +} + +inline const Event* Event::FromFFI(const diplomat::capi::Event* ptr) { + return reinterpret_cast(ptr); +} + +inline Event* Event::FromFFI(diplomat::capi::Event* ptr) { + return reinterpret_cast(ptr); +} + +inline void Event::operator delete(void* ptr) { + diplomat::capi::Event_destroy(reinterpret_cast(ptr)); +} + + +#endif // Event_HPP diff --git a/bindings/cpp/FieldElement.d.hpp b/bindings/cpp/FieldElement.d.hpp new file mode 100644 index 0000000..3440a33 --- /dev/null +++ b/bindings/cpp/FieldElement.d.hpp @@ -0,0 +1,67 @@ +#ifndef FieldElement_D_HPP +#define FieldElement_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct FieldElement; +} // namespace capi +} // namespace + +/** + * Represents a Starknet field element (Felt) + */ +class FieldElement { +public: + + /** + * Creates a new FieldElement from a hexadecimal string + */ + inline static diplomat::result, std::unique_ptr> new_from_hex(std::string_view hex); + + /** + * Creates a new FieldElement from big-endian bytes + */ + inline static std::unique_ptr new_from_bytes(diplomat::span bytes); + + /** + * Returns the field element as a hexadecimal string + */ + inline std::string to_hex() const; + template + inline void to_hex_write(W& writeable_output) const; + + /** + * Returns the field element as bytes (big-endian) + */ + inline void to_bytes(diplomat::span result) const; + + inline const diplomat::capi::FieldElement* AsFFI() const; + inline diplomat::capi::FieldElement* AsFFI(); + inline static const FieldElement* FromFFI(const diplomat::capi::FieldElement* ptr); + inline static FieldElement* FromFFI(diplomat::capi::FieldElement* ptr); + inline static void operator delete(void* ptr); +private: + FieldElement() = delete; + FieldElement(const FieldElement&) = delete; + FieldElement(FieldElement&&) noexcept = delete; + FieldElement operator=(const FieldElement&) = delete; + FieldElement operator=(FieldElement&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // FieldElement_D_HPP diff --git a/bindings/cpp/FieldElement.hpp b/bindings/cpp/FieldElement.hpp new file mode 100644 index 0000000..0021a84 --- /dev/null +++ b/bindings/cpp/FieldElement.hpp @@ -0,0 +1,87 @@ +#ifndef FieldElement_HPP +#define FieldElement_HPP + +#include "FieldElement.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + typedef struct FieldElement_new_from_hex_result {union {diplomat::capi::FieldElement* ok; diplomat::capi::DojoError* err;}; bool is_ok;} FieldElement_new_from_hex_result; + FieldElement_new_from_hex_result FieldElement_new_from_hex(diplomat::capi::DiplomatStringView hex); + + diplomat::capi::FieldElement* FieldElement_new_from_bytes(diplomat::capi::DiplomatU8View bytes); + + void FieldElement_to_hex(const diplomat::capi::FieldElement* self, diplomat::capi::DiplomatWrite* write); + + void FieldElement_to_bytes(const diplomat::capi::FieldElement* self, diplomat::capi::DiplomatU8ViewMut result); + + void FieldElement_destroy(FieldElement* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::result, std::unique_ptr> FieldElement::new_from_hex(std::string_view hex) { + auto result = diplomat::capi::FieldElement_new_from_hex({hex.data(), hex.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(FieldElement::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline std::unique_ptr FieldElement::new_from_bytes(diplomat::span bytes) { + auto result = diplomat::capi::FieldElement_new_from_bytes({bytes.data(), bytes.size()}); + return std::unique_ptr(FieldElement::FromFFI(result)); +} + +inline std::string FieldElement::to_hex() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::FieldElement_to_hex(this->AsFFI(), + &write); + return output; +} +template +inline void FieldElement::to_hex_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::FieldElement_to_hex(this->AsFFI(), + &write); +} + +inline void FieldElement::to_bytes(diplomat::span result) const { + diplomat::capi::FieldElement_to_bytes(this->AsFFI(), + {result.data(), result.size()}); +} + +inline const diplomat::capi::FieldElement* FieldElement::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::FieldElement* FieldElement::AsFFI() { + return reinterpret_cast(this); +} + +inline const FieldElement* FieldElement::FromFFI(const diplomat::capi::FieldElement* ptr) { + return reinterpret_cast(ptr); +} + +inline FieldElement* FieldElement::FromFFI(diplomat::capi::FieldElement* ptr) { + return reinterpret_cast(ptr); +} + +inline void FieldElement::operator delete(void* ptr) { + diplomat::capi::FieldElement_destroy(reinterpret_cast(ptr)); +} + + +#endif // FieldElement_HPP diff --git a/bindings/cpp/KeysClause.d.hpp b/bindings/cpp/KeysClause.d.hpp new file mode 100644 index 0000000..39e929f --- /dev/null +++ b/bindings/cpp/KeysClause.d.hpp @@ -0,0 +1,62 @@ +#ifndef KeysClause_D_HPP +#define KeysClause_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; +namespace diplomat::capi { struct FieldElement; } +class FieldElement; + + +namespace diplomat { +namespace capi { + struct KeysClause; +} // namespace capi +} // namespace + +/** + * Keys clause for filtering by entity keys + */ +class KeysClause { +public: + + /** + * Creates a new keys clause + */ + inline static std::unique_ptr new_(); + + /** + * Adds a key to filter by + */ + inline void add_key(const FieldElement& key); + + /** + * Adds a model to filter by + */ + inline diplomat::result> add_model(std::string_view model); + + inline const diplomat::capi::KeysClause* AsFFI() const; + inline diplomat::capi::KeysClause* AsFFI(); + inline static const KeysClause* FromFFI(const diplomat::capi::KeysClause* ptr); + inline static KeysClause* FromFFI(diplomat::capi::KeysClause* ptr); + inline static void operator delete(void* ptr); +private: + KeysClause() = delete; + KeysClause(const KeysClause&) = delete; + KeysClause(KeysClause&&) noexcept = delete; + KeysClause operator=(const KeysClause&) = delete; + KeysClause operator=(KeysClause&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // KeysClause_D_HPP diff --git a/bindings/cpp/KeysClause.hpp b/bindings/cpp/KeysClause.hpp new file mode 100644 index 0000000..ab2c6e9 --- /dev/null +++ b/bindings/cpp/KeysClause.hpp @@ -0,0 +1,73 @@ +#ifndef KeysClause_HPP +#define KeysClause_HPP + +#include "KeysClause.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "FieldElement.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::KeysClause* KeysClause_new(void); + + void KeysClause_add_key(diplomat::capi::KeysClause* self, const diplomat::capi::FieldElement* key); + + typedef struct KeysClause_add_model_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} KeysClause_add_model_result; + KeysClause_add_model_result KeysClause_add_model(diplomat::capi::KeysClause* self, diplomat::capi::DiplomatStringView model); + + void KeysClause_destroy(KeysClause* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::unique_ptr KeysClause::new_() { + auto result = diplomat::capi::KeysClause_new(); + return std::unique_ptr(KeysClause::FromFFI(result)); +} + +inline void KeysClause::add_key(const FieldElement& key) { + diplomat::capi::KeysClause_add_key(this->AsFFI(), + key.AsFFI()); +} + +inline diplomat::result> KeysClause::add_model(std::string_view model) { + auto result = diplomat::capi::KeysClause_add_model(this->AsFFI(), + {model.data(), model.size()}); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::KeysClause* KeysClause::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::KeysClause* KeysClause::AsFFI() { + return reinterpret_cast(this); +} + +inline const KeysClause* KeysClause::FromFFI(const diplomat::capi::KeysClause* ptr) { + return reinterpret_cast(ptr); +} + +inline KeysClause* KeysClause::FromFFI(diplomat::capi::KeysClause* ptr) { + return reinterpret_cast(ptr); +} + +inline void KeysClause::operator delete(void* ptr) { + diplomat::capi::KeysClause_destroy(reinterpret_cast(ptr)); +} + + +#endif // KeysClause_HPP diff --git a/bindings/cpp/LogicalOperator.d.hpp b/bindings/cpp/LogicalOperator.d.hpp new file mode 100644 index 0000000..b0f0faf --- /dev/null +++ b/bindings/cpp/LogicalOperator.d.hpp @@ -0,0 +1,51 @@ +#ifndef LogicalOperator_D_HPP +#define LogicalOperator_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + enum LogicalOperator { + LogicalOperator_And = 0, + LogicalOperator_Or = 1, + }; + + typedef struct LogicalOperator_option {union { LogicalOperator ok; }; bool is_ok; } LogicalOperator_option; +} // namespace capi +} // namespace + +/** + * Logical operator for combining clauses + */ +class LogicalOperator { +public: + enum Value { + And = 0, + Or = 1, + }; + + LogicalOperator(): value(Value::And) {} + + // Implicit conversions between enum and ::Value + constexpr LogicalOperator(Value v) : value(v) {} + constexpr operator Value() const { return value; } + // Prevent usage as boolean value + explicit operator bool() const = delete; + + inline diplomat::capi::LogicalOperator AsFFI() const; + inline static LogicalOperator FromFFI(diplomat::capi::LogicalOperator c_enum); +private: + Value value; +}; + + +#endif // LogicalOperator_D_HPP diff --git a/bindings/cpp/LogicalOperator.hpp b/bindings/cpp/LogicalOperator.hpp new file mode 100644 index 0000000..235ea83 --- /dev/null +++ b/bindings/cpp/LogicalOperator.hpp @@ -0,0 +1,38 @@ +#ifndef LogicalOperator_HPP +#define LogicalOperator_HPP + +#include "LogicalOperator.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::capi::LogicalOperator LogicalOperator::AsFFI() const { + return static_cast(value); +} + +inline LogicalOperator LogicalOperator::FromFFI(diplomat::capi::LogicalOperator c_enum) { + switch (c_enum) { + case diplomat::capi::LogicalOperator_And: + case diplomat::capi::LogicalOperator_Or: + return static_cast(c_enum); + default: + std::abort(); + } +} +#endif // LogicalOperator_HPP diff --git a/bindings/cpp/Member.d.hpp b/bindings/cpp/Member.d.hpp new file mode 100644 index 0000000..2c53cc3 --- /dev/null +++ b/bindings/cpp/Member.d.hpp @@ -0,0 +1,54 @@ +#ifndef Member_D_HPP +#define Member_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + struct Member; +} // namespace capi +} // namespace + +/** + * Represents a Dojo struct member (field) + */ +class Member { +public: + + /** + * Gets the member name + */ + inline std::string name() const; + template + inline void name_write(W& writeable_output) const; + + /** + * Returns true if this member is a key + */ + inline bool is_key() const; + + inline const diplomat::capi::Member* AsFFI() const; + inline diplomat::capi::Member* AsFFI(); + inline static const Member* FromFFI(const diplomat::capi::Member* ptr); + inline static Member* FromFFI(diplomat::capi::Member* ptr); + inline static void operator delete(void* ptr); +private: + Member() = delete; + Member(const Member&) = delete; + Member(Member&&) noexcept = delete; + Member operator=(const Member&) = delete; + Member operator=(Member&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Member_D_HPP diff --git a/bindings/cpp/Member.hpp b/bindings/cpp/Member.hpp new file mode 100644 index 0000000..8bf2e67 --- /dev/null +++ b/bindings/cpp/Member.hpp @@ -0,0 +1,71 @@ +#ifndef Member_HPP +#define Member_HPP + +#include "Member.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Member_name(const diplomat::capi::Member* self, diplomat::capi::DiplomatWrite* write); + + bool Member_is_key(const diplomat::capi::Member* self); + + void Member_destroy(Member* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Member::name() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Member_name(this->AsFFI(), + &write); + return output; +} +template +inline void Member::name_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Member_name(this->AsFFI(), + &write); +} + +inline bool Member::is_key() const { + auto result = diplomat::capi::Member_is_key(this->AsFFI()); + return result; +} + +inline const diplomat::capi::Member* Member::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Member* Member::AsFFI() { + return reinterpret_cast(this); +} + +inline const Member* Member::FromFFI(const diplomat::capi::Member* ptr) { + return reinterpret_cast(ptr); +} + +inline Member* Member::FromFFI(diplomat::capi::Member* ptr) { + return reinterpret_cast(ptr); +} + +inline void Member::operator delete(void* ptr) { + diplomat::capi::Member_destroy(reinterpret_cast(ptr)); +} + + +#endif // Member_HPP diff --git a/bindings/cpp/Model.d.hpp b/bindings/cpp/Model.d.hpp new file mode 100644 index 0000000..48db13d --- /dev/null +++ b/bindings/cpp/Model.d.hpp @@ -0,0 +1,107 @@ +#ifndef Model_D_HPP +#define Model_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Model; +} // namespace capi +} // namespace + +/** + * Represents a Dojo model + */ +class Model { +public: + + /** + * Gets the model name + */ + inline std::string name() const; + template + inline void name_write(W& writeable_output) const; + + /** + * Gets the model namespace + */ + inline std::string namespace_() const; + template + inline void namespace__write(W& writeable_output) const; + + /** + * Gets the model selector (hex) + */ + inline std::string selector() const; + template + inline void selector_write(W& writeable_output) const; + + /** + * Gets the model class hash (hex) + */ + inline std::string class_hash() const; + template + inline void class_hash_write(W& writeable_output) const; + + /** + * Gets the model contract address (hex) + */ + inline std::string contract_address() const; + template + inline void contract_address_write(W& writeable_output) const; + + /** + * Gets the packed size + */ + inline uint32_t packed_size() const; + + /** + * Gets the unpacked size + */ + inline uint32_t unpacked_size() const; + + /** + * Returns true if the model uses legacy store + */ + inline bool use_legacy_store() const; + + /** + * Creates a new model from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the model to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Model* AsFFI() const; + inline diplomat::capi::Model* AsFFI(); + inline static const Model* FromFFI(const diplomat::capi::Model* ptr); + inline static Model* FromFFI(diplomat::capi::Model* ptr); + inline static void operator delete(void* ptr); +private: + Model() = delete; + Model(const Model&) = delete; + Model(Model&&) noexcept = delete; + Model operator=(const Model&) = delete; + Model operator=(Model&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Model_D_HPP diff --git a/bindings/cpp/Model.hpp b/bindings/cpp/Model.hpp new file mode 100644 index 0000000..d98ea9b --- /dev/null +++ b/bindings/cpp/Model.hpp @@ -0,0 +1,176 @@ +#ifndef Model_HPP +#define Model_HPP + +#include "Model.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Model_name(const diplomat::capi::Model* self, diplomat::capi::DiplomatWrite* write); + + void Model_namespace(const diplomat::capi::Model* self, diplomat::capi::DiplomatWrite* write); + + void Model_selector(const diplomat::capi::Model* self, diplomat::capi::DiplomatWrite* write); + + void Model_class_hash(const diplomat::capi::Model* self, diplomat::capi::DiplomatWrite* write); + + void Model_contract_address(const diplomat::capi::Model* self, diplomat::capi::DiplomatWrite* write); + + uint32_t Model_packed_size(const diplomat::capi::Model* self); + + uint32_t Model_unpacked_size(const diplomat::capi::Model* self); + + bool Model_use_legacy_store(const diplomat::capi::Model* self); + + typedef struct Model_from_json_result {union {diplomat::capi::Model* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Model_from_json_result; + Model_from_json_result Model_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Model_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Model_to_json_result; + Model_to_json_result Model_to_json(const diplomat::capi::Model* self, diplomat::capi::DiplomatWrite* write); + + void Model_destroy(Model* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Model::name() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Model_name(this->AsFFI(), + &write); + return output; +} +template +inline void Model::name_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Model_name(this->AsFFI(), + &write); +} + +inline std::string Model::namespace_() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Model_namespace(this->AsFFI(), + &write); + return output; +} +template +inline void Model::namespace__write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Model_namespace(this->AsFFI(), + &write); +} + +inline std::string Model::selector() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Model_selector(this->AsFFI(), + &write); + return output; +} +template +inline void Model::selector_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Model_selector(this->AsFFI(), + &write); +} + +inline std::string Model::class_hash() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Model_class_hash(this->AsFFI(), + &write); + return output; +} +template +inline void Model::class_hash_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Model_class_hash(this->AsFFI(), + &write); +} + +inline std::string Model::contract_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Model_contract_address(this->AsFFI(), + &write); + return output; +} +template +inline void Model::contract_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Model_contract_address(this->AsFFI(), + &write); +} + +inline uint32_t Model::packed_size() const { + auto result = diplomat::capi::Model_packed_size(this->AsFFI()); + return result; +} + +inline uint32_t Model::unpacked_size() const { + auto result = diplomat::capi::Model_unpacked_size(this->AsFFI()); + return result; +} + +inline bool Model::use_legacy_store() const { + auto result = diplomat::capi::Model_use_legacy_store(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> Model::from_json(std::string_view json) { + auto result = diplomat::capi::Model_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Model::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Model::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Model_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Model::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Model_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Model* Model::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Model* Model::AsFFI() { + return reinterpret_cast(this); +} + +inline const Model* Model::FromFFI(const diplomat::capi::Model* ptr) { + return reinterpret_cast(ptr); +} + +inline Model* Model::FromFFI(diplomat::capi::Model* ptr) { + return reinterpret_cast(ptr); +} + +inline void Model::operator delete(void* ptr) { + diplomat::capi::Model_destroy(reinterpret_cast(ptr)); +} + + +#endif // Model_HPP diff --git a/bindings/cpp/ModelQuery.d.hpp b/bindings/cpp/ModelQuery.d.hpp new file mode 100644 index 0000000..ca4fe4f --- /dev/null +++ b/bindings/cpp/ModelQuery.d.hpp @@ -0,0 +1,55 @@ +#ifndef ModelQuery_D_HPP +#define ModelQuery_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct ModelQuery; +} // namespace capi +} // namespace + +/** + * Model query for retrieving model definitions + */ +class ModelQuery { +public: + + /** + * Creates a new model query + */ + inline static std::unique_ptr new_(); + + /** + * Adds a model name to query + */ + inline diplomat::result> add_model(std::string_view model_name); + + inline const diplomat::capi::ModelQuery* AsFFI() const; + inline diplomat::capi::ModelQuery* AsFFI(); + inline static const ModelQuery* FromFFI(const diplomat::capi::ModelQuery* ptr); + inline static ModelQuery* FromFFI(diplomat::capi::ModelQuery* ptr); + inline static void operator delete(void* ptr); +private: + ModelQuery() = delete; + ModelQuery(const ModelQuery&) = delete; + ModelQuery(ModelQuery&&) noexcept = delete; + ModelQuery operator=(const ModelQuery&) = delete; + ModelQuery operator=(ModelQuery&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // ModelQuery_D_HPP diff --git a/bindings/cpp/ModelQuery.hpp b/bindings/cpp/ModelQuery.hpp new file mode 100644 index 0000000..62c6bd4 --- /dev/null +++ b/bindings/cpp/ModelQuery.hpp @@ -0,0 +1,65 @@ +#ifndef ModelQuery_HPP +#define ModelQuery_HPP + +#include "ModelQuery.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::ModelQuery* ModelQuery_new(void); + + typedef struct ModelQuery_add_model_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} ModelQuery_add_model_result; + ModelQuery_add_model_result ModelQuery_add_model(diplomat::capi::ModelQuery* self, diplomat::capi::DiplomatStringView model_name); + + void ModelQuery_destroy(ModelQuery* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::unique_ptr ModelQuery::new_() { + auto result = diplomat::capi::ModelQuery_new(); + return std::unique_ptr(ModelQuery::FromFFI(result)); +} + +inline diplomat::result> ModelQuery::add_model(std::string_view model_name) { + auto result = diplomat::capi::ModelQuery_add_model(this->AsFFI(), + {model_name.data(), model_name.size()}); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::ModelQuery* ModelQuery::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::ModelQuery* ModelQuery::AsFFI() { + return reinterpret_cast(this); +} + +inline const ModelQuery* ModelQuery::FromFFI(const diplomat::capi::ModelQuery* ptr) { + return reinterpret_cast(ptr); +} + +inline ModelQuery* ModelQuery::FromFFI(diplomat::capi::ModelQuery* ptr) { + return reinterpret_cast(ptr); +} + +inline void ModelQuery::operator delete(void* ptr) { + diplomat::capi::ModelQuery_destroy(reinterpret_cast(ptr)); +} + + +#endif // ModelQuery_HPP diff --git a/bindings/cpp/OrderBy.d.hpp b/bindings/cpp/OrderBy.d.hpp new file mode 100644 index 0000000..7c3b5d8 --- /dev/null +++ b/bindings/cpp/OrderBy.d.hpp @@ -0,0 +1,51 @@ +#ifndef OrderBy_D_HPP +#define OrderBy_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; +class OrderDirection; + + +namespace diplomat { +namespace capi { + struct OrderBy; +} // namespace capi +} // namespace + +/** + * Ordering specification for query results + */ +class OrderBy { +public: + + /** + * Creates a new OrderBy specification + */ + inline static diplomat::result, std::unique_ptr> new_(std::string_view field, OrderDirection direction); + + inline const diplomat::capi::OrderBy* AsFFI() const; + inline diplomat::capi::OrderBy* AsFFI(); + inline static const OrderBy* FromFFI(const diplomat::capi::OrderBy* ptr); + inline static OrderBy* FromFFI(diplomat::capi::OrderBy* ptr); + inline static void operator delete(void* ptr); +private: + OrderBy() = delete; + OrderBy(const OrderBy&) = delete; + OrderBy(OrderBy&&) noexcept = delete; + OrderBy operator=(const OrderBy&) = delete; + OrderBy operator=(OrderBy&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // OrderBy_D_HPP diff --git a/bindings/cpp/OrderBy.hpp b/bindings/cpp/OrderBy.hpp new file mode 100644 index 0000000..959b36f --- /dev/null +++ b/bindings/cpp/OrderBy.hpp @@ -0,0 +1,59 @@ +#ifndef OrderBy_HPP +#define OrderBy_HPP + +#include "OrderBy.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "OrderDirection.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + typedef struct OrderBy_new_result {union {diplomat::capi::OrderBy* ok; diplomat::capi::DojoError* err;}; bool is_ok;} OrderBy_new_result; + OrderBy_new_result OrderBy_new(diplomat::capi::DiplomatStringView field, diplomat::capi::OrderDirection direction); + + void OrderBy_destroy(OrderBy* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::result, std::unique_ptr> OrderBy::new_(std::string_view field, OrderDirection direction) { + auto result = diplomat::capi::OrderBy_new({field.data(), field.size()}, + direction.AsFFI()); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(OrderBy::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::OrderBy* OrderBy::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::OrderBy* OrderBy::AsFFI() { + return reinterpret_cast(this); +} + +inline const OrderBy* OrderBy::FromFFI(const diplomat::capi::OrderBy* ptr) { + return reinterpret_cast(ptr); +} + +inline OrderBy* OrderBy::FromFFI(diplomat::capi::OrderBy* ptr) { + return reinterpret_cast(ptr); +} + +inline void OrderBy::operator delete(void* ptr) { + diplomat::capi::OrderBy_destroy(reinterpret_cast(ptr)); +} + + +#endif // OrderBy_HPP diff --git a/bindings/cpp/OrderDirection.d.hpp b/bindings/cpp/OrderDirection.d.hpp new file mode 100644 index 0000000..fe407b2 --- /dev/null +++ b/bindings/cpp/OrderDirection.d.hpp @@ -0,0 +1,51 @@ +#ifndef OrderDirection_D_HPP +#define OrderDirection_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + enum OrderDirection { + OrderDirection_Asc = 0, + OrderDirection_Desc = 1, + }; + + typedef struct OrderDirection_option {union { OrderDirection ok; }; bool is_ok; } OrderDirection_option; +} // namespace capi +} // namespace + +/** + * Direction for ordering results + */ +class OrderDirection { +public: + enum Value { + Asc = 0, + Desc = 1, + }; + + OrderDirection(): value(Value::Asc) {} + + // Implicit conversions between enum and ::Value + constexpr OrderDirection(Value v) : value(v) {} + constexpr operator Value() const { return value; } + // Prevent usage as boolean value + explicit operator bool() const = delete; + + inline diplomat::capi::OrderDirection AsFFI() const; + inline static OrderDirection FromFFI(diplomat::capi::OrderDirection c_enum); +private: + Value value; +}; + + +#endif // OrderDirection_D_HPP diff --git a/bindings/cpp/OrderDirection.hpp b/bindings/cpp/OrderDirection.hpp new file mode 100644 index 0000000..60b7d9b --- /dev/null +++ b/bindings/cpp/OrderDirection.hpp @@ -0,0 +1,38 @@ +#ifndef OrderDirection_HPP +#define OrderDirection_HPP + +#include "OrderDirection.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::capi::OrderDirection OrderDirection::AsFFI() const { + return static_cast(value); +} + +inline OrderDirection OrderDirection::FromFFI(diplomat::capi::OrderDirection c_enum) { + switch (c_enum) { + case diplomat::capi::OrderDirection_Asc: + case diplomat::capi::OrderDirection_Desc: + return static_cast(c_enum); + default: + std::abort(); + } +} +#endif // OrderDirection_HPP diff --git a/bindings/cpp/Pagination.d.hpp b/bindings/cpp/Pagination.d.hpp new file mode 100644 index 0000000..ed1c888 --- /dev/null +++ b/bindings/cpp/Pagination.d.hpp @@ -0,0 +1,73 @@ +#ifndef Pagination_D_HPP +#define Pagination_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; +namespace diplomat::capi { struct OrderBy; } +class OrderBy; +class PaginationDirection; + + +namespace diplomat { +namespace capi { + struct Pagination; +} // namespace capi +} // namespace + +/** + * Pagination configuration for queries + */ +class Pagination { +public: + + /** + * Creates a new Pagination with default values + */ + inline static std::unique_ptr new_(); + + /** + * Sets the cursor for pagination + */ + inline diplomat::result> set_cursor(std::string_view cursor); + + /** + * Sets the limit for pagination + */ + inline void set_limit(uint32_t limit); + + /** + * Sets the direction for pagination + */ + inline void set_direction(PaginationDirection direction); + + /** + * Adds an ordering specification + */ + inline void add_order_by(const OrderBy& order_by); + + inline const diplomat::capi::Pagination* AsFFI() const; + inline diplomat::capi::Pagination* AsFFI(); + inline static const Pagination* FromFFI(const diplomat::capi::Pagination* ptr); + inline static Pagination* FromFFI(diplomat::capi::Pagination* ptr); + inline static void operator delete(void* ptr); +private: + Pagination() = delete; + Pagination(const Pagination&) = delete; + Pagination(Pagination&&) noexcept = delete; + Pagination operator=(const Pagination&) = delete; + Pagination operator=(Pagination&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Pagination_D_HPP diff --git a/bindings/cpp/Pagination.hpp b/bindings/cpp/Pagination.hpp new file mode 100644 index 0000000..4f02e2e --- /dev/null +++ b/bindings/cpp/Pagination.hpp @@ -0,0 +1,88 @@ +#ifndef Pagination_HPP +#define Pagination_HPP + +#include "Pagination.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "OrderBy.hpp" +#include "PaginationDirection.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::Pagination* Pagination_new(void); + + typedef struct Pagination_set_cursor_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Pagination_set_cursor_result; + Pagination_set_cursor_result Pagination_set_cursor(diplomat::capi::Pagination* self, diplomat::capi::DiplomatStringView cursor); + + void Pagination_set_limit(diplomat::capi::Pagination* self, uint32_t limit); + + void Pagination_set_direction(diplomat::capi::Pagination* self, diplomat::capi::PaginationDirection direction); + + void Pagination_add_order_by(diplomat::capi::Pagination* self, const diplomat::capi::OrderBy* order_by); + + void Pagination_destroy(Pagination* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::unique_ptr Pagination::new_() { + auto result = diplomat::capi::Pagination_new(); + return std::unique_ptr(Pagination::FromFFI(result)); +} + +inline diplomat::result> Pagination::set_cursor(std::string_view cursor) { + auto result = diplomat::capi::Pagination_set_cursor(this->AsFFI(), + {cursor.data(), cursor.size()}); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline void Pagination::set_limit(uint32_t limit) { + diplomat::capi::Pagination_set_limit(this->AsFFI(), + limit); +} + +inline void Pagination::set_direction(PaginationDirection direction) { + diplomat::capi::Pagination_set_direction(this->AsFFI(), + direction.AsFFI()); +} + +inline void Pagination::add_order_by(const OrderBy& order_by) { + diplomat::capi::Pagination_add_order_by(this->AsFFI(), + order_by.AsFFI()); +} + +inline const diplomat::capi::Pagination* Pagination::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Pagination* Pagination::AsFFI() { + return reinterpret_cast(this); +} + +inline const Pagination* Pagination::FromFFI(const diplomat::capi::Pagination* ptr) { + return reinterpret_cast(ptr); +} + +inline Pagination* Pagination::FromFFI(diplomat::capi::Pagination* ptr) { + return reinterpret_cast(ptr); +} + +inline void Pagination::operator delete(void* ptr) { + diplomat::capi::Pagination_destroy(reinterpret_cast(ptr)); +} + + +#endif // Pagination_HPP diff --git a/bindings/cpp/PaginationDirection.d.hpp b/bindings/cpp/PaginationDirection.d.hpp new file mode 100644 index 0000000..8adbdbc --- /dev/null +++ b/bindings/cpp/PaginationDirection.d.hpp @@ -0,0 +1,51 @@ +#ifndef PaginationDirection_D_HPP +#define PaginationDirection_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + enum PaginationDirection { + PaginationDirection_Forward = 0, + PaginationDirection_Backward = 1, + }; + + typedef struct PaginationDirection_option {union { PaginationDirection ok; }; bool is_ok; } PaginationDirection_option; +} // namespace capi +} // namespace + +/** + * Direction for pagination + */ +class PaginationDirection { +public: + enum Value { + Forward = 0, + Backward = 1, + }; + + PaginationDirection(): value(Value::Forward) {} + + // Implicit conversions between enum and ::Value + constexpr PaginationDirection(Value v) : value(v) {} + constexpr operator Value() const { return value; } + // Prevent usage as boolean value + explicit operator bool() const = delete; + + inline diplomat::capi::PaginationDirection AsFFI() const; + inline static PaginationDirection FromFFI(diplomat::capi::PaginationDirection c_enum); +private: + Value value; +}; + + +#endif // PaginationDirection_D_HPP diff --git a/bindings/cpp/PaginationDirection.hpp b/bindings/cpp/PaginationDirection.hpp new file mode 100644 index 0000000..c80ba02 --- /dev/null +++ b/bindings/cpp/PaginationDirection.hpp @@ -0,0 +1,38 @@ +#ifndef PaginationDirection_HPP +#define PaginationDirection_HPP + +#include "PaginationDirection.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::capi::PaginationDirection PaginationDirection::AsFFI() const { + return static_cast(value); +} + +inline PaginationDirection PaginationDirection::FromFFI(diplomat::capi::PaginationDirection c_enum) { + switch (c_enum) { + case diplomat::capi::PaginationDirection_Forward: + case diplomat::capi::PaginationDirection_Backward: + return static_cast(c_enum); + default: + std::abort(); + } +} +#endif // PaginationDirection_HPP diff --git a/bindings/cpp/PatternMatching.d.hpp b/bindings/cpp/PatternMatching.d.hpp new file mode 100644 index 0000000..c22ba68 --- /dev/null +++ b/bindings/cpp/PatternMatching.d.hpp @@ -0,0 +1,51 @@ +#ifndef PatternMatching_D_HPP +#define PatternMatching_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + enum PatternMatching { + PatternMatching_FixedLen = 0, + PatternMatching_VariableLen = 1, + }; + + typedef struct PatternMatching_option {union { PatternMatching ok; }; bool is_ok; } PatternMatching_option; +} // namespace capi +} // namespace + +/** + * Pattern matching mode for key queries + */ +class PatternMatching { +public: + enum Value { + FixedLen = 0, + VariableLen = 1, + }; + + PatternMatching(): value(Value::FixedLen) {} + + // Implicit conversions between enum and ::Value + constexpr PatternMatching(Value v) : value(v) {} + constexpr operator Value() const { return value; } + // Prevent usage as boolean value + explicit operator bool() const = delete; + + inline diplomat::capi::PatternMatching AsFFI() const; + inline static PatternMatching FromFFI(diplomat::capi::PatternMatching c_enum); +private: + Value value; +}; + + +#endif // PatternMatching_D_HPP diff --git a/bindings/cpp/PatternMatching.hpp b/bindings/cpp/PatternMatching.hpp new file mode 100644 index 0000000..4e4468b --- /dev/null +++ b/bindings/cpp/PatternMatching.hpp @@ -0,0 +1,38 @@ +#ifndef PatternMatching_HPP +#define PatternMatching_HPP + +#include "PatternMatching.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::capi::PatternMatching PatternMatching::AsFFI() const { + return static_cast(value); +} + +inline PatternMatching PatternMatching::FromFFI(diplomat::capi::PatternMatching c_enum) { + switch (c_enum) { + case diplomat::capi::PatternMatching_FixedLen: + case diplomat::capi::PatternMatching_VariableLen: + return static_cast(c_enum); + default: + std::abort(); + } +} +#endif // PatternMatching_HPP diff --git a/bindings/cpp/PlayerAchievementEntry.d.hpp b/bindings/cpp/PlayerAchievementEntry.d.hpp new file mode 100644 index 0000000..764b8c0 --- /dev/null +++ b/bindings/cpp/PlayerAchievementEntry.d.hpp @@ -0,0 +1,94 @@ +#ifndef PlayerAchievementEntry_D_HPP +#define PlayerAchievementEntry_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct PlayerAchievementEntry; +} // namespace capi +} // namespace + +/** + * Represents player achievement progress + */ +class PlayerAchievementEntry { +public: + + /** + * Gets the player address (hex) + */ + inline std::string player_address() const; + template + inline void player_address_write(W& writeable_output) const; + + /** + * Gets the total points + */ + inline uint32_t total_points() const; + + /** + * Gets the completed achievements count + */ + inline uint32_t completed_achievements() const; + + /** + * Gets the total achievements count + */ + inline uint32_t total_achievements() const; + + /** + * Gets the completion percentage + */ + inline double completion_percentage() const; + + /** + * Gets the achievements count + */ + inline uint32_t achievements_count() const; + + /** + * Gets the updated_at timestamp + */ + inline uint64_t updated_at() const; + + /** + * Creates a player achievement entry from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the player achievement entry to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::PlayerAchievementEntry* AsFFI() const; + inline diplomat::capi::PlayerAchievementEntry* AsFFI(); + inline static const PlayerAchievementEntry* FromFFI(const diplomat::capi::PlayerAchievementEntry* ptr); + inline static PlayerAchievementEntry* FromFFI(diplomat::capi::PlayerAchievementEntry* ptr); + inline static void operator delete(void* ptr); +private: + PlayerAchievementEntry() = delete; + PlayerAchievementEntry(const PlayerAchievementEntry&) = delete; + PlayerAchievementEntry(PlayerAchievementEntry&&) noexcept = delete; + PlayerAchievementEntry operator=(const PlayerAchievementEntry&) = delete; + PlayerAchievementEntry operator=(PlayerAchievementEntry&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // PlayerAchievementEntry_D_HPP diff --git a/bindings/cpp/PlayerAchievementEntry.hpp b/bindings/cpp/PlayerAchievementEntry.hpp new file mode 100644 index 0000000..9460552 --- /dev/null +++ b/bindings/cpp/PlayerAchievementEntry.hpp @@ -0,0 +1,133 @@ +#ifndef PlayerAchievementEntry_HPP +#define PlayerAchievementEntry_HPP + +#include "PlayerAchievementEntry.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void PlayerAchievementEntry_player_address(const diplomat::capi::PlayerAchievementEntry* self, diplomat::capi::DiplomatWrite* write); + + uint32_t PlayerAchievementEntry_total_points(const diplomat::capi::PlayerAchievementEntry* self); + + uint32_t PlayerAchievementEntry_completed_achievements(const diplomat::capi::PlayerAchievementEntry* self); + + uint32_t PlayerAchievementEntry_total_achievements(const diplomat::capi::PlayerAchievementEntry* self); + + double PlayerAchievementEntry_completion_percentage(const diplomat::capi::PlayerAchievementEntry* self); + + uint32_t PlayerAchievementEntry_achievements_count(const diplomat::capi::PlayerAchievementEntry* self); + + uint64_t PlayerAchievementEntry_updated_at(const diplomat::capi::PlayerAchievementEntry* self); + + typedef struct PlayerAchievementEntry_from_json_result {union {diplomat::capi::PlayerAchievementEntry* ok; diplomat::capi::DojoError* err;}; bool is_ok;} PlayerAchievementEntry_from_json_result; + PlayerAchievementEntry_from_json_result PlayerAchievementEntry_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct PlayerAchievementEntry_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} PlayerAchievementEntry_to_json_result; + PlayerAchievementEntry_to_json_result PlayerAchievementEntry_to_json(const diplomat::capi::PlayerAchievementEntry* self, diplomat::capi::DiplomatWrite* write); + + void PlayerAchievementEntry_destroy(PlayerAchievementEntry* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string PlayerAchievementEntry::player_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::PlayerAchievementEntry_player_address(this->AsFFI(), + &write); + return output; +} +template +inline void PlayerAchievementEntry::player_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::PlayerAchievementEntry_player_address(this->AsFFI(), + &write); +} + +inline uint32_t PlayerAchievementEntry::total_points() const { + auto result = diplomat::capi::PlayerAchievementEntry_total_points(this->AsFFI()); + return result; +} + +inline uint32_t PlayerAchievementEntry::completed_achievements() const { + auto result = diplomat::capi::PlayerAchievementEntry_completed_achievements(this->AsFFI()); + return result; +} + +inline uint32_t PlayerAchievementEntry::total_achievements() const { + auto result = diplomat::capi::PlayerAchievementEntry_total_achievements(this->AsFFI()); + return result; +} + +inline double PlayerAchievementEntry::completion_percentage() const { + auto result = diplomat::capi::PlayerAchievementEntry_completion_percentage(this->AsFFI()); + return result; +} + +inline uint32_t PlayerAchievementEntry::achievements_count() const { + auto result = diplomat::capi::PlayerAchievementEntry_achievements_count(this->AsFFI()); + return result; +} + +inline uint64_t PlayerAchievementEntry::updated_at() const { + auto result = diplomat::capi::PlayerAchievementEntry_updated_at(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> PlayerAchievementEntry::from_json(std::string_view json) { + auto result = diplomat::capi::PlayerAchievementEntry_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(PlayerAchievementEntry::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> PlayerAchievementEntry::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::PlayerAchievementEntry_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> PlayerAchievementEntry::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::PlayerAchievementEntry_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::PlayerAchievementEntry* PlayerAchievementEntry::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::PlayerAchievementEntry* PlayerAchievementEntry::AsFFI() { + return reinterpret_cast(this); +} + +inline const PlayerAchievementEntry* PlayerAchievementEntry::FromFFI(const diplomat::capi::PlayerAchievementEntry* ptr) { + return reinterpret_cast(ptr); +} + +inline PlayerAchievementEntry* PlayerAchievementEntry::FromFFI(diplomat::capi::PlayerAchievementEntry* ptr) { + return reinterpret_cast(ptr); +} + +inline void PlayerAchievementEntry::operator delete(void* ptr) { + diplomat::capi::PlayerAchievementEntry_destroy(reinterpret_cast(ptr)); +} + + +#endif // PlayerAchievementEntry_HPP diff --git a/bindings/cpp/Primitive.d.hpp b/bindings/cpp/Primitive.d.hpp new file mode 100644 index 0000000..f3b5e53 --- /dev/null +++ b/bindings/cpp/Primitive.d.hpp @@ -0,0 +1,63 @@ +#ifndef Primitive_D_HPP +#define Primitive_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; +class PrimitiveType; + + +namespace diplomat { +namespace capi { + struct Primitive; +} // namespace capi +} // namespace + +/** + * Represents a primitive Cairo type with its value + */ +class Primitive { +public: + + /** + * Gets the primitive type + */ + inline PrimitiveType primitive_type() const; + + /** + * Creates a primitive from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the primitive to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Primitive* AsFFI() const; + inline diplomat::capi::Primitive* AsFFI(); + inline static const Primitive* FromFFI(const diplomat::capi::Primitive* ptr); + inline static Primitive* FromFFI(diplomat::capi::Primitive* ptr); + inline static void operator delete(void* ptr); +private: + Primitive() = delete; + Primitive(const Primitive&) = delete; + Primitive(Primitive&&) noexcept = delete; + Primitive operator=(const Primitive&) = delete; + Primitive operator=(Primitive&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Primitive_D_HPP diff --git a/bindings/cpp/Primitive.hpp b/bindings/cpp/Primitive.hpp new file mode 100644 index 0000000..cda9865 --- /dev/null +++ b/bindings/cpp/Primitive.hpp @@ -0,0 +1,83 @@ +#ifndef Primitive_HPP +#define Primitive_HPP + +#include "Primitive.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "PrimitiveType.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::PrimitiveType Primitive_primitive_type(const diplomat::capi::Primitive* self); + + typedef struct Primitive_from_json_result {union {diplomat::capi::Primitive* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Primitive_from_json_result; + Primitive_from_json_result Primitive_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Primitive_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Primitive_to_json_result; + Primitive_to_json_result Primitive_to_json(const diplomat::capi::Primitive* self, diplomat::capi::DiplomatWrite* write); + + void Primitive_destroy(Primitive* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline PrimitiveType Primitive::primitive_type() const { + auto result = diplomat::capi::Primitive_primitive_type(this->AsFFI()); + return PrimitiveType::FromFFI(result); +} + +inline diplomat::result, std::unique_ptr> Primitive::from_json(std::string_view json) { + auto result = diplomat::capi::Primitive_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Primitive::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Primitive::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Primitive_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Primitive::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Primitive_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Primitive* Primitive::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Primitive* Primitive::AsFFI() { + return reinterpret_cast(this); +} + +inline const Primitive* Primitive::FromFFI(const diplomat::capi::Primitive* ptr) { + return reinterpret_cast(ptr); +} + +inline Primitive* Primitive::FromFFI(diplomat::capi::Primitive* ptr) { + return reinterpret_cast(ptr); +} + +inline void Primitive::operator delete(void* ptr) { + diplomat::capi::Primitive_destroy(reinterpret_cast(ptr)); +} + + +#endif // Primitive_HPP diff --git a/bindings/cpp/PrimitiveType.d.hpp b/bindings/cpp/PrimitiveType.d.hpp new file mode 100644 index 0000000..12efb5c --- /dev/null +++ b/bindings/cpp/PrimitiveType.d.hpp @@ -0,0 +1,79 @@ +#ifndef PrimitiveType_D_HPP +#define PrimitiveType_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + enum PrimitiveType { + PrimitiveType_I8 = 0, + PrimitiveType_I16 = 1, + PrimitiveType_I32 = 2, + PrimitiveType_I64 = 3, + PrimitiveType_I128 = 4, + PrimitiveType_U8 = 5, + PrimitiveType_U16 = 6, + PrimitiveType_U32 = 7, + PrimitiveType_U64 = 8, + PrimitiveType_U128 = 9, + PrimitiveType_U256 = 10, + PrimitiveType_Bool = 11, + PrimitiveType_Felt252 = 12, + PrimitiveType_ClassHash = 13, + PrimitiveType_ContractAddress = 14, + PrimitiveType_EthAddress = 15, + }; + + typedef struct PrimitiveType_option {union { PrimitiveType ok; }; bool is_ok; } PrimitiveType_option; +} // namespace capi +} // namespace + +/** + * Type of primitive + */ +class PrimitiveType { +public: + enum Value { + I8 = 0, + I16 = 1, + I32 = 2, + I64 = 3, + I128 = 4, + U8 = 5, + U16 = 6, + U32 = 7, + U64 = 8, + U128 = 9, + U256 = 10, + Bool = 11, + Felt252 = 12, + ClassHash = 13, + ContractAddress = 14, + EthAddress = 15, + }; + + PrimitiveType(): value(Value::I8) {} + + // Implicit conversions between enum and ::Value + constexpr PrimitiveType(Value v) : value(v) {} + constexpr operator Value() const { return value; } + // Prevent usage as boolean value + explicit operator bool() const = delete; + + inline diplomat::capi::PrimitiveType AsFFI() const; + inline static PrimitiveType FromFFI(diplomat::capi::PrimitiveType c_enum); +private: + Value value; +}; + + +#endif // PrimitiveType_D_HPP diff --git a/bindings/cpp/PrimitiveType.hpp b/bindings/cpp/PrimitiveType.hpp new file mode 100644 index 0000000..9508941 --- /dev/null +++ b/bindings/cpp/PrimitiveType.hpp @@ -0,0 +1,52 @@ +#ifndef PrimitiveType_HPP +#define PrimitiveType_HPP + +#include "PrimitiveType.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::capi::PrimitiveType PrimitiveType::AsFFI() const { + return static_cast(value); +} + +inline PrimitiveType PrimitiveType::FromFFI(diplomat::capi::PrimitiveType c_enum) { + switch (c_enum) { + case diplomat::capi::PrimitiveType_I8: + case diplomat::capi::PrimitiveType_I16: + case diplomat::capi::PrimitiveType_I32: + case diplomat::capi::PrimitiveType_I64: + case diplomat::capi::PrimitiveType_I128: + case diplomat::capi::PrimitiveType_U8: + case diplomat::capi::PrimitiveType_U16: + case diplomat::capi::PrimitiveType_U32: + case diplomat::capi::PrimitiveType_U64: + case diplomat::capi::PrimitiveType_U128: + case diplomat::capi::PrimitiveType_U256: + case diplomat::capi::PrimitiveType_Bool: + case diplomat::capi::PrimitiveType_Felt252: + case diplomat::capi::PrimitiveType_ClassHash: + case diplomat::capi::PrimitiveType_ContractAddress: + case diplomat::capi::PrimitiveType_EthAddress: + return static_cast(c_enum); + default: + std::abort(); + } +} +#endif // PrimitiveType_HPP diff --git a/bindings/cpp/Provider.d.hpp b/bindings/cpp/Provider.d.hpp new file mode 100644 index 0000000..251865a --- /dev/null +++ b/bindings/cpp/Provider.d.hpp @@ -0,0 +1,62 @@ +#ifndef Provider_D_HPP +#define Provider_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Provider; +} // namespace capi +} // namespace + +/** + * JSON-RPC provider for Starknet + */ +class Provider { +public: + + /** + * Creates a new provider from an RPC URL + */ + inline static diplomat::result, std::unique_ptr> new_(std::string_view rpc_url); + + /** + * Gets the chain ID + */ + inline diplomat::result> chain_id() const; + template + inline diplomat::result> chain_id_write(W& writeable_output) const; + + /** + * Gets the latest block number + */ + inline diplomat::result> block_number() const; + + inline const diplomat::capi::Provider* AsFFI() const; + inline diplomat::capi::Provider* AsFFI(); + inline static const Provider* FromFFI(const diplomat::capi::Provider* ptr); + inline static Provider* FromFFI(diplomat::capi::Provider* ptr); + inline static void operator delete(void* ptr); +private: + Provider() = delete; + Provider(const Provider&) = delete; + Provider(Provider&&) noexcept = delete; + Provider operator=(const Provider&) = delete; + Provider operator=(Provider&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Provider_D_HPP diff --git a/bindings/cpp/Provider.hpp b/bindings/cpp/Provider.hpp new file mode 100644 index 0000000..7bd48b7 --- /dev/null +++ b/bindings/cpp/Provider.hpp @@ -0,0 +1,83 @@ +#ifndef Provider_HPP +#define Provider_HPP + +#include "Provider.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + typedef struct Provider_new_result {union {diplomat::capi::Provider* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Provider_new_result; + Provider_new_result Provider_new(diplomat::capi::DiplomatStringView rpc_url); + + typedef struct Provider_chain_id_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Provider_chain_id_result; + Provider_chain_id_result Provider_chain_id(const diplomat::capi::Provider* self, diplomat::capi::DiplomatWrite* write); + + typedef struct Provider_block_number_result {union {uint64_t ok; diplomat::capi::DojoError* err;}; bool is_ok;} Provider_block_number_result; + Provider_block_number_result Provider_block_number(const diplomat::capi::Provider* self); + + void Provider_destroy(Provider* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::result, std::unique_ptr> Provider::new_(std::string_view rpc_url) { + auto result = diplomat::capi::Provider_new({rpc_url.data(), rpc_url.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Provider::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Provider::chain_id() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Provider_chain_id(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Provider::chain_id_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Provider_chain_id(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Provider::block_number() const { + auto result = diplomat::capi::Provider_block_number(this->AsFFI()); + return result.is_ok ? diplomat::result>(diplomat::Ok(result.ok)) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Provider* Provider::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Provider* Provider::AsFFI() { + return reinterpret_cast(this); +} + +inline const Provider* Provider::FromFFI(const diplomat::capi::Provider* ptr) { + return reinterpret_cast(ptr); +} + +inline Provider* Provider::FromFFI(diplomat::capi::Provider* ptr) { + return reinterpret_cast(ptr); +} + +inline void Provider::operator delete(void* ptr) { + diplomat::capi::Provider_destroy(reinterpret_cast(ptr)); +} + + +#endif // Provider_HPP diff --git a/bindings/cpp/Signature.d.hpp b/bindings/cpp/Signature.d.hpp new file mode 100644 index 0000000..feaf4d1 --- /dev/null +++ b/bindings/cpp/Signature.d.hpp @@ -0,0 +1,64 @@ +#ifndef Signature_D_HPP +#define Signature_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct FieldElement; } +class FieldElement; + + +namespace diplomat { +namespace capi { + struct Signature; +} // namespace capi +} // namespace + +/** + * Represents a signature (r, s pair) + */ +class Signature { +public: + + /** + * Creates a new signature from r and s components + */ + inline static std::unique_ptr new_(const FieldElement& r, const FieldElement& s); + + /** + * Gets the r component + */ + inline std::string r() const; + template + inline void r_write(W& writeable_output) const; + + /** + * Gets the s component + */ + inline std::string s() const; + template + inline void s_write(W& writeable_output) const; + + inline const diplomat::capi::Signature* AsFFI() const; + inline diplomat::capi::Signature* AsFFI(); + inline static const Signature* FromFFI(const diplomat::capi::Signature* ptr); + inline static Signature* FromFFI(diplomat::capi::Signature* ptr); + inline static void operator delete(void* ptr); +private: + Signature() = delete; + Signature(const Signature&) = delete; + Signature(Signature&&) noexcept = delete; + Signature operator=(const Signature&) = delete; + Signature operator=(Signature&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Signature_D_HPP diff --git a/bindings/cpp/Signature.hpp b/bindings/cpp/Signature.hpp new file mode 100644 index 0000000..60d0b96 --- /dev/null +++ b/bindings/cpp/Signature.hpp @@ -0,0 +1,89 @@ +#ifndef Signature_HPP +#define Signature_HPP + +#include "Signature.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "FieldElement.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + diplomat::capi::Signature* Signature_new(const diplomat::capi::FieldElement* r, const diplomat::capi::FieldElement* s); + + void Signature_r(const diplomat::capi::Signature* self, diplomat::capi::DiplomatWrite* write); + + void Signature_s(const diplomat::capi::Signature* self, diplomat::capi::DiplomatWrite* write); + + void Signature_destroy(Signature* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::unique_ptr Signature::new_(const FieldElement& r, const FieldElement& s) { + auto result = diplomat::capi::Signature_new(r.AsFFI(), + s.AsFFI()); + return std::unique_ptr(Signature::FromFFI(result)); +} + +inline std::string Signature::r() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Signature_r(this->AsFFI(), + &write); + return output; +} +template +inline void Signature::r_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Signature_r(this->AsFFI(), + &write); +} + +inline std::string Signature::s() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Signature_s(this->AsFFI(), + &write); + return output; +} +template +inline void Signature::s_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Signature_s(this->AsFFI(), + &write); +} + +inline const diplomat::capi::Signature* Signature::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Signature* Signature::AsFFI() { + return reinterpret_cast(this); +} + +inline const Signature* Signature::FromFFI(const diplomat::capi::Signature* ptr) { + return reinterpret_cast(ptr); +} + +inline Signature* Signature::FromFFI(diplomat::capi::Signature* ptr) { + return reinterpret_cast(ptr); +} + +inline void Signature::operator delete(void* ptr) { + diplomat::capi::Signature_destroy(reinterpret_cast(ptr)); +} + + +#endif // Signature_HPP diff --git a/bindings/cpp/SigningKey.d.hpp b/bindings/cpp/SigningKey.d.hpp new file mode 100644 index 0000000..8e0c6cb --- /dev/null +++ b/bindings/cpp/SigningKey.d.hpp @@ -0,0 +1,78 @@ +#ifndef SigningKey_D_HPP +#define SigningKey_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; +namespace diplomat::capi { struct FieldElement; } +class FieldElement; +namespace diplomat::capi { struct Signature; } +class Signature; +namespace diplomat::capi { struct VerifyingKey; } +class VerifyingKey; + + +namespace diplomat { +namespace capi { + struct SigningKey; +} // namespace capi +} // namespace + +/** + * Represents a signing key for Starknet transactions + */ +class SigningKey { +public: + + /** + * Creates a new signing key from a secret scalar + */ + inline static diplomat::result, std::unique_ptr> new_(std::string_view secret_scalar); + + /** + * Generates a new random signing key + */ + inline static std::unique_ptr from_random(); + + /** + * Returns the secret scalar of the signing key + */ + inline std::string secret_scalar() const; + template + inline void secret_scalar_write(W& writeable_output) const; + + /** + * Signs a message hash + */ + inline diplomat::result, std::unique_ptr> sign(const FieldElement& hash) const; + + /** + * Returns the verifying key + */ + inline std::unique_ptr verifying_key() const; + + inline const diplomat::capi::SigningKey* AsFFI() const; + inline diplomat::capi::SigningKey* AsFFI(); + inline static const SigningKey* FromFFI(const diplomat::capi::SigningKey* ptr); + inline static SigningKey* FromFFI(diplomat::capi::SigningKey* ptr); + inline static void operator delete(void* ptr); +private: + SigningKey() = delete; + SigningKey(const SigningKey&) = delete; + SigningKey(SigningKey&&) noexcept = delete; + SigningKey operator=(const SigningKey&) = delete; + SigningKey operator=(SigningKey&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // SigningKey_D_HPP diff --git a/bindings/cpp/SigningKey.hpp b/bindings/cpp/SigningKey.hpp new file mode 100644 index 0000000..0d4bf52 --- /dev/null +++ b/bindings/cpp/SigningKey.hpp @@ -0,0 +1,99 @@ +#ifndef SigningKey_HPP +#define SigningKey_HPP + +#include "SigningKey.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "FieldElement.hpp" +#include "Signature.hpp" +#include "VerifyingKey.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + typedef struct SigningKey_new_result {union {diplomat::capi::SigningKey* ok; diplomat::capi::DojoError* err;}; bool is_ok;} SigningKey_new_result; + SigningKey_new_result SigningKey_new(diplomat::capi::DiplomatStringView secret_scalar); + + diplomat::capi::SigningKey* SigningKey_from_random(void); + + void SigningKey_secret_scalar(const diplomat::capi::SigningKey* self, diplomat::capi::DiplomatWrite* write); + + typedef struct SigningKey_sign_result {union {diplomat::capi::Signature* ok; diplomat::capi::DojoError* err;}; bool is_ok;} SigningKey_sign_result; + SigningKey_sign_result SigningKey_sign(const diplomat::capi::SigningKey* self, const diplomat::capi::FieldElement* hash); + + diplomat::capi::VerifyingKey* SigningKey_verifying_key(const diplomat::capi::SigningKey* self); + + void SigningKey_destroy(SigningKey* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::result, std::unique_ptr> SigningKey::new_(std::string_view secret_scalar) { + auto result = diplomat::capi::SigningKey_new({secret_scalar.data(), secret_scalar.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(SigningKey::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline std::unique_ptr SigningKey::from_random() { + auto result = diplomat::capi::SigningKey_from_random(); + return std::unique_ptr(SigningKey::FromFFI(result)); +} + +inline std::string SigningKey::secret_scalar() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::SigningKey_secret_scalar(this->AsFFI(), + &write); + return output; +} +template +inline void SigningKey::secret_scalar_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::SigningKey_secret_scalar(this->AsFFI(), + &write); +} + +inline diplomat::result, std::unique_ptr> SigningKey::sign(const FieldElement& hash) const { + auto result = diplomat::capi::SigningKey_sign(this->AsFFI(), + hash.AsFFI()); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Signature::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline std::unique_ptr SigningKey::verifying_key() const { + auto result = diplomat::capi::SigningKey_verifying_key(this->AsFFI()); + return std::unique_ptr(VerifyingKey::FromFFI(result)); +} + +inline const diplomat::capi::SigningKey* SigningKey::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::SigningKey* SigningKey::AsFFI() { + return reinterpret_cast(this); +} + +inline const SigningKey* SigningKey::FromFFI(const diplomat::capi::SigningKey* ptr) { + return reinterpret_cast(ptr); +} + +inline SigningKey* SigningKey::FromFFI(diplomat::capi::SigningKey* ptr) { + return reinterpret_cast(ptr); +} + +inline void SigningKey::operator delete(void* ptr) { + diplomat::capi::SigningKey_destroy(reinterpret_cast(ptr)); +} + + +#endif // SigningKey_HPP diff --git a/bindings/cpp/Struct.d.hpp b/bindings/cpp/Struct.d.hpp new file mode 100644 index 0000000..7fbc9e0 --- /dev/null +++ b/bindings/cpp/Struct.d.hpp @@ -0,0 +1,69 @@ +#ifndef Struct_D_HPP +#define Struct_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Struct; +} // namespace capi +} // namespace + +/** + * Represents a Dojo struct + */ +class Struct { +public: + + /** + * Gets the struct name + */ + inline std::string name() const; + template + inline void name_write(W& writeable_output) const; + + /** + * Gets the number of children (members) + */ + inline uint32_t children_count() const; + + /** + * Creates a new struct from JSON schema + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the struct to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Struct* AsFFI() const; + inline diplomat::capi::Struct* AsFFI(); + inline static const Struct* FromFFI(const diplomat::capi::Struct* ptr); + inline static Struct* FromFFI(diplomat::capi::Struct* ptr); + inline static void operator delete(void* ptr); +private: + Struct() = delete; + Struct(const Struct&) = delete; + Struct(Struct&&) noexcept = delete; + Struct operator=(const Struct&) = delete; + Struct operator=(Struct&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Struct_D_HPP diff --git a/bindings/cpp/Struct.hpp b/bindings/cpp/Struct.hpp new file mode 100644 index 0000000..5852284 --- /dev/null +++ b/bindings/cpp/Struct.hpp @@ -0,0 +1,98 @@ +#ifndef Struct_HPP +#define Struct_HPP + +#include "Struct.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Struct_name(const diplomat::capi::Struct* self, diplomat::capi::DiplomatWrite* write); + + uint32_t Struct_children_count(const diplomat::capi::Struct* self); + + typedef struct Struct_from_json_result {union {diplomat::capi::Struct* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Struct_from_json_result; + Struct_from_json_result Struct_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Struct_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Struct_to_json_result; + Struct_to_json_result Struct_to_json(const diplomat::capi::Struct* self, diplomat::capi::DiplomatWrite* write); + + void Struct_destroy(Struct* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Struct::name() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Struct_name(this->AsFFI(), + &write); + return output; +} +template +inline void Struct::name_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Struct_name(this->AsFFI(), + &write); +} + +inline uint32_t Struct::children_count() const { + auto result = diplomat::capi::Struct_children_count(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> Struct::from_json(std::string_view json) { + auto result = diplomat::capi::Struct_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Struct::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Struct::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Struct_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Struct::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Struct_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Struct* Struct::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Struct* Struct::AsFFI() { + return reinterpret_cast(this); +} + +inline const Struct* Struct::FromFFI(const diplomat::capi::Struct* ptr) { + return reinterpret_cast(ptr); +} + +inline Struct* Struct::FromFFI(diplomat::capi::Struct* ptr) { + return reinterpret_cast(ptr); +} + +inline void Struct::operator delete(void* ptr) { + diplomat::capi::Struct_destroy(reinterpret_cast(ptr)); +} + + +#endif // Struct_HPP diff --git a/bindings/cpp/Subscription.d.hpp b/bindings/cpp/Subscription.d.hpp new file mode 100644 index 0000000..ca1ca65 --- /dev/null +++ b/bindings/cpp/Subscription.d.hpp @@ -0,0 +1,47 @@ +#ifndef Subscription_D_HPP +#define Subscription_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + struct Subscription; +} // namespace capi +} // namespace + +/** + * Subscription handle for managing event streams + */ +class Subscription { +public: + + /** + * Gets the subscription ID + */ + inline uint64_t id() const; + + inline const diplomat::capi::Subscription* AsFFI() const; + inline diplomat::capi::Subscription* AsFFI(); + inline static const Subscription* FromFFI(const diplomat::capi::Subscription* ptr); + inline static Subscription* FromFFI(diplomat::capi::Subscription* ptr); + inline static void operator delete(void* ptr); +private: + Subscription() = delete; + Subscription(const Subscription&) = delete; + Subscription(Subscription&&) noexcept = delete; + Subscription operator=(const Subscription&) = delete; + Subscription operator=(Subscription&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Subscription_D_HPP diff --git a/bindings/cpp/Subscription.hpp b/bindings/cpp/Subscription.hpp new file mode 100644 index 0000000..b84f2a5 --- /dev/null +++ b/bindings/cpp/Subscription.hpp @@ -0,0 +1,55 @@ +#ifndef Subscription_HPP +#define Subscription_HPP + +#include "Subscription.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + uint64_t Subscription_id(const diplomat::capi::Subscription* self); + + void Subscription_destroy(Subscription* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline uint64_t Subscription::id() const { + auto result = diplomat::capi::Subscription_id(this->AsFFI()); + return result; +} + +inline const diplomat::capi::Subscription* Subscription::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Subscription* Subscription::AsFFI() { + return reinterpret_cast(this); +} + +inline const Subscription* Subscription::FromFFI(const diplomat::capi::Subscription* ptr) { + return reinterpret_cast(ptr); +} + +inline Subscription* Subscription::FromFFI(diplomat::capi::Subscription* ptr) { + return reinterpret_cast(ptr); +} + +inline void Subscription::operator delete(void* ptr) { + diplomat::capi::Subscription_destroy(reinterpret_cast(ptr)); +} + + +#endif // Subscription_HPP diff --git a/bindings/cpp/Token.d.hpp b/bindings/cpp/Token.d.hpp new file mode 100644 index 0000000..90b510d --- /dev/null +++ b/bindings/cpp/Token.d.hpp @@ -0,0 +1,90 @@ +#ifndef Token_D_HPP +#define Token_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Token; +} // namespace capi +} // namespace + +/** + * Represents a token (ERC20, ERC721, or ERC1155) + */ +class Token { +public: + + /** + * Gets the contract address (hex) + */ + inline std::string contract_address() const; + template + inline void contract_address_write(W& writeable_output) const; + + /** + * Gets the token name + */ + inline std::string name() const; + template + inline void name_write(W& writeable_output) const; + + /** + * Gets the token symbol + */ + inline std::string symbol() const; + template + inline void symbol_write(W& writeable_output) const; + + /** + * Gets the token decimals + */ + inline uint8_t decimals() const; + + /** + * Gets the metadata as JSON string + */ + inline std::string metadata() const; + template + inline void metadata_write(W& writeable_output) const; + + /** + * Creates a token from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the token to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Token* AsFFI() const; + inline diplomat::capi::Token* AsFFI(); + inline static const Token* FromFFI(const diplomat::capi::Token* ptr); + inline static Token* FromFFI(diplomat::capi::Token* ptr); + inline static void operator delete(void* ptr); +private: + Token() = delete; + Token(const Token&) = delete; + Token(Token&&) noexcept = delete; + Token operator=(const Token&) = delete; + Token operator=(Token&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Token_D_HPP diff --git a/bindings/cpp/Token.hpp b/bindings/cpp/Token.hpp new file mode 100644 index 0000000..4c63d84 --- /dev/null +++ b/bindings/cpp/Token.hpp @@ -0,0 +1,146 @@ +#ifndef Token_HPP +#define Token_HPP + +#include "Token.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Token_contract_address(const diplomat::capi::Token* self, diplomat::capi::DiplomatWrite* write); + + void Token_name(const diplomat::capi::Token* self, diplomat::capi::DiplomatWrite* write); + + void Token_symbol(const diplomat::capi::Token* self, diplomat::capi::DiplomatWrite* write); + + uint8_t Token_decimals(const diplomat::capi::Token* self); + + void Token_metadata(const diplomat::capi::Token* self, diplomat::capi::DiplomatWrite* write); + + typedef struct Token_from_json_result {union {diplomat::capi::Token* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Token_from_json_result; + Token_from_json_result Token_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Token_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Token_to_json_result; + Token_to_json_result Token_to_json(const diplomat::capi::Token* self, diplomat::capi::DiplomatWrite* write); + + void Token_destroy(Token* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Token::contract_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Token_contract_address(this->AsFFI(), + &write); + return output; +} +template +inline void Token::contract_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Token_contract_address(this->AsFFI(), + &write); +} + +inline std::string Token::name() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Token_name(this->AsFFI(), + &write); + return output; +} +template +inline void Token::name_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Token_name(this->AsFFI(), + &write); +} + +inline std::string Token::symbol() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Token_symbol(this->AsFFI(), + &write); + return output; +} +template +inline void Token::symbol_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Token_symbol(this->AsFFI(), + &write); +} + +inline uint8_t Token::decimals() const { + auto result = diplomat::capi::Token_decimals(this->AsFFI()); + return result; +} + +inline std::string Token::metadata() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Token_metadata(this->AsFFI(), + &write); + return output; +} +template +inline void Token::metadata_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Token_metadata(this->AsFFI(), + &write); +} + +inline diplomat::result, std::unique_ptr> Token::from_json(std::string_view json) { + auto result = diplomat::capi::Token_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Token::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Token::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Token_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Token::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Token_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Token* Token::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Token* Token::AsFFI() { + return reinterpret_cast(this); +} + +inline const Token* Token::FromFFI(const diplomat::capi::Token* ptr) { + return reinterpret_cast(ptr); +} + +inline Token* Token::FromFFI(diplomat::capi::Token* ptr) { + return reinterpret_cast(ptr); +} + +inline void Token::operator delete(void* ptr) { + diplomat::capi::Token_destroy(reinterpret_cast(ptr)); +} + + +#endif // Token_HPP diff --git a/bindings/cpp/TokenBalance.d.hpp b/bindings/cpp/TokenBalance.d.hpp new file mode 100644 index 0000000..bd55b78 --- /dev/null +++ b/bindings/cpp/TokenBalance.d.hpp @@ -0,0 +1,78 @@ +#ifndef TokenBalance_D_HPP +#define TokenBalance_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct TokenBalance; +} // namespace capi +} // namespace + +/** + * Represents a token balance for an account + */ +class TokenBalance { +public: + + /** + * Gets the account address (hex) + */ + inline std::string account_address() const; + template + inline void account_address_write(W& writeable_output) const; + + /** + * Gets the contract address (hex) + */ + inline std::string contract_address() const; + template + inline void contract_address_write(W& writeable_output) const; + + /** + * Gets the balance as a string + */ + inline std::string balance() const; + template + inline void balance_write(W& writeable_output) const; + + /** + * Creates a token balance from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the token balance to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::TokenBalance* AsFFI() const; + inline diplomat::capi::TokenBalance* AsFFI(); + inline static const TokenBalance* FromFFI(const diplomat::capi::TokenBalance* ptr); + inline static TokenBalance* FromFFI(diplomat::capi::TokenBalance* ptr); + inline static void operator delete(void* ptr); +private: + TokenBalance() = delete; + TokenBalance(const TokenBalance&) = delete; + TokenBalance(TokenBalance&&) noexcept = delete; + TokenBalance operator=(const TokenBalance&) = delete; + TokenBalance operator=(TokenBalance&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // TokenBalance_D_HPP diff --git a/bindings/cpp/TokenBalance.hpp b/bindings/cpp/TokenBalance.hpp new file mode 100644 index 0000000..113d788 --- /dev/null +++ b/bindings/cpp/TokenBalance.hpp @@ -0,0 +1,123 @@ +#ifndef TokenBalance_HPP +#define TokenBalance_HPP + +#include "TokenBalance.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void TokenBalance_account_address(const diplomat::capi::TokenBalance* self, diplomat::capi::DiplomatWrite* write); + + void TokenBalance_contract_address(const diplomat::capi::TokenBalance* self, diplomat::capi::DiplomatWrite* write); + + void TokenBalance_balance(const diplomat::capi::TokenBalance* self, diplomat::capi::DiplomatWrite* write); + + typedef struct TokenBalance_from_json_result {union {diplomat::capi::TokenBalance* ok; diplomat::capi::DojoError* err;}; bool is_ok;} TokenBalance_from_json_result; + TokenBalance_from_json_result TokenBalance_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct TokenBalance_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} TokenBalance_to_json_result; + TokenBalance_to_json_result TokenBalance_to_json(const diplomat::capi::TokenBalance* self, diplomat::capi::DiplomatWrite* write); + + void TokenBalance_destroy(TokenBalance* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string TokenBalance::account_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::TokenBalance_account_address(this->AsFFI(), + &write); + return output; +} +template +inline void TokenBalance::account_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::TokenBalance_account_address(this->AsFFI(), + &write); +} + +inline std::string TokenBalance::contract_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::TokenBalance_contract_address(this->AsFFI(), + &write); + return output; +} +template +inline void TokenBalance::contract_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::TokenBalance_contract_address(this->AsFFI(), + &write); +} + +inline std::string TokenBalance::balance() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::TokenBalance_balance(this->AsFFI(), + &write); + return output; +} +template +inline void TokenBalance::balance_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::TokenBalance_balance(this->AsFFI(), + &write); +} + +inline diplomat::result, std::unique_ptr> TokenBalance::from_json(std::string_view json) { + auto result = diplomat::capi::TokenBalance_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(TokenBalance::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> TokenBalance::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::TokenBalance_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> TokenBalance::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::TokenBalance_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::TokenBalance* TokenBalance::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::TokenBalance* TokenBalance::AsFFI() { + return reinterpret_cast(this); +} + +inline const TokenBalance* TokenBalance::FromFFI(const diplomat::capi::TokenBalance* ptr) { + return reinterpret_cast(ptr); +} + +inline TokenBalance* TokenBalance::FromFFI(diplomat::capi::TokenBalance* ptr) { + return reinterpret_cast(ptr); +} + +inline void TokenBalance::operator delete(void* ptr) { + diplomat::capi::TokenBalance_destroy(reinterpret_cast(ptr)); +} + + +#endif // TokenBalance_HPP diff --git a/bindings/cpp/TokenContract.d.hpp b/bindings/cpp/TokenContract.d.hpp new file mode 100644 index 0000000..8e9ae6d --- /dev/null +++ b/bindings/cpp/TokenContract.d.hpp @@ -0,0 +1,71 @@ +#ifndef TokenContract_D_HPP +#define TokenContract_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct TokenContract; +} // namespace capi +} // namespace + +/** + * Represents a token contract + */ +class TokenContract { +public: + + /** + * Gets the contract address (hex) + */ + inline std::string contract_address() const; + template + inline void contract_address_write(W& writeable_output) const; + + /** + * Gets the contract type as string + */ + inline std::string contract_type() const; + template + inline void contract_type_write(W& writeable_output) const; + + /** + * Creates a token contract from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the token contract to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::TokenContract* AsFFI() const; + inline diplomat::capi::TokenContract* AsFFI(); + inline static const TokenContract* FromFFI(const diplomat::capi::TokenContract* ptr); + inline static TokenContract* FromFFI(diplomat::capi::TokenContract* ptr); + inline static void operator delete(void* ptr); +private: + TokenContract() = delete; + TokenContract(const TokenContract&) = delete; + TokenContract(TokenContract&&) noexcept = delete; + TokenContract operator=(const TokenContract&) = delete; + TokenContract operator=(TokenContract&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // TokenContract_D_HPP diff --git a/bindings/cpp/TokenContract.hpp b/bindings/cpp/TokenContract.hpp new file mode 100644 index 0000000..66e7a05 --- /dev/null +++ b/bindings/cpp/TokenContract.hpp @@ -0,0 +1,107 @@ +#ifndef TokenContract_HPP +#define TokenContract_HPP + +#include "TokenContract.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void TokenContract_contract_address(const diplomat::capi::TokenContract* self, diplomat::capi::DiplomatWrite* write); + + void TokenContract_contract_type(const diplomat::capi::TokenContract* self, diplomat::capi::DiplomatWrite* write); + + typedef struct TokenContract_from_json_result {union {diplomat::capi::TokenContract* ok; diplomat::capi::DojoError* err;}; bool is_ok;} TokenContract_from_json_result; + TokenContract_from_json_result TokenContract_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct TokenContract_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} TokenContract_to_json_result; + TokenContract_to_json_result TokenContract_to_json(const diplomat::capi::TokenContract* self, diplomat::capi::DiplomatWrite* write); + + void TokenContract_destroy(TokenContract* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string TokenContract::contract_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::TokenContract_contract_address(this->AsFFI(), + &write); + return output; +} +template +inline void TokenContract::contract_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::TokenContract_contract_address(this->AsFFI(), + &write); +} + +inline std::string TokenContract::contract_type() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::TokenContract_contract_type(this->AsFFI(), + &write); + return output; +} +template +inline void TokenContract::contract_type_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::TokenContract_contract_type(this->AsFFI(), + &write); +} + +inline diplomat::result, std::unique_ptr> TokenContract::from_json(std::string_view json) { + auto result = diplomat::capi::TokenContract_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(TokenContract::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> TokenContract::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::TokenContract_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> TokenContract::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::TokenContract_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::TokenContract* TokenContract::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::TokenContract* TokenContract::AsFFI() { + return reinterpret_cast(this); +} + +inline const TokenContract* TokenContract::FromFFI(const diplomat::capi::TokenContract* ptr) { + return reinterpret_cast(ptr); +} + +inline TokenContract* TokenContract::FromFFI(diplomat::capi::TokenContract* ptr) { + return reinterpret_cast(ptr); +} + +inline void TokenContract::operator delete(void* ptr) { + diplomat::capi::TokenContract_destroy(reinterpret_cast(ptr)); +} + + +#endif // TokenContract_HPP diff --git a/bindings/cpp/TokenTransfer.d.hpp b/bindings/cpp/TokenTransfer.d.hpp new file mode 100644 index 0000000..de20660 --- /dev/null +++ b/bindings/cpp/TokenTransfer.d.hpp @@ -0,0 +1,90 @@ +#ifndef TokenTransfer_D_HPP +#define TokenTransfer_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct TokenTransfer; +} // namespace capi +} // namespace + +/** + * Represents a token transfer event + */ +class TokenTransfer { +public: + + /** + * Gets the from address (hex) + */ + inline std::string from_address() const; + template + inline void from_address_write(W& writeable_output) const; + + /** + * Gets the to address (hex) + */ + inline std::string to_address() const; + template + inline void to_address_write(W& writeable_output) const; + + /** + * Gets the contract address (hex) + */ + inline std::string contract_address() const; + template + inline void contract_address_write(W& writeable_output) const; + + /** + * Gets the amount as a string + */ + inline std::string amount() const; + template + inline void amount_write(W& writeable_output) const; + + /** + * Gets the executed_at timestamp + */ + inline uint64_t executed_at() const; + + /** + * Creates a token transfer from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the token transfer to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::TokenTransfer* AsFFI() const; + inline diplomat::capi::TokenTransfer* AsFFI(); + inline static const TokenTransfer* FromFFI(const diplomat::capi::TokenTransfer* ptr); + inline static TokenTransfer* FromFFI(diplomat::capi::TokenTransfer* ptr); + inline static void operator delete(void* ptr); +private: + TokenTransfer() = delete; + TokenTransfer(const TokenTransfer&) = delete; + TokenTransfer(TokenTransfer&&) noexcept = delete; + TokenTransfer operator=(const TokenTransfer&) = delete; + TokenTransfer operator=(TokenTransfer&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // TokenTransfer_D_HPP diff --git a/bindings/cpp/TokenTransfer.hpp b/bindings/cpp/TokenTransfer.hpp new file mode 100644 index 0000000..8473d04 --- /dev/null +++ b/bindings/cpp/TokenTransfer.hpp @@ -0,0 +1,146 @@ +#ifndef TokenTransfer_HPP +#define TokenTransfer_HPP + +#include "TokenTransfer.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void TokenTransfer_from_address(const diplomat::capi::TokenTransfer* self, diplomat::capi::DiplomatWrite* write); + + void TokenTransfer_to_address(const diplomat::capi::TokenTransfer* self, diplomat::capi::DiplomatWrite* write); + + void TokenTransfer_contract_address(const diplomat::capi::TokenTransfer* self, diplomat::capi::DiplomatWrite* write); + + void TokenTransfer_amount(const diplomat::capi::TokenTransfer* self, diplomat::capi::DiplomatWrite* write); + + uint64_t TokenTransfer_executed_at(const diplomat::capi::TokenTransfer* self); + + typedef struct TokenTransfer_from_json_result {union {diplomat::capi::TokenTransfer* ok; diplomat::capi::DojoError* err;}; bool is_ok;} TokenTransfer_from_json_result; + TokenTransfer_from_json_result TokenTransfer_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct TokenTransfer_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} TokenTransfer_to_json_result; + TokenTransfer_to_json_result TokenTransfer_to_json(const diplomat::capi::TokenTransfer* self, diplomat::capi::DiplomatWrite* write); + + void TokenTransfer_destroy(TokenTransfer* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string TokenTransfer::from_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::TokenTransfer_from_address(this->AsFFI(), + &write); + return output; +} +template +inline void TokenTransfer::from_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::TokenTransfer_from_address(this->AsFFI(), + &write); +} + +inline std::string TokenTransfer::to_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::TokenTransfer_to_address(this->AsFFI(), + &write); + return output; +} +template +inline void TokenTransfer::to_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::TokenTransfer_to_address(this->AsFFI(), + &write); +} + +inline std::string TokenTransfer::contract_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::TokenTransfer_contract_address(this->AsFFI(), + &write); + return output; +} +template +inline void TokenTransfer::contract_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::TokenTransfer_contract_address(this->AsFFI(), + &write); +} + +inline std::string TokenTransfer::amount() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::TokenTransfer_amount(this->AsFFI(), + &write); + return output; +} +template +inline void TokenTransfer::amount_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::TokenTransfer_amount(this->AsFFI(), + &write); +} + +inline uint64_t TokenTransfer::executed_at() const { + auto result = diplomat::capi::TokenTransfer_executed_at(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> TokenTransfer::from_json(std::string_view json) { + auto result = diplomat::capi::TokenTransfer_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(TokenTransfer::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> TokenTransfer::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::TokenTransfer_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> TokenTransfer::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::TokenTransfer_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::TokenTransfer* TokenTransfer::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::TokenTransfer* TokenTransfer::AsFFI() { + return reinterpret_cast(this); +} + +inline const TokenTransfer* TokenTransfer::FromFFI(const diplomat::capi::TokenTransfer* ptr) { + return reinterpret_cast(ptr); +} + +inline TokenTransfer* TokenTransfer::FromFFI(diplomat::capi::TokenTransfer* ptr) { + return reinterpret_cast(ptr); +} + +inline void TokenTransfer::operator delete(void* ptr) { + diplomat::capi::TokenTransfer_destroy(reinterpret_cast(ptr)); +} + + +#endif // TokenTransfer_HPP diff --git a/bindings/cpp/ToriiClient.d.hpp b/bindings/cpp/ToriiClient.d.hpp new file mode 100644 index 0000000..5390858 --- /dev/null +++ b/bindings/cpp/ToriiClient.d.hpp @@ -0,0 +1,66 @@ +#ifndef ToriiClient_D_HPP +#define ToriiClient_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; +namespace diplomat::capi { struct FieldElement; } +class FieldElement; + + +namespace diplomat { +namespace capi { + struct ToriiClient; +} // namespace capi +} // namespace + +/** + * Opaque handle to a Torii client instance + */ +class ToriiClient { +public: + + /** + * Creates a new Torii client instance + */ + inline static diplomat::result, std::unique_ptr> new_(std::string_view torii_url); + + /** + * Gets information about the Torii server + */ + inline diplomat::result> info() const; + template + inline diplomat::result> info_write(W& writeable_output) const; + + /** + * Publishes a message to the network + */ + inline diplomat::result> publish_message(std::string_view message_json, const FieldElement& signature_r, const FieldElement& signature_s, const FieldElement& world_address) const; + template + inline diplomat::result> publish_message_write(std::string_view message_json, const FieldElement& signature_r, const FieldElement& signature_s, const FieldElement& world_address, W& writeable_output) const; + + inline const diplomat::capi::ToriiClient* AsFFI() const; + inline diplomat::capi::ToriiClient* AsFFI(); + inline static const ToriiClient* FromFFI(const diplomat::capi::ToriiClient* ptr); + inline static ToriiClient* FromFFI(diplomat::capi::ToriiClient* ptr); + inline static void operator delete(void* ptr); +private: + ToriiClient() = delete; + ToriiClient(const ToriiClient&) = delete; + ToriiClient(ToriiClient&&) noexcept = delete; + ToriiClient operator=(const ToriiClient&) = delete; + ToriiClient operator=(ToriiClient&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // ToriiClient_D_HPP diff --git a/bindings/cpp/ToriiClient.hpp b/bindings/cpp/ToriiClient.hpp new file mode 100644 index 0000000..8390f60 --- /dev/null +++ b/bindings/cpp/ToriiClient.hpp @@ -0,0 +1,102 @@ +#ifndef ToriiClient_HPP +#define ToriiClient_HPP + +#include "ToriiClient.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "FieldElement.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + typedef struct ToriiClient_new_result {union {diplomat::capi::ToriiClient* ok; diplomat::capi::DojoError* err;}; bool is_ok;} ToriiClient_new_result; + ToriiClient_new_result ToriiClient_new(diplomat::capi::DiplomatStringView torii_url); + + typedef struct ToriiClient_info_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} ToriiClient_info_result; + ToriiClient_info_result ToriiClient_info(const diplomat::capi::ToriiClient* self, diplomat::capi::DiplomatWrite* write); + + typedef struct ToriiClient_publish_message_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} ToriiClient_publish_message_result; + ToriiClient_publish_message_result ToriiClient_publish_message(const diplomat::capi::ToriiClient* self, diplomat::capi::DiplomatStringView message_json, const diplomat::capi::FieldElement* signature_r, const diplomat::capi::FieldElement* signature_s, const diplomat::capi::FieldElement* world_address, diplomat::capi::DiplomatWrite* write); + + void ToriiClient_destroy(ToriiClient* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::result, std::unique_ptr> ToriiClient::new_(std::string_view torii_url) { + auto result = diplomat::capi::ToriiClient_new({torii_url.data(), torii_url.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(ToriiClient::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> ToriiClient::info() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::ToriiClient_info(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> ToriiClient::info_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::ToriiClient_info(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> ToriiClient::publish_message(std::string_view message_json, const FieldElement& signature_r, const FieldElement& signature_s, const FieldElement& world_address) const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::ToriiClient_publish_message(this->AsFFI(), + {message_json.data(), message_json.size()}, + signature_r.AsFFI(), + signature_s.AsFFI(), + world_address.AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> ToriiClient::publish_message_write(std::string_view message_json, const FieldElement& signature_r, const FieldElement& signature_s, const FieldElement& world_address, W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::ToriiClient_publish_message(this->AsFFI(), + {message_json.data(), message_json.size()}, + signature_r.AsFFI(), + signature_s.AsFFI(), + world_address.AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::ToriiClient* ToriiClient::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::ToriiClient* ToriiClient::AsFFI() { + return reinterpret_cast(this); +} + +inline const ToriiClient* ToriiClient::FromFFI(const diplomat::capi::ToriiClient* ptr) { + return reinterpret_cast(ptr); +} + +inline ToriiClient* ToriiClient::FromFFI(diplomat::capi::ToriiClient* ptr) { + return reinterpret_cast(ptr); +} + +inline void ToriiClient::operator delete(void* ptr) { + diplomat::capi::ToriiClient_destroy(reinterpret_cast(ptr)); +} + + +#endif // ToriiClient_HPP diff --git a/bindings/cpp/Transaction.d.hpp b/bindings/cpp/Transaction.d.hpp new file mode 100644 index 0000000..2310d22 --- /dev/null +++ b/bindings/cpp/Transaction.d.hpp @@ -0,0 +1,102 @@ +#ifndef Transaction_D_HPP +#define Transaction_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct Transaction; +} // namespace capi +} // namespace + +/** + * Represents a transaction + */ +class Transaction { +public: + + /** + * Gets the transaction hash (hex) + */ + inline std::string transaction_hash() const; + template + inline void transaction_hash_write(W& writeable_output) const; + + /** + * Gets the sender address (hex) + */ + inline std::string sender_address() const; + template + inline void sender_address_write(W& writeable_output) const; + + /** + * Gets the max fee as string + */ + inline std::string max_fee() const; + template + inline void max_fee_write(W& writeable_output) const; + + /** + * Gets the signature as JSON array string + */ + inline std::string signature() const; + template + inline void signature_write(W& writeable_output) const; + + /** + * Gets the nonce as string + */ + inline std::string nonce() const; + template + inline void nonce_write(W& writeable_output) const; + + /** + * Gets the block timestamp + */ + inline uint64_t block_timestamp() const; + + /** + * Gets the block number + */ + inline uint64_t block_number() const; + + /** + * Creates a transaction from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the transaction to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::Transaction* AsFFI() const; + inline diplomat::capi::Transaction* AsFFI(); + inline static const Transaction* FromFFI(const diplomat::capi::Transaction* ptr); + inline static Transaction* FromFFI(diplomat::capi::Transaction* ptr); + inline static void operator delete(void* ptr); +private: + Transaction() = delete; + Transaction(const Transaction&) = delete; + Transaction(Transaction&&) noexcept = delete; + Transaction operator=(const Transaction&) = delete; + Transaction operator=(Transaction&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // Transaction_D_HPP diff --git a/bindings/cpp/Transaction.hpp b/bindings/cpp/Transaction.hpp new file mode 100644 index 0000000..0d009a7 --- /dev/null +++ b/bindings/cpp/Transaction.hpp @@ -0,0 +1,169 @@ +#ifndef Transaction_HPP +#define Transaction_HPP + +#include "Transaction.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void Transaction_transaction_hash(const diplomat::capi::Transaction* self, diplomat::capi::DiplomatWrite* write); + + void Transaction_sender_address(const diplomat::capi::Transaction* self, diplomat::capi::DiplomatWrite* write); + + void Transaction_max_fee(const diplomat::capi::Transaction* self, diplomat::capi::DiplomatWrite* write); + + void Transaction_signature(const diplomat::capi::Transaction* self, diplomat::capi::DiplomatWrite* write); + + void Transaction_nonce(const diplomat::capi::Transaction* self, diplomat::capi::DiplomatWrite* write); + + uint64_t Transaction_block_timestamp(const diplomat::capi::Transaction* self); + + uint64_t Transaction_block_number(const diplomat::capi::Transaction* self); + + typedef struct Transaction_from_json_result {union {diplomat::capi::Transaction* ok; diplomat::capi::DojoError* err;}; bool is_ok;} Transaction_from_json_result; + Transaction_from_json_result Transaction_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct Transaction_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} Transaction_to_json_result; + Transaction_to_json_result Transaction_to_json(const diplomat::capi::Transaction* self, diplomat::capi::DiplomatWrite* write); + + void Transaction_destroy(Transaction* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string Transaction::transaction_hash() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Transaction_transaction_hash(this->AsFFI(), + &write); + return output; +} +template +inline void Transaction::transaction_hash_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Transaction_transaction_hash(this->AsFFI(), + &write); +} + +inline std::string Transaction::sender_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Transaction_sender_address(this->AsFFI(), + &write); + return output; +} +template +inline void Transaction::sender_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Transaction_sender_address(this->AsFFI(), + &write); +} + +inline std::string Transaction::max_fee() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Transaction_max_fee(this->AsFFI(), + &write); + return output; +} +template +inline void Transaction::max_fee_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Transaction_max_fee(this->AsFFI(), + &write); +} + +inline std::string Transaction::signature() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Transaction_signature(this->AsFFI(), + &write); + return output; +} +template +inline void Transaction::signature_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Transaction_signature(this->AsFFI(), + &write); +} + +inline std::string Transaction::nonce() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::Transaction_nonce(this->AsFFI(), + &write); + return output; +} +template +inline void Transaction::nonce_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::Transaction_nonce(this->AsFFI(), + &write); +} + +inline uint64_t Transaction::block_timestamp() const { + auto result = diplomat::capi::Transaction_block_timestamp(this->AsFFI()); + return result; +} + +inline uint64_t Transaction::block_number() const { + auto result = diplomat::capi::Transaction_block_number(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> Transaction::from_json(std::string_view json) { + auto result = diplomat::capi::Transaction_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(Transaction::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> Transaction::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::Transaction_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> Transaction::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::Transaction_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::Transaction* Transaction::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::Transaction* Transaction::AsFFI() { + return reinterpret_cast(this); +} + +inline const Transaction* Transaction::FromFFI(const diplomat::capi::Transaction* ptr) { + return reinterpret_cast(ptr); +} + +inline Transaction* Transaction::FromFFI(diplomat::capi::Transaction* ptr) { + return reinterpret_cast(ptr); +} + +inline void Transaction::operator delete(void* ptr) { + diplomat::capi::Transaction_destroy(reinterpret_cast(ptr)); +} + + +#endif // Transaction_HPP diff --git a/bindings/cpp/TypedData.d.hpp b/bindings/cpp/TypedData.d.hpp new file mode 100644 index 0000000..532d9f5 --- /dev/null +++ b/bindings/cpp/TypedData.d.hpp @@ -0,0 +1,50 @@ +#ifndef TypedData_D_HPP +#define TypedData_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct TypedData; +} // namespace capi +} // namespace + +/** + * Represents a typed data structure for EIP-712 style signing + */ +class TypedData { +public: + + /** + * Creates a new TypedData from JSON string + */ + inline static diplomat::result, std::unique_ptr> new_from_json(std::string_view json); + + inline const diplomat::capi::TypedData* AsFFI() const; + inline diplomat::capi::TypedData* AsFFI(); + inline static const TypedData* FromFFI(const diplomat::capi::TypedData* ptr); + inline static TypedData* FromFFI(diplomat::capi::TypedData* ptr); + inline static void operator delete(void* ptr); +private: + TypedData() = delete; + TypedData(const TypedData&) = delete; + TypedData(TypedData&&) noexcept = delete; + TypedData operator=(const TypedData&) = delete; + TypedData operator=(TypedData&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // TypedData_D_HPP diff --git a/bindings/cpp/TypedData.hpp b/bindings/cpp/TypedData.hpp new file mode 100644 index 0000000..9d1ac7d --- /dev/null +++ b/bindings/cpp/TypedData.hpp @@ -0,0 +1,57 @@ +#ifndef TypedData_HPP +#define TypedData_HPP + +#include "TypedData.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + typedef struct TypedData_new_from_json_result {union {diplomat::capi::TypedData* ok; diplomat::capi::DojoError* err;}; bool is_ok;} TypedData_new_from_json_result; + TypedData_new_from_json_result TypedData_new_from_json(diplomat::capi::DiplomatStringView json); + + void TypedData_destroy(TypedData* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::result, std::unique_ptr> TypedData::new_from_json(std::string_view json) { + auto result = diplomat::capi::TypedData_new_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(TypedData::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::TypedData* TypedData::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::TypedData* TypedData::AsFFI() { + return reinterpret_cast(this); +} + +inline const TypedData* TypedData::FromFFI(const diplomat::capi::TypedData* ptr) { + return reinterpret_cast(ptr); +} + +inline TypedData* TypedData::FromFFI(diplomat::capi::TypedData* ptr) { + return reinterpret_cast(ptr); +} + +inline void TypedData::operator delete(void* ptr) { + diplomat::capi::TypedData_destroy(reinterpret_cast(ptr)); +} + + +#endif // TypedData_HPP diff --git a/bindings/cpp/U256.d.hpp b/bindings/cpp/U256.d.hpp new file mode 100644 index 0000000..b8e8961 --- /dev/null +++ b/bindings/cpp/U256.d.hpp @@ -0,0 +1,67 @@ +#ifndef U256_D_HPP +#define U256_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct U256; +} // namespace capi +} // namespace + +/** + * Represents a 256-bit unsigned integer + */ +class U256 { +public: + + /** + * Creates a new U256 from a hexadecimal string + */ + inline static diplomat::result, std::unique_ptr> new_from_hex(std::string_view hex); + + /** + * Creates a new U256 from big-endian bytes + */ + inline static diplomat::result, std::unique_ptr> new_from_bytes(diplomat::span bytes); + + /** + * Returns the U256 as a hexadecimal string + */ + inline std::string to_hex() const; + template + inline void to_hex_write(W& writeable_output) const; + + /** + * Returns the U256 as bytes (big-endian) + */ + inline void to_bytes(diplomat::span result) const; + + inline const diplomat::capi::U256* AsFFI() const; + inline diplomat::capi::U256* AsFFI(); + inline static const U256* FromFFI(const diplomat::capi::U256* ptr); + inline static U256* FromFFI(diplomat::capi::U256* ptr); + inline static void operator delete(void* ptr); +private: + U256() = delete; + U256(const U256&) = delete; + U256(U256&&) noexcept = delete; + U256 operator=(const U256&) = delete; + U256 operator=(U256&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // U256_D_HPP diff --git a/bindings/cpp/U256.hpp b/bindings/cpp/U256.hpp new file mode 100644 index 0000000..70e911a --- /dev/null +++ b/bindings/cpp/U256.hpp @@ -0,0 +1,88 @@ +#ifndef U256_HPP +#define U256_HPP + +#include "U256.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + typedef struct U256_new_from_hex_result {union {diplomat::capi::U256* ok; diplomat::capi::DojoError* err;}; bool is_ok;} U256_new_from_hex_result; + U256_new_from_hex_result U256_new_from_hex(diplomat::capi::DiplomatStringView hex); + + typedef struct U256_new_from_bytes_result {union {diplomat::capi::U256* ok; diplomat::capi::DojoError* err;}; bool is_ok;} U256_new_from_bytes_result; + U256_new_from_bytes_result U256_new_from_bytes(diplomat::capi::DiplomatU8View bytes); + + void U256_to_hex(const diplomat::capi::U256* self, diplomat::capi::DiplomatWrite* write); + + void U256_to_bytes(const diplomat::capi::U256* self, diplomat::capi::DiplomatU8ViewMut result); + + void U256_destroy(U256* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline diplomat::result, std::unique_ptr> U256::new_from_hex(std::string_view hex) { + auto result = diplomat::capi::U256_new_from_hex({hex.data(), hex.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(U256::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result, std::unique_ptr> U256::new_from_bytes(diplomat::span bytes) { + auto result = diplomat::capi::U256_new_from_bytes({bytes.data(), bytes.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(U256::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline std::string U256::to_hex() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::U256_to_hex(this->AsFFI(), + &write); + return output; +} +template +inline void U256::to_hex_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::U256_to_hex(this->AsFFI(), + &write); +} + +inline void U256::to_bytes(diplomat::span result) const { + diplomat::capi::U256_to_bytes(this->AsFFI(), + {result.data(), result.size()}); +} + +inline const diplomat::capi::U256* U256::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::U256* U256::AsFFI() { + return reinterpret_cast(this); +} + +inline const U256* U256::FromFFI(const diplomat::capi::U256* ptr) { + return reinterpret_cast(ptr); +} + +inline U256* U256::FromFFI(diplomat::capi::U256* ptr) { + return reinterpret_cast(ptr); +} + +inline void U256::operator delete(void* ptr) { + diplomat::capi::U256_destroy(reinterpret_cast(ptr)); +} + + +#endif // U256_HPP diff --git a/bindings/cpp/VerifyingKey.d.hpp b/bindings/cpp/VerifyingKey.d.hpp new file mode 100644 index 0000000..5041997 --- /dev/null +++ b/bindings/cpp/VerifyingKey.d.hpp @@ -0,0 +1,61 @@ +#ifndef VerifyingKey_D_HPP +#define VerifyingKey_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; +namespace diplomat::capi { struct FieldElement; } +class FieldElement; +namespace diplomat::capi { struct Signature; } +class Signature; + + +namespace diplomat { +namespace capi { + struct VerifyingKey; +} // namespace capi +} // namespace + +/** + * Represents a verifying key for signature verification + */ +class VerifyingKey { +public: + + /** + * Returns the scalar value of the verifying key + */ + inline std::string scalar() const; + template + inline void scalar_write(W& writeable_output) const; + + /** + * Verifies a signature + */ + inline diplomat::result> verify(const FieldElement& hash, const Signature& signature) const; + + inline const diplomat::capi::VerifyingKey* AsFFI() const; + inline diplomat::capi::VerifyingKey* AsFFI(); + inline static const VerifyingKey* FromFFI(const diplomat::capi::VerifyingKey* ptr); + inline static VerifyingKey* FromFFI(diplomat::capi::VerifyingKey* ptr); + inline static void operator delete(void* ptr); +private: + VerifyingKey() = delete; + VerifyingKey(const VerifyingKey&) = delete; + VerifyingKey(VerifyingKey&&) noexcept = delete; + VerifyingKey operator=(const VerifyingKey&) = delete; + VerifyingKey operator=(VerifyingKey&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // VerifyingKey_D_HPP diff --git a/bindings/cpp/VerifyingKey.hpp b/bindings/cpp/VerifyingKey.hpp new file mode 100644 index 0000000..b9bb691 --- /dev/null +++ b/bindings/cpp/VerifyingKey.hpp @@ -0,0 +1,77 @@ +#ifndef VerifyingKey_HPP +#define VerifyingKey_HPP + +#include "VerifyingKey.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "FieldElement.hpp" +#include "Signature.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void VerifyingKey_scalar(const diplomat::capi::VerifyingKey* self, diplomat::capi::DiplomatWrite* write); + + typedef struct VerifyingKey_verify_result {union {bool ok; diplomat::capi::DojoError* err;}; bool is_ok;} VerifyingKey_verify_result; + VerifyingKey_verify_result VerifyingKey_verify(const diplomat::capi::VerifyingKey* self, const diplomat::capi::FieldElement* hash, const diplomat::capi::Signature* signature); + + void VerifyingKey_destroy(VerifyingKey* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string VerifyingKey::scalar() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::VerifyingKey_scalar(this->AsFFI(), + &write); + return output; +} +template +inline void VerifyingKey::scalar_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::VerifyingKey_scalar(this->AsFFI(), + &write); +} + +inline diplomat::result> VerifyingKey::verify(const FieldElement& hash, const Signature& signature) const { + auto result = diplomat::capi::VerifyingKey_verify(this->AsFFI(), + hash.AsFFI(), + signature.AsFFI()); + return result.is_ok ? diplomat::result>(diplomat::Ok(result.ok)) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::VerifyingKey* VerifyingKey::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::VerifyingKey* VerifyingKey::AsFFI() { + return reinterpret_cast(this); +} + +inline const VerifyingKey* VerifyingKey::FromFFI(const diplomat::capi::VerifyingKey* ptr) { + return reinterpret_cast(ptr); +} + +inline VerifyingKey* VerifyingKey::FromFFI(diplomat::capi::VerifyingKey* ptr) { + return reinterpret_cast(ptr); +} + +inline void VerifyingKey::operator delete(void* ptr) { + diplomat::capi::VerifyingKey_destroy(reinterpret_cast(ptr)); +} + + +#endif // VerifyingKey_HPP diff --git a/bindings/cpp/World.d.hpp b/bindings/cpp/World.d.hpp new file mode 100644 index 0000000..fbee97d --- /dev/null +++ b/bindings/cpp/World.d.hpp @@ -0,0 +1,69 @@ +#ifndef World_D_HPP +#define World_D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include "diplomat_runtime.hpp" + +namespace diplomat::capi { struct DojoError; } +class DojoError; + + +namespace diplomat { +namespace capi { + struct World; +} // namespace capi +} // namespace + +/** + * Represents a Dojo world + */ +class World { +public: + + /** + * Gets the world address (hex) + */ + inline std::string world_address() const; + template + inline void world_address_write(W& writeable_output) const; + + /** + * Gets the number of models in this world + */ + inline uint32_t models_count() const; + + /** + * Creates a new world from JSON + */ + inline static diplomat::result, std::unique_ptr> from_json(std::string_view json); + + /** + * Serializes the world to JSON + */ + inline diplomat::result> to_json() const; + template + inline diplomat::result> to_json_write(W& writeable_output) const; + + inline const diplomat::capi::World* AsFFI() const; + inline diplomat::capi::World* AsFFI(); + inline static const World* FromFFI(const diplomat::capi::World* ptr); + inline static World* FromFFI(diplomat::capi::World* ptr); + inline static void operator delete(void* ptr); +private: + World() = delete; + World(const World&) = delete; + World(World&&) noexcept = delete; + World operator=(const World&) = delete; + World operator=(World&&) noexcept = delete; + static void operator delete[](void*, size_t) = delete; +}; + + +#endif // World_D_HPP diff --git a/bindings/cpp/World.hpp b/bindings/cpp/World.hpp new file mode 100644 index 0000000..020c7b4 --- /dev/null +++ b/bindings/cpp/World.hpp @@ -0,0 +1,98 @@ +#ifndef World_HPP +#define World_HPP + +#include "World.d.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DojoError.hpp" +#include "diplomat_runtime.hpp" + + +namespace diplomat { +namespace capi { + extern "C" { + + void World_world_address(const diplomat::capi::World* self, diplomat::capi::DiplomatWrite* write); + + uint32_t World_models_count(const diplomat::capi::World* self); + + typedef struct World_from_json_result {union {diplomat::capi::World* ok; diplomat::capi::DojoError* err;}; bool is_ok;} World_from_json_result; + World_from_json_result World_from_json(diplomat::capi::DiplomatStringView json); + + typedef struct World_to_json_result {union { diplomat::capi::DojoError* err;}; bool is_ok;} World_to_json_result; + World_to_json_result World_to_json(const diplomat::capi::World* self, diplomat::capi::DiplomatWrite* write); + + void World_destroy(World* self); + + } // extern "C" +} // namespace capi +} // namespace + +inline std::string World::world_address() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + diplomat::capi::World_world_address(this->AsFFI(), + &write); + return output; +} +template +inline void World::world_address_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + diplomat::capi::World_world_address(this->AsFFI(), + &write); +} + +inline uint32_t World::models_count() const { + auto result = diplomat::capi::World_models_count(this->AsFFI()); + return result; +} + +inline diplomat::result, std::unique_ptr> World::from_json(std::string_view json) { + auto result = diplomat::capi::World_from_json({json.data(), json.size()}); + return result.is_ok ? diplomat::result, std::unique_ptr>(diplomat::Ok>(std::unique_ptr(World::FromFFI(result.ok)))) : diplomat::result, std::unique_ptr>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline diplomat::result> World::to_json() const { + std::string output; + diplomat::capi::DiplomatWrite write = diplomat::WriteFromString(output); + auto result = diplomat::capi::World_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok(std::move(output))) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} +template +inline diplomat::result> World::to_json_write(W& writeable) const { + diplomat::capi::DiplomatWrite write = diplomat::WriteTrait::Construct(writeable); + auto result = diplomat::capi::World_to_json(this->AsFFI(), + &write); + return result.is_ok ? diplomat::result>(diplomat::Ok()) : diplomat::result>(diplomat::Err>(std::unique_ptr(DojoError::FromFFI(result.err)))); +} + +inline const diplomat::capi::World* World::AsFFI() const { + return reinterpret_cast(this); +} + +inline diplomat::capi::World* World::AsFFI() { + return reinterpret_cast(this); +} + +inline const World* World::FromFFI(const diplomat::capi::World* ptr) { + return reinterpret_cast(ptr); +} + +inline World* World::FromFFI(diplomat::capi::World* ptr) { + return reinterpret_cast(ptr); +} + +inline void World::operator delete(void* ptr) { + diplomat::capi::World_destroy(reinterpret_cast(ptr)); +} + + +#endif // World_HPP diff --git a/bindings/cpp/diplomat_runtime.hpp b/bindings/cpp/diplomat_runtime.hpp new file mode 100644 index 0000000..8cd3659 --- /dev/null +++ b/bindings/cpp/diplomat_runtime.hpp @@ -0,0 +1,387 @@ +#ifndef DIPLOMAT_RUNTIME_CPP_H +#define DIPLOMAT_RUNTIME_CPP_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#if __cplusplus >= 202002L +#include +#else +#include +#endif + +namespace diplomat { + +namespace capi { +extern "C" { + +static_assert(sizeof(char) == sizeof(uint8_t), "your architecture's `char` is not 8 bits"); +static_assert(sizeof(char16_t) == sizeof(uint16_t), "your architecture's `char16_t` is not 16 bits"); +static_assert(sizeof(char32_t) == sizeof(uint32_t), "your architecture's `char32_t` is not 32 bits"); + +typedef struct DiplomatWrite { + void* context; + char* buf; + size_t len; + size_t cap; + bool grow_failed; + void (*flush)(struct DiplomatWrite*); + bool (*grow)(struct DiplomatWrite*, size_t); +} DiplomatWrite; + +bool diplomat_is_str(const char* buf, size_t len); + +#define MAKE_SLICES(name, c_ty) \ + typedef struct Diplomat##name##View { \ + const c_ty* data; \ + size_t len; \ + } Diplomat##name##View; \ + typedef struct Diplomat##name##ViewMut { \ + c_ty* data; \ + size_t len; \ + } Diplomat##name##ViewMut; \ + typedef struct Diplomat##name##Array { \ + const c_ty* data; \ + size_t len; \ + } Diplomat##name##Array; + +#define MAKE_SLICES_AND_OPTIONS(name, c_ty) \ + MAKE_SLICES(name, c_ty) \ + typedef struct Option##name {union { c_ty ok; }; bool is_ok; } Option##name; \ + typedef struct Option##name##View {union { Diplomat##name##View ok; }; bool is_ok; } Option##name##View; \ + typedef struct Option##name##ViewMut {union { Diplomat##name##ViewMut ok; }; bool is_ok; } Option##name##ViewMut; \ + typedef struct Option##name##Array {union { Diplomat##name##Array ok; }; bool is_ok; } Option##name##Array; \ + +MAKE_SLICES_AND_OPTIONS(I8, int8_t) +MAKE_SLICES_AND_OPTIONS(U8, uint8_t) +MAKE_SLICES_AND_OPTIONS(I16, int16_t) +MAKE_SLICES_AND_OPTIONS(U16, uint16_t) +MAKE_SLICES_AND_OPTIONS(I32, int32_t) +MAKE_SLICES_AND_OPTIONS(U32, uint32_t) +MAKE_SLICES_AND_OPTIONS(I64, int64_t) +MAKE_SLICES_AND_OPTIONS(U64, uint64_t) +MAKE_SLICES_AND_OPTIONS(Isize, intptr_t) +MAKE_SLICES_AND_OPTIONS(Usize, size_t) +MAKE_SLICES_AND_OPTIONS(F32, float) +MAKE_SLICES_AND_OPTIONS(F64, double) +MAKE_SLICES_AND_OPTIONS(Bool, bool) +MAKE_SLICES_AND_OPTIONS(Char, char32_t) +MAKE_SLICES_AND_OPTIONS(String, char) +MAKE_SLICES_AND_OPTIONS(String16, char16_t) +MAKE_SLICES_AND_OPTIONS(Strings, DiplomatStringView) +MAKE_SLICES_AND_OPTIONS(Strings16, DiplomatString16View) + +} // extern "C" +} // namespace capi + +extern "C" inline void _flush(capi::DiplomatWrite* w) { + std::string* string = reinterpret_cast(w->context); + string->resize(w->len); +} + +extern "C" inline bool _grow(capi::DiplomatWrite* w, uintptr_t requested) { + std::string* string = reinterpret_cast(w->context); + string->resize(requested); + w->cap = string->length(); + w->buf = &(*string)[0]; + return true; +} + +inline capi::DiplomatWrite WriteFromString(std::string& string) { + capi::DiplomatWrite w; + w.context = &string; + w.buf = &string[0]; + w.len = string.length(); + w.cap = string.length(); + // Will never become true, as _grow is infallible. + w.grow_failed = false; + w.flush = _flush; + w.grow = _grow; + return w; +} + +// This "trait" allows one to use _write() methods to efficiently +// write to a custom string type. To do this you need to write a specialized +// `WriteTrait` (see WriteTrait below) +// that is capable of constructing a DiplomatWrite, which can wrap +// your string type with appropriate resize/flush functionality. +template struct WriteTrait { + // Fill in this method on a specialization to implement this trait + // static inline capi::DiplomatWrite Construct(T& t); +}; + +template<> struct WriteTrait { + static inline capi::DiplomatWrite Construct(std::string& t) { + return diplomat::WriteFromString(t); + } +}; + +template struct Ok { + T inner; + Ok(T&& i): inner(std::forward(i)) {} + // We don't want to expose an lvalue-capable constructor in general + // however there is no problem doing this for trivially copyable types + template::value>::type> + Ok(T i): inner(i) {} + Ok() = default; + Ok(Ok&&) noexcept = default; + Ok(const Ok &) = default; + Ok& operator=(const Ok&) = default; + Ok& operator=(Ok&&) noexcept = default; +}; + +template struct Err { + T inner; + Err(T&& i): inner(std::forward(i)) {} + // We don't want to expose an lvalue-capable constructor in general + // however there is no problem doing this for trivially copyable types + template::value>::type> + Err(T i): inner(i) {} + Err() = default; + Err(Err&&) noexcept = default; + Err(const Err &) = default; + Err& operator=(const Err&) = default; + Err& operator=(Err&&) noexcept = default; +}; + +template +class result { +private: + std::variant, Err> val; +public: + result(Ok&& v): val(std::move(v)) {} + result(Err&& v): val(std::move(v)) {} + result() = default; + result(const result &) = default; + result& operator=(const result&) = default; + result& operator=(result&&) noexcept = default; + result(result &&) noexcept = default; + ~result() = default; + bool is_ok() const { + return std::holds_alternative>(this->val); + } + bool is_err() const { + return std::holds_alternative>(this->val); + } + + template, std::nullptr_t> = nullptr> + std::optional ok() && { + if (!this->is_ok()) { + return std::nullopt; + } + return std::make_optional(std::move(std::get>(std::move(this->val)).inner)); + } + + template, std::nullptr_t> = nullptr> + std::optional err() && { + if (!this->is_err()) { + return std::nullopt; + } + return std::make_optional(std::move(std::get>(std::move(this->val)).inner)); + } + + // std::optional does not work with reference types directly, so wrap them if present + template, std::nullptr_t> = nullptr> + std::optional>> ok() && { + if (!this->is_ok()) { + return std::nullopt; + } + return std::make_optional(std::reference_wrapper(std::forward(std::get>(std::move(this->val)).inner))); + } + + template, std::nullptr_t> = nullptr> + std::optional>> err() && { + if (!this->is_err()) { + return std::nullopt; + } + return std::make_optional(std::reference_wrapper(std::forward(std::get>(std::move(this->val)).inner))); + } + + void set_ok(T&& t) { + this->val = Ok(std::move(t)); + } + + void set_err(E&& e) { + this->val = Err(std::move(e)); + } + + template + result replace_ok(T2&& t) { + if (this->is_err()) { + return result(Err(std::get>(std::move(this->val)))); + } else { + return result(Ok(std::move(t))); + } + } +}; + +class Utf8Error {}; + +// Use custom std::span on C++17, otherwise use std::span +#if __cplusplus >= 202002L + +constexpr std::size_t dynamic_extent = std::dynamic_extent; +template using span = std::span; + +#else // __cplusplus < 202002L + +// C++-17-compatible-ish std::span +constexpr size_t dynamic_extent = std::numeric_limits::max(); +template +class span { +public: + constexpr span(T *data = nullptr, size_t size = Extent) + : data_(data), size_(size) {} + + constexpr span(const span &o) + : data_(o.data_), size_(o.size_) {} + template + constexpr span(std::array, N> &arr) + : data_(const_cast(arr.data())), size_(N) {} + + constexpr T* data() const noexcept { + return this->data_; + } + constexpr size_t size() const noexcept { + return this->size_; + } + + constexpr T *begin() const noexcept { return data(); } + constexpr T *end() const noexcept { return data() + size(); } + + void operator=(span o) { + data_ = o.data_; + size_ = o.size_; + } + +private: + T* data_; + size_t size_; +}; + +#endif // __cplusplus >= 202002L + +// Interop between std::function & our C Callback wrapper type + +template +struct as_ffi { + using type = T; +}; + +template +struct as_ffi>().AsFFI())>> { + using type = decltype(std::declval>().AsFFI()); +}; + +template +using as_ffi_t = typename as_ffi::type; + +template +using replace_string_view_t = std::conditional_t, capi::DiplomatStringView, T>; + +template +using replace_ref_with_ptr_t = std::conditional_t, std::add_pointer_t>, T>; + +/// Replace the argument types from the std::function with the argument types for th function pointer +template +using replace_fn_t = replace_string_view_t>; + +template struct fn_traits; +template struct fn_traits> { + using fn_ptr_t = Ret(Args...); + using function_t = std::function; + using ret = Ret; + + // For a given T, creates a function that take in the C ABI version & return the C++ type. + template + static T replace(replace_fn_t val) { + if constexpr(std::is_same_v) { + return std::string_view{val.data, val.len}; + } else if constexpr (!std::is_same_v>) { + if constexpr (std::is_lvalue_reference_v) { + return *std::remove_reference_t::FromFFI(val); + } + else { + return T::FromFFI(val); + } + } + else { + return val; + } + } + + static Ret c_run_callback(const void *cb, replace_fn_t... args) { + return (*reinterpret_cast(cb))(replace(args)...); + } + + static void c_delete(const void *cb) { + delete reinterpret_cast(cb); + } + + fn_traits(function_t) {} // Allows less clunky construction (avoids decltype) +}; + +// additional deduction guide required +template +fn_traits(T) -> fn_traits; + +// Trait for extracting inner types from either std::optional or std::unique_ptr. +// These are the two potential types returned by next() functions +template struct inner { using type = T; }; +template struct inner> { using type = T; }; +template struct inner>{ using type = T; }; + +template::type> +inline const U get_inner_if_present(T v) { + if constexpr(std::is_same_v) { + return std::move(v); + } else { + return *std::move(v); + } +} + +// Adapter for iterator types +template struct has_next : std::false_type {}; +template struct has_next < T, std::void_t().next())>> : std::true_type {}; +template constexpr bool has_next_v = has_next::value; + +/// Helper template enabling native iteration over unique ptrs to objects which implement next() +template +struct next_to_iter_helper { + static_assert(has_next_v, "next_to_iter_helper may only be used with types implementing next()"); + using next_type = decltype(std::declval().next()); + + // STL Iterator trait definitions + using value_type = typename inner::type; + using difference_type = void; + using reference = std::add_lvalue_reference_t; + using iterator_category = std::input_iterator_tag; + + next_to_iter_helper(std::unique_ptr&& ptr) : _ptr(std::move(ptr)), _curr(_ptr->next()) {} + + // https://en.cppreference.com/w/cpp/named_req/InputIterator requires that the type be copyable + next_to_iter_helper(const next_to_iter_helper& o) : _ptr(o._ptr), _curr(o._curr) {} + + void operator++() { _curr = _ptr->next(); } + void operator++(int) { ++(*this); } + const value_type& operator*() const { return *_curr; } + + bool operator!=(std::nullopt_t) { + return (bool)_curr; + } + + std::shared_ptr _ptr; // shared to satisfy the copyable requirement + next_type _curr; +}; + +} // namespace diplomat + +#endif \ No newline at end of file diff --git a/bindings/js/Account.d.ts b/bindings/js/Account.d.ts new file mode 100644 index 0000000..33a9dc0 --- /dev/null +++ b/bindings/js/Account.d.ts @@ -0,0 +1,45 @@ +// generated by diplomat-tool +import type { CallList } from "./CallList" +import type { DojoError } from "./DojoError" +import type { FieldElement } from "./FieldElement" +import type { Provider } from "./Provider" +import type { SigningKey } from "./SigningKey" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Starknet account for signing and executing transactions + */ +export class Account { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new account + */ + static new_(provider: Provider, signer: SigningKey, address: FieldElement, chainId: FieldElement): Account; + + /** + * Gets the account address + */ + address(): string; + + /** + * Gets the chain ID + */ + chainId(): string; + + /** + * Executes a transaction with the given calls + */ + execute(calls: CallList): string; + + /** + * Gets the nonce for the account + */ + nonce(): bigint; +} \ No newline at end of file diff --git a/bindings/js/Account.mjs b/bindings/js/Account.mjs new file mode 100644 index 0000000..122d0b7 --- /dev/null +++ b/bindings/js/Account.mjs @@ -0,0 +1,145 @@ +// generated by diplomat-tool +import { CallList } from "./CallList.mjs" +import { DojoError } from "./DojoError.mjs" +import { FieldElement } from "./FieldElement.mjs" +import { Provider } from "./Provider.mjs" +import { SigningKey } from "./SigningKey.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Account_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Account_destroy(ptr); +}); + +/** + * Starknet account for signing and executing transactions + */ +export class Account { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Account is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Account_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new account + */ + static new_(provider, signer, address, chainId) { + + const result = wasm.Account_new(provider.ffiValue, signer.ffiValue, address.ffiValue, chainId.ffiValue); + + try { + return new Account(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Gets the account address + */ + address() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Account_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the chain ID + */ + chainId() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Account_chain_id(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Executes a transaction with the given calls + */ + execute(calls) { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Account_execute(diplomatReceive.buffer, this.ffiValue, calls.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + /** + * Gets the nonce for the account + */ + nonce() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 9, 8, true); + + + const result = wasm.Account_nonce(diplomatReceive.buffer, this.ffiValue); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return (new BigUint64Array(wasm.memory.buffer, diplomatReceive.buffer, 1))[0]; + } + + finally { + diplomatReceive.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Achievement.d.ts b/bindings/js/Achievement.d.ts new file mode 100644 index 0000000..6e9b31c --- /dev/null +++ b/bindings/js/Achievement.d.ts @@ -0,0 +1,66 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents an achievement + */ +export class Achievement { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the achievement ID + */ + id(): string; + + /** + * Gets the world address (hex) + */ + worldAddress(): string; + + /** + * Gets the namespace + */ + namespace(): string; + + /** + * Gets the achievement title + */ + title(): string; + + /** + * Gets the achievement description + */ + description(): string; + + /** + * Gets the hidden flag + */ + hidden(): boolean; + + /** + * Gets the icon URI + */ + icon(): string; + + /** + * Gets the points for this achievement + */ + points(): number; + + /** + * Creates an achievement from JSON + */ + static fromJson(json: string): Achievement; + + /** + * Serializes the achievement to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Achievement.mjs b/bindings/js/Achievement.mjs new file mode 100644 index 0000000..c19e77a --- /dev/null +++ b/bindings/js/Achievement.mjs @@ -0,0 +1,229 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Achievement_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Achievement_destroy(ptr); +}); + +/** + * Represents an achievement + */ +export class Achievement { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Achievement is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Achievement_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the achievement ID + */ + id() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Achievement_id(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the world address (hex) + */ + worldAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Achievement_world_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the namespace + */ + namespace() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Achievement_namespace(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the achievement title + */ + title() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Achievement_title(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the achievement description + */ + description() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Achievement_description(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the hidden flag + */ + hidden() { + + const result = wasm.Achievement_hidden(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the icon URI + */ + icon() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Achievement_icon(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the points for this achievement + */ + points() { + + const result = wasm.Achievement_points(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates an achievement from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Achievement_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Achievement(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the achievement to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Achievement_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Activity.d.ts b/bindings/js/Activity.d.ts new file mode 100644 index 0000000..c67b044 --- /dev/null +++ b/bindings/js/Activity.d.ts @@ -0,0 +1,66 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents an activity + */ +export class Activity { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the activity ID + */ + id(): string; + + /** + * Gets the world address (hex) + */ + worldAddress(): string; + + /** + * Gets the namespace + */ + namespace(): string; + + /** + * Gets the caller address (hex) + */ + callerAddress(): string; + + /** + * Gets the session start timestamp + */ + sessionStart(): bigint; + + /** + * Gets the session end timestamp + */ + sessionEnd(): bigint; + + /** + * Gets the action count + */ + actionCount(): number; + + /** + * Gets the updated_at timestamp + */ + updatedAt(): bigint; + + /** + * Creates an activity from JSON + */ + static fromJson(json: string): Activity; + + /** + * Serializes the activity to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Activity.mjs b/bindings/js/Activity.mjs new file mode 100644 index 0000000..5c30936 --- /dev/null +++ b/bindings/js/Activity.mjs @@ -0,0 +1,225 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Activity_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Activity_destroy(ptr); +}); + +/** + * Represents an activity + */ +export class Activity { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Activity is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Activity_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the activity ID + */ + id() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Activity_id(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the world address (hex) + */ + worldAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Activity_world_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the namespace + */ + namespace() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Activity_namespace(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the caller address (hex) + */ + callerAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Activity_caller_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the session start timestamp + */ + sessionStart() { + + const result = wasm.Activity_session_start(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the session end timestamp + */ + sessionEnd() { + + const result = wasm.Activity_session_end(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the action count + */ + actionCount() { + + const result = wasm.Activity_action_count(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the updated_at timestamp + */ + updatedAt() { + + const result = wasm.Activity_updated_at(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates an activity from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Activity_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Activity(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the activity to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Activity_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/AggregationEntry.d.ts b/bindings/js/AggregationEntry.d.ts new file mode 100644 index 0000000..cea8b3f --- /dev/null +++ b/bindings/js/AggregationEntry.d.ts @@ -0,0 +1,71 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents an aggregation entry + */ +export class AggregationEntry { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the aggregation ID + */ + id(): string; + + /** + * Gets the aggregator ID + */ + aggregatorId(): string; + + /** + * Gets the entity ID + */ + entityId(): string; + + /** + * Gets the model ID + */ + modelId(): string; + + /** + * Gets the aggregation value + */ + value(): string; + + /** + * Gets the display value + */ + displayValue(): string; + + /** + * Gets the position + */ + position(): bigint; + + /** + * Gets the created_at timestamp + */ + createdAt(): bigint; + + /** + * Gets the updated_at timestamp + */ + updatedAt(): bigint; + + /** + * Creates an aggregation entry from JSON + */ + static fromJson(json: string): AggregationEntry; + + /** + * Serializes the aggregation entry to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/AggregationEntry.mjs b/bindings/js/AggregationEntry.mjs new file mode 100644 index 0000000..88115b9 --- /dev/null +++ b/bindings/js/AggregationEntry.mjs @@ -0,0 +1,244 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const AggregationEntry_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.AggregationEntry_destroy(ptr); +}); + +/** + * Represents an aggregation entry + */ +export class AggregationEntry { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("AggregationEntry is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + AggregationEntry_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the aggregation ID + */ + id() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.AggregationEntry_id(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the aggregator ID + */ + aggregatorId() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.AggregationEntry_aggregator_id(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the entity ID + */ + entityId() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.AggregationEntry_entity_id(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the model ID + */ + modelId() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.AggregationEntry_model_id(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the aggregation value + */ + value() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.AggregationEntry_value(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the display value + */ + displayValue() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.AggregationEntry_display_value(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the position + */ + position() { + + const result = wasm.AggregationEntry_position(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the created_at timestamp + */ + createdAt() { + + const result = wasm.AggregationEntry_created_at(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the updated_at timestamp + */ + updatedAt() { + + const result = wasm.AggregationEntry_updated_at(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates an aggregation entry from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.AggregationEntry_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new AggregationEntry(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the aggregation entry to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.AggregationEntry_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/BlockId.d.ts b/bindings/js/BlockId.d.ts new file mode 100644 index 0000000..a1f1e52 --- /dev/null +++ b/bindings/js/BlockId.d.ts @@ -0,0 +1,32 @@ +// generated by diplomat-tool +import type { BlockTag } from "./BlockTag" +import type { FieldElement } from "./FieldElement" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Block identifier (hash, number, or tag) + */ +export class BlockId { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a BlockId from a block hash + */ + static fromHash(hash: FieldElement): BlockId; + + /** + * Creates a BlockId from a block number + */ + static fromNumber(number: bigint): BlockId; + + /** + * Creates a BlockId from a block tag + */ + static fromTag(tag: BlockTag): BlockId; +} \ No newline at end of file diff --git a/bindings/js/BlockId.mjs b/bindings/js/BlockId.mjs new file mode 100644 index 0000000..f672318 --- /dev/null +++ b/bindings/js/BlockId.mjs @@ -0,0 +1,91 @@ +// generated by diplomat-tool +import { BlockTag } from "./BlockTag.mjs" +import { FieldElement } from "./FieldElement.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const BlockId_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.BlockId_destroy(ptr); +}); + +/** + * Block identifier (hash, number, or tag) + */ +export class BlockId { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("BlockId is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + BlockId_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a BlockId from a block hash + */ + static fromHash(hash) { + + const result = wasm.BlockId_from_hash(hash.ffiValue); + + try { + return new BlockId(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Creates a BlockId from a block number + */ + static fromNumber(number) { + + const result = wasm.BlockId_from_number(number); + + try { + return new BlockId(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Creates a BlockId from a block tag + */ + static fromTag(tag) { + + const result = wasm.BlockId_from_tag(tag.ffiValue); + + try { + return new BlockId(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/BlockTag.d.ts b/bindings/js/BlockTag.d.ts new file mode 100644 index 0000000..1dcda63 --- /dev/null +++ b/bindings/js/BlockTag.d.ts @@ -0,0 +1,24 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Block tag for identifying specific blocks + */ +export class BlockTag { + + /** @internal */ + static fromValue(value: BlockTag | string): BlockTag; + + get value(): string; + + /** @internal */ + get ffiValue(): number; + + static Latest : BlockTag; + static PreConfirmed : BlockTag; + + + constructor(value: BlockTag | string ); +} \ No newline at end of file diff --git a/bindings/js/BlockTag.mjs b/bindings/js/BlockTag.mjs new file mode 100644 index 0000000..dc55709 --- /dev/null +++ b/bindings/js/BlockTag.mjs @@ -0,0 +1,72 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + + + +/** + * Block tag for identifying specific blocks + */ +export class BlockTag { + #value = undefined; + + static #values = new Map([ + ["Latest", 0], + ["PreConfirmed", 1] + ]); + + static getAllEntries() { + return BlockTag.#values.entries(); + } + + #internalConstructor(value) { + if (arguments.length > 1 && arguments[0] === diplomatRuntime.internalConstructor) { + // We pass in two internalConstructor arguments to create *new* + // instances of this type, otherwise the enums are treated as singletons. + if (arguments[1] === diplomatRuntime.internalConstructor ) { + this.#value = arguments[2]; + return this; + } + return BlockTag.#objectValues[arguments[1]]; + } + + if (value instanceof BlockTag) { + return value; + } + + let intVal = BlockTag.#values.get(value); + + // Nullish check, checks for null or undefined + if (intVal != null) { + return BlockTag.#objectValues[intVal]; + } + + throw TypeError(value + " is not a BlockTag and does not correspond to any of its enumerator values."); + } + + /** @internal */ + static fromValue(value) { + return new BlockTag(value); + } + + get value(){ + return [...BlockTag.#values.keys()][this.#value]; + } + + /** @internal */ + get ffiValue(){ + return this.#value; + } + static #objectValues = [ + new BlockTag(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 0), + new BlockTag(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 1), + ]; + + static Latest = BlockTag.#objectValues[0]; + static PreConfirmed = BlockTag.#objectValues[1]; + + + constructor(value) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Call.d.ts b/bindings/js/Call.d.ts new file mode 100644 index 0000000..b96407b --- /dev/null +++ b/bindings/js/Call.d.ts @@ -0,0 +1,32 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { FieldElement } from "./FieldElement" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a Starknet call + */ +export class Call { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new Call + */ + static new_(to: FieldElement, selector: FieldElement): Call; + + /** + * Adds a field element to the calldata + */ + pushCalldata(felt: FieldElement): void; + + /** + * Creates a call from selector name + */ + static newFromSelectorName(to: FieldElement, selectorName: string): Call; +} \ No newline at end of file diff --git a/bindings/js/Call.mjs b/bindings/js/Call.mjs new file mode 100644 index 0000000..0647ac0 --- /dev/null +++ b/bindings/js/Call.mjs @@ -0,0 +1,100 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import { FieldElement } from "./FieldElement.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Call_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Call_destroy(ptr); +}); + +/** + * Represents a Starknet call + */ +export class Call { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Call is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Call_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new Call + */ + static new_(to, selector) { + + const result = wasm.Call_new(to.ffiValue, selector.ffiValue); + + try { + return new Call(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Adds a field element to the calldata + */ + pushCalldata(felt) { + wasm.Call_push_calldata(this.ffiValue, felt.ffiValue); + + try {} + + finally { + } + } + + /** + * Creates a call from selector name + */ + static newFromSelectorName(to, selectorName) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const selectorNameSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, selectorName))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Call_new_from_selector_name(diplomatReceive.buffer, to.ffiValue, selectorNameSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Call(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/CallList.d.ts b/bindings/js/CallList.d.ts new file mode 100644 index 0000000..2cfa5c1 --- /dev/null +++ b/bindings/js/CallList.d.ts @@ -0,0 +1,31 @@ +// generated by diplomat-tool +import type { Call } from "./Call" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * List of calls for batch transactions + */ +export class CallList { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new empty call list + */ + static new_(): CallList; + + /** + * Adds a call to the list + */ + addCall(call: Call): void; + + /** + * Returns the number of calls in the list + */ + len(): number; +} \ No newline at end of file diff --git a/bindings/js/CallList.mjs b/bindings/js/CallList.mjs new file mode 100644 index 0000000..52c5b3a --- /dev/null +++ b/bindings/js/CallList.mjs @@ -0,0 +1,87 @@ +// generated by diplomat-tool +import { Call } from "./Call.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const CallList_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.CallList_destroy(ptr); +}); + +/** + * List of calls for batch transactions + */ +export class CallList { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("CallList is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + CallList_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new empty call list + */ + static new_() { + + const result = wasm.CallList_new(); + + try { + return new CallList(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Adds a call to the list + */ + addCall(call) { + wasm.CallList_add_call(this.ffiValue, call.ffiValue); + + try {} + + finally { + } + } + + /** + * Returns the number of calls in the list + */ + len() { + + const result = wasm.CallList_len(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/CallType.d.ts b/bindings/js/CallType.d.ts new file mode 100644 index 0000000..261f6cd --- /dev/null +++ b/bindings/js/CallType.d.ts @@ -0,0 +1,24 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Type of call in a transaction + */ +export class CallType { + + /** @internal */ + static fromValue(value: CallType | string): CallType; + + get value(): string; + + /** @internal */ + get ffiValue(): number; + + static Execute : CallType; + static ExecuteFromOutside : CallType; + + + constructor(value: CallType | string ); +} \ No newline at end of file diff --git a/bindings/js/CallType.mjs b/bindings/js/CallType.mjs new file mode 100644 index 0000000..bd27be7 --- /dev/null +++ b/bindings/js/CallType.mjs @@ -0,0 +1,72 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + + + +/** + * Type of call in a transaction + */ +export class CallType { + #value = undefined; + + static #values = new Map([ + ["Execute", 0], + ["ExecuteFromOutside", 1] + ]); + + static getAllEntries() { + return CallType.#values.entries(); + } + + #internalConstructor(value) { + if (arguments.length > 1 && arguments[0] === diplomatRuntime.internalConstructor) { + // We pass in two internalConstructor arguments to create *new* + // instances of this type, otherwise the enums are treated as singletons. + if (arguments[1] === diplomatRuntime.internalConstructor ) { + this.#value = arguments[2]; + return this; + } + return CallType.#objectValues[arguments[1]]; + } + + if (value instanceof CallType) { + return value; + } + + let intVal = CallType.#values.get(value); + + // Nullish check, checks for null or undefined + if (intVal != null) { + return CallType.#objectValues[intVal]; + } + + throw TypeError(value + " is not a CallType and does not correspond to any of its enumerator values."); + } + + /** @internal */ + static fromValue(value) { + return new CallType(value); + } + + get value(){ + return [...CallType.#values.keys()][this.#value]; + } + + /** @internal */ + get ffiValue(){ + return this.#value; + } + static #objectValues = [ + new CallType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 0), + new CallType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 1), + ]; + + static Execute = CallType.#objectValues[0]; + static ExecuteFromOutside = CallType.#objectValues[1]; + + + constructor(value) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Clause.d.ts b/bindings/js/Clause.d.ts new file mode 100644 index 0000000..ae0be07 --- /dev/null +++ b/bindings/js/Clause.d.ts @@ -0,0 +1,15 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Query clause for filtering entities + */ +export class Clause { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + +} \ No newline at end of file diff --git a/bindings/js/Clause.mjs b/bindings/js/Clause.mjs new file mode 100644 index 0000000..e7252d3 --- /dev/null +++ b/bindings/js/Clause.mjs @@ -0,0 +1,44 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Clause_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Clause_destroy(ptr); +}); + +/** + * Query clause for filtering entities + */ +export class Clause { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Clause is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Clause_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/ComparisonOperator.d.ts b/bindings/js/ComparisonOperator.d.ts new file mode 100644 index 0000000..3348dcd --- /dev/null +++ b/bindings/js/ComparisonOperator.d.ts @@ -0,0 +1,36 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Comparison operators for member clauses + */ +export class ComparisonOperator { + + /** @internal */ + static fromValue(value: ComparisonOperator | string): ComparisonOperator; + + get value(): string; + + /** @internal */ + get ffiValue(): number; + + static Eq : ComparisonOperator; + static Neq : ComparisonOperator; + static Gt : ComparisonOperator; + static Gte : ComparisonOperator; + static Lt : ComparisonOperator; + static Lte : ComparisonOperator; + static In : ComparisonOperator; + static NotIn : ComparisonOperator; + static Contains : ComparisonOperator; + static ContainsAll : ComparisonOperator; + static ContainsAny : ComparisonOperator; + static ArrayLengthEq : ComparisonOperator; + static ArrayLengthGt : ComparisonOperator; + static ArrayLengthLt : ComparisonOperator; + + + constructor(value: ComparisonOperator | string ); +} \ No newline at end of file diff --git a/bindings/js/ComparisonOperator.mjs b/bindings/js/ComparisonOperator.mjs new file mode 100644 index 0000000..746b2cf --- /dev/null +++ b/bindings/js/ComparisonOperator.mjs @@ -0,0 +1,108 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + + + +/** + * Comparison operators for member clauses + */ +export class ComparisonOperator { + #value = undefined; + + static #values = new Map([ + ["Eq", 0], + ["Neq", 1], + ["Gt", 2], + ["Gte", 3], + ["Lt", 4], + ["Lte", 5], + ["In", 6], + ["NotIn", 7], + ["Contains", 8], + ["ContainsAll", 9], + ["ContainsAny", 10], + ["ArrayLengthEq", 11], + ["ArrayLengthGt", 12], + ["ArrayLengthLt", 13] + ]); + + static getAllEntries() { + return ComparisonOperator.#values.entries(); + } + + #internalConstructor(value) { + if (arguments.length > 1 && arguments[0] === diplomatRuntime.internalConstructor) { + // We pass in two internalConstructor arguments to create *new* + // instances of this type, otherwise the enums are treated as singletons. + if (arguments[1] === diplomatRuntime.internalConstructor ) { + this.#value = arguments[2]; + return this; + } + return ComparisonOperator.#objectValues[arguments[1]]; + } + + if (value instanceof ComparisonOperator) { + return value; + } + + let intVal = ComparisonOperator.#values.get(value); + + // Nullish check, checks for null or undefined + if (intVal != null) { + return ComparisonOperator.#objectValues[intVal]; + } + + throw TypeError(value + " is not a ComparisonOperator and does not correspond to any of its enumerator values."); + } + + /** @internal */ + static fromValue(value) { + return new ComparisonOperator(value); + } + + get value(){ + return [...ComparisonOperator.#values.keys()][this.#value]; + } + + /** @internal */ + get ffiValue(){ + return this.#value; + } + static #objectValues = [ + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 0), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 1), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 2), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 3), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 4), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 5), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 6), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 7), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 8), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 9), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 10), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 11), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 12), + new ComparisonOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 13), + ]; + + static Eq = ComparisonOperator.#objectValues[0]; + static Neq = ComparisonOperator.#objectValues[1]; + static Gt = ComparisonOperator.#objectValues[2]; + static Gte = ComparisonOperator.#objectValues[3]; + static Lt = ComparisonOperator.#objectValues[4]; + static Lte = ComparisonOperator.#objectValues[5]; + static In = ComparisonOperator.#objectValues[6]; + static NotIn = ComparisonOperator.#objectValues[7]; + static Contains = ComparisonOperator.#objectValues[8]; + static ContainsAll = ComparisonOperator.#objectValues[9]; + static ContainsAny = ComparisonOperator.#objectValues[10]; + static ArrayLengthEq = ComparisonOperator.#objectValues[11]; + static ArrayLengthGt = ComparisonOperator.#objectValues[12]; + static ArrayLengthLt = ComparisonOperator.#objectValues[13]; + + + constructor(value) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Contract.d.ts b/bindings/js/Contract.d.ts new file mode 100644 index 0000000..da841c9 --- /dev/null +++ b/bindings/js/Contract.d.ts @@ -0,0 +1,56 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a contract + */ +export class Contract { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the contract address (hex) + */ + contractAddress(): string; + + /** + * Gets the contract type as string + */ + contractType(): string; + + /** + * Gets the head block number (if any) + */ + head(): bigint; + + /** + * Gets the TPS (transactions per second) if available + */ + tps(): bigint; + + /** + * Gets the created_at timestamp + */ + createdAt(): bigint; + + /** + * Gets the updated_at timestamp + */ + updatedAt(): bigint; + + /** + * Creates a contract from JSON + */ + static fromJson(json: string): Contract; + + /** + * Serializes the contract to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Contract.mjs b/bindings/js/Contract.mjs new file mode 100644 index 0000000..88a8ba9 --- /dev/null +++ b/bindings/js/Contract.mjs @@ -0,0 +1,191 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Contract_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Contract_destroy(ptr); +}); + +/** + * Represents a contract + */ +export class Contract { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Contract is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Contract_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the contract address (hex) + */ + contractAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Contract_contract_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the contract type as string + */ + contractType() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Contract_contract_type(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the head block number (if any) + */ + head() { + + const result = wasm.Contract_head(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the TPS (transactions per second) if available + */ + tps() { + + const result = wasm.Contract_tps(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the created_at timestamp + */ + createdAt() { + + const result = wasm.Contract_created_at(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the updated_at timestamp + */ + updatedAt() { + + const result = wasm.Contract_updated_at(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates a contract from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Contract_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Contract(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the contract to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Contract_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/ContractType.d.ts b/bindings/js/ContractType.d.ts new file mode 100644 index 0000000..ded9522 --- /dev/null +++ b/bindings/js/ContractType.d.ts @@ -0,0 +1,28 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Type of contract + */ +export class ContractType { + + /** @internal */ + static fromValue(value: ContractType | string): ContractType; + + get value(): string; + + /** @internal */ + get ffiValue(): number; + + static World : ContractType; + static Erc20 : ContractType; + static Erc721 : ContractType; + static Erc1155 : ContractType; + static Udc : ContractType; + static Other : ContractType; + + + constructor(value: ContractType | string ); +} \ No newline at end of file diff --git a/bindings/js/ContractType.mjs b/bindings/js/ContractType.mjs new file mode 100644 index 0000000..ad806b3 --- /dev/null +++ b/bindings/js/ContractType.mjs @@ -0,0 +1,84 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + + + +/** + * Type of contract + */ +export class ContractType { + #value = undefined; + + static #values = new Map([ + ["World", 0], + ["Erc20", 1], + ["Erc721", 2], + ["Erc1155", 3], + ["Udc", 4], + ["Other", 5] + ]); + + static getAllEntries() { + return ContractType.#values.entries(); + } + + #internalConstructor(value) { + if (arguments.length > 1 && arguments[0] === diplomatRuntime.internalConstructor) { + // We pass in two internalConstructor arguments to create *new* + // instances of this type, otherwise the enums are treated as singletons. + if (arguments[1] === diplomatRuntime.internalConstructor ) { + this.#value = arguments[2]; + return this; + } + return ContractType.#objectValues[arguments[1]]; + } + + if (value instanceof ContractType) { + return value; + } + + let intVal = ContractType.#values.get(value); + + // Nullish check, checks for null or undefined + if (intVal != null) { + return ContractType.#objectValues[intVal]; + } + + throw TypeError(value + " is not a ContractType and does not correspond to any of its enumerator values."); + } + + /** @internal */ + static fromValue(value) { + return new ContractType(value); + } + + get value(){ + return [...ContractType.#values.keys()][this.#value]; + } + + /** @internal */ + get ffiValue(){ + return this.#value; + } + static #objectValues = [ + new ContractType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 0), + new ContractType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 1), + new ContractType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 2), + new ContractType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 3), + new ContractType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 4), + new ContractType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 5), + ]; + + static World = ContractType.#objectValues[0]; + static Erc20 = ContractType.#objectValues[1]; + static Erc721 = ContractType.#objectValues[2]; + static Erc1155 = ContractType.#objectValues[3]; + static Udc = ContractType.#objectValues[4]; + static Other = ContractType.#objectValues[5]; + + + constructor(value) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/DojoError.d.ts b/bindings/js/DojoError.d.ts new file mode 100644 index 0000000..d943294 --- /dev/null +++ b/bindings/js/DojoError.d.ts @@ -0,0 +1,28 @@ +// generated by diplomat-tool +import type { ErrorType } from "./ErrorType" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Error types for Dojo operations + */ +export class DojoError { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + static new_(errorType: ErrorType, message: string): DojoError; + + /** + * Gets the error message + */ + message(): string; + + /** + * Gets the error type + */ + errorType(): ErrorType; +} \ No newline at end of file diff --git a/bindings/js/DojoError.mjs b/bindings/js/DojoError.mjs new file mode 100644 index 0000000..4f5a6ec --- /dev/null +++ b/bindings/js/DojoError.mjs @@ -0,0 +1,94 @@ +// generated by diplomat-tool +import { ErrorType } from "./ErrorType.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const DojoError_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.DojoError_destroy(ptr); +}); + +/** + * Error types for Dojo operations + */ +export class DojoError { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("DojoError is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + DojoError_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + static new_(errorType, message) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const messageSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, message))); + + const result = wasm.DojoError_new(errorType.ffiValue, messageSlice.ptr); + + try { + return new DojoError(diplomatRuntime.internalConstructor, result, []); + } + + finally { + functionCleanupArena.free(); + + } + } + + /** + * Gets the error message + */ + message() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.DojoError_message(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the error type + */ + errorType() { + + const result = wasm.DojoError_error_type(this.ffiValue); + + try { + return new ErrorType(diplomatRuntime.internalConstructor, result); + } + + finally { + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Entity.d.ts b/bindings/js/Entity.d.ts new file mode 100644 index 0000000..087e6bb --- /dev/null +++ b/bindings/js/Entity.d.ts @@ -0,0 +1,51 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a Dojo entity + */ +export class Entity { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the hashed keys (hex) + */ + hashedKeys(): string; + + /** + * Gets the number of models in this entity + */ + modelsCount(): number; + + /** + * Gets the created_at timestamp + */ + createdAt(): bigint; + + /** + * Gets the updated_at timestamp + */ + updatedAt(): bigint; + + /** + * Gets the executed_at timestamp + */ + executedAt(): bigint; + + /** + * Creates a new entity from JSON + */ + static fromJson(json: string): Entity; + + /** + * Serializes the entity to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Entity.mjs b/bindings/js/Entity.mjs new file mode 100644 index 0000000..c8a8c6d --- /dev/null +++ b/bindings/js/Entity.mjs @@ -0,0 +1,174 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Entity_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Entity_destroy(ptr); +}); + +/** + * Represents a Dojo entity + */ +export class Entity { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Entity is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Entity_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the hashed keys (hex) + */ + hashedKeys() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Entity_hashed_keys(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the number of models in this entity + */ + modelsCount() { + + const result = wasm.Entity_models_count(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the created_at timestamp + */ + createdAt() { + + const result = wasm.Entity_created_at(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the updated_at timestamp + */ + updatedAt() { + + const result = wasm.Entity_updated_at(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the executed_at timestamp + */ + executedAt() { + + const result = wasm.Entity_executed_at(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates a new entity from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Entity_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Entity(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the entity to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Entity_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/EntityQuery.d.ts b/bindings/js/EntityQuery.d.ts new file mode 100644 index 0000000..6368b03 --- /dev/null +++ b/bindings/js/EntityQuery.d.ts @@ -0,0 +1,30 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Entity query for retrieving entities from Torii + */ +export class EntityQuery { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new entity query + */ + static new_(): EntityQuery; + + /** + * Sets the limit for the query + */ + setLimit(limit: number): void; + + /** + * Sets the offset for the query + */ + setOffset(offset: number): void; +} \ No newline at end of file diff --git a/bindings/js/EntityQuery.mjs b/bindings/js/EntityQuery.mjs new file mode 100644 index 0000000..9f4e950 --- /dev/null +++ b/bindings/js/EntityQuery.mjs @@ -0,0 +1,83 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const EntityQuery_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.EntityQuery_destroy(ptr); +}); + +/** + * Entity query for retrieving entities from Torii + */ +export class EntityQuery { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("EntityQuery is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + EntityQuery_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new entity query + */ + static new_() { + + const result = wasm.EntityQuery_new(); + + try { + return new EntityQuery(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Sets the limit for the query + */ + setLimit(limit) { + wasm.EntityQuery_set_limit(this.ffiValue, limit); + + try {} + + finally { + } + } + + /** + * Sets the offset for the query + */ + setOffset(offset) { + wasm.EntityQuery_set_offset(this.ffiValue, offset); + + try {} + + finally { + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Enum.d.ts b/bindings/js/Enum.d.ts new file mode 100644 index 0000000..f5dd9b3 --- /dev/null +++ b/bindings/js/Enum.d.ts @@ -0,0 +1,41 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a Dojo enum + */ +export class Enum { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the enum name + */ + name(): string; + + /** + * Gets the current option (selected variant) index + */ + option(): number; + + /** + * Gets the number of options (variants) + */ + optionsCount(): number; + + /** + * Creates a new enum from JSON schema + */ + static fromJson(json: string): Enum; + + /** + * Serializes the enum to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Enum.mjs b/bindings/js/Enum.mjs new file mode 100644 index 0000000..a7873c2 --- /dev/null +++ b/bindings/js/Enum.mjs @@ -0,0 +1,144 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Enum_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Enum_destroy(ptr); +}); + +/** + * Represents a Dojo enum + */ +export class Enum { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Enum is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Enum_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the enum name + */ + name() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Enum_name(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the current option (selected variant) index + */ + option() { + + const result = wasm.Enum_option(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the number of options (variants) + */ + optionsCount() { + + const result = wasm.Enum_options_count(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates a new enum from JSON schema + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Enum_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Enum(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the enum to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Enum_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/EnumOption.d.ts b/bindings/js/EnumOption.d.ts new file mode 100644 index 0000000..2f814a2 --- /dev/null +++ b/bindings/js/EnumOption.d.ts @@ -0,0 +1,20 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a Dojo enum option (variant) + */ +export class EnumOption { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the option name + */ + name(): string; +} \ No newline at end of file diff --git a/bindings/js/EnumOption.mjs b/bindings/js/EnumOption.mjs new file mode 100644 index 0000000..18b298b --- /dev/null +++ b/bindings/js/EnumOption.mjs @@ -0,0 +1,61 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const EnumOption_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.EnumOption_destroy(ptr); +}); + +/** + * Represents a Dojo enum option (variant) + */ +export class EnumOption { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("EnumOption is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + EnumOption_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the option name + */ + name() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.EnumOption_name(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/ErrorType.d.ts b/bindings/js/ErrorType.d.ts new file mode 100644 index 0000000..4b676f3 --- /dev/null +++ b/bindings/js/ErrorType.d.ts @@ -0,0 +1,32 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +export class ErrorType { + + /** @internal */ + static fromValue(value: ErrorType | string): ErrorType; + + get value(): string; + + /** @internal */ + get ffiValue(): number; + + static ClientError : ErrorType; + static ParseError : ErrorType; + static EntityError : ErrorType; + static QueryError : ErrorType; + static SubscriptionError : ErrorType; + static TransactionError : ErrorType; + static AccountError : ErrorType; + static SigningError : ErrorType; + static ProviderError : ErrorType; + static StorageError : ErrorType; + static ControllerError : ErrorType; + static InvalidInput : ErrorType; + static RuntimeError : ErrorType; + + + constructor(value: ErrorType | string ); +} \ No newline at end of file diff --git a/bindings/js/ErrorType.mjs b/bindings/js/ErrorType.mjs new file mode 100644 index 0000000..8a29a0e --- /dev/null +++ b/bindings/js/ErrorType.mjs @@ -0,0 +1,102 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + + + +export class ErrorType { + #value = undefined; + + static #values = new Map([ + ["ClientError", 0], + ["ParseError", 1], + ["EntityError", 2], + ["QueryError", 3], + ["SubscriptionError", 4], + ["TransactionError", 5], + ["AccountError", 6], + ["SigningError", 7], + ["ProviderError", 8], + ["StorageError", 9], + ["ControllerError", 10], + ["InvalidInput", 11], + ["RuntimeError", 12] + ]); + + static getAllEntries() { + return ErrorType.#values.entries(); + } + + #internalConstructor(value) { + if (arguments.length > 1 && arguments[0] === diplomatRuntime.internalConstructor) { + // We pass in two internalConstructor arguments to create *new* + // instances of this type, otherwise the enums are treated as singletons. + if (arguments[1] === diplomatRuntime.internalConstructor ) { + this.#value = arguments[2]; + return this; + } + return ErrorType.#objectValues[arguments[1]]; + } + + if (value instanceof ErrorType) { + return value; + } + + let intVal = ErrorType.#values.get(value); + + // Nullish check, checks for null or undefined + if (intVal != null) { + return ErrorType.#objectValues[intVal]; + } + + throw TypeError(value + " is not a ErrorType and does not correspond to any of its enumerator values."); + } + + /** @internal */ + static fromValue(value) { + return new ErrorType(value); + } + + get value(){ + return [...ErrorType.#values.keys()][this.#value]; + } + + /** @internal */ + get ffiValue(){ + return this.#value; + } + static #objectValues = [ + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 0), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 1), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 2), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 3), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 4), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 5), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 6), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 7), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 8), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 9), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 10), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 11), + new ErrorType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 12), + ]; + + static ClientError = ErrorType.#objectValues[0]; + static ParseError = ErrorType.#objectValues[1]; + static EntityError = ErrorType.#objectValues[2]; + static QueryError = ErrorType.#objectValues[3]; + static SubscriptionError = ErrorType.#objectValues[4]; + static TransactionError = ErrorType.#objectValues[5]; + static AccountError = ErrorType.#objectValues[6]; + static SigningError = ErrorType.#objectValues[7]; + static ProviderError = ErrorType.#objectValues[8]; + static StorageError = ErrorType.#objectValues[9]; + static ControllerError = ErrorType.#objectValues[10]; + static InvalidInput = ErrorType.#objectValues[11]; + static RuntimeError = ErrorType.#objectValues[12]; + + + constructor(value) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Event.d.ts b/bindings/js/Event.d.ts new file mode 100644 index 0000000..ba9bb9a --- /dev/null +++ b/bindings/js/Event.d.ts @@ -0,0 +1,41 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a Dojo event message + */ +export class Event { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the keys as JSON array string + */ + keys(): string; + + /** + * Gets the data as JSON array string + */ + data(): string; + + /** + * Gets the transaction hash (hex) + */ + transactionHash(): string; + + /** + * Creates an event from JSON + */ + static fromJson(json: string): Event; + + /** + * Serializes the event to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Event.mjs b/bindings/js/Event.mjs new file mode 100644 index 0000000..7f40d46 --- /dev/null +++ b/bindings/js/Event.mjs @@ -0,0 +1,148 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Event_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Event_destroy(ptr); +}); + +/** + * Represents a Dojo event message + */ +export class Event { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Event is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Event_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the keys as JSON array string + */ + keys() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Event_keys(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the data as JSON array string + */ + data() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Event_data(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the transaction hash (hex) + */ + transactionHash() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Event_transaction_hash(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Creates an event from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Event_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Event(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the event to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Event_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/FieldElement.d.ts b/bindings/js/FieldElement.d.ts new file mode 100644 index 0000000..43d47dc --- /dev/null +++ b/bindings/js/FieldElement.d.ts @@ -0,0 +1,36 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a Starknet field element (Felt) + */ +export class FieldElement { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new FieldElement from a hexadecimal string + */ + static newFromHex(hex: string): FieldElement; + + /** + * Creates a new FieldElement from big-endian bytes + */ + static newFromBytes(bytes: Array): FieldElement; + + /** + * Returns the field element as a hexadecimal string + */ + toHex(): string; + + /** + * Returns the field element as bytes (big-endian) + */ + toBytes(result: Array): void; +} \ No newline at end of file diff --git a/bindings/js/FieldElement.mjs b/bindings/js/FieldElement.mjs new file mode 100644 index 0000000..79ac348 --- /dev/null +++ b/bindings/js/FieldElement.mjs @@ -0,0 +1,126 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const FieldElement_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.FieldElement_destroy(ptr); +}); + +/** + * Represents a Starknet field element (Felt) + */ +export class FieldElement { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("FieldElement is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + FieldElement_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new FieldElement from a hexadecimal string + */ + static newFromHex(hex) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const hexSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, hex))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.FieldElement_new_from_hex(diplomatReceive.buffer, hexSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new FieldElement(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Creates a new FieldElement from big-endian bytes + */ + static newFromBytes(bytes) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const bytesSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.slice(wasm, bytes, "u8"))); + + const result = wasm.FieldElement_new_from_bytes(bytesSlice.ptr); + + try { + return new FieldElement(diplomatRuntime.internalConstructor, result, []); + } + + finally { + functionCleanupArena.free(); + + } + } + + /** + * Returns the field element as a hexadecimal string + */ + toHex() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.FieldElement_to_hex(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Returns the field element as bytes (big-endian) + */ + toBytes(result) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const resultSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.slice(wasm, result, "u8"))); + wasm.FieldElement_to_bytes(this.ffiValue, resultSlice.ptr); + + try {} + + finally { + functionCleanupArena.free(); + + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/KeysClause.d.ts b/bindings/js/KeysClause.d.ts new file mode 100644 index 0000000..d554a87 --- /dev/null +++ b/bindings/js/KeysClause.d.ts @@ -0,0 +1,32 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { FieldElement } from "./FieldElement" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Keys clause for filtering by entity keys + */ +export class KeysClause { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new keys clause + */ + static new_(): KeysClause; + + /** + * Adds a key to filter by + */ + addKey(key: FieldElement): void; + + /** + * Adds a model to filter by + */ + addModel(model: string): void; +} \ No newline at end of file diff --git a/bindings/js/KeysClause.mjs b/bindings/js/KeysClause.mjs new file mode 100644 index 0000000..c0f46e3 --- /dev/null +++ b/bindings/js/KeysClause.mjs @@ -0,0 +1,99 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import { FieldElement } from "./FieldElement.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const KeysClause_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.KeysClause_destroy(ptr); +}); + +/** + * Keys clause for filtering by entity keys + */ +export class KeysClause { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("KeysClause is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + KeysClause_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new keys clause + */ + static new_() { + + const result = wasm.KeysClause_new(); + + try { + return new KeysClause(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Adds a key to filter by + */ + addKey(key) { + wasm.KeysClause_add_key(this.ffiValue, key.ffiValue); + + try {} + + finally { + } + } + + /** + * Adds a model to filter by + */ + addModel(model) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const modelSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, model))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.KeysClause_add_model(diplomatReceive.buffer, this.ffiValue, modelSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/LogicalOperator.d.ts b/bindings/js/LogicalOperator.d.ts new file mode 100644 index 0000000..ca09606 --- /dev/null +++ b/bindings/js/LogicalOperator.d.ts @@ -0,0 +1,24 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Logical operator for combining clauses + */ +export class LogicalOperator { + + /** @internal */ + static fromValue(value: LogicalOperator | string): LogicalOperator; + + get value(): string; + + /** @internal */ + get ffiValue(): number; + + static And : LogicalOperator; + static Or : LogicalOperator; + + + constructor(value: LogicalOperator | string ); +} \ No newline at end of file diff --git a/bindings/js/LogicalOperator.mjs b/bindings/js/LogicalOperator.mjs new file mode 100644 index 0000000..ccaf82c --- /dev/null +++ b/bindings/js/LogicalOperator.mjs @@ -0,0 +1,72 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + + + +/** + * Logical operator for combining clauses + */ +export class LogicalOperator { + #value = undefined; + + static #values = new Map([ + ["And", 0], + ["Or", 1] + ]); + + static getAllEntries() { + return LogicalOperator.#values.entries(); + } + + #internalConstructor(value) { + if (arguments.length > 1 && arguments[0] === diplomatRuntime.internalConstructor) { + // We pass in two internalConstructor arguments to create *new* + // instances of this type, otherwise the enums are treated as singletons. + if (arguments[1] === diplomatRuntime.internalConstructor ) { + this.#value = arguments[2]; + return this; + } + return LogicalOperator.#objectValues[arguments[1]]; + } + + if (value instanceof LogicalOperator) { + return value; + } + + let intVal = LogicalOperator.#values.get(value); + + // Nullish check, checks for null or undefined + if (intVal != null) { + return LogicalOperator.#objectValues[intVal]; + } + + throw TypeError(value + " is not a LogicalOperator and does not correspond to any of its enumerator values."); + } + + /** @internal */ + static fromValue(value) { + return new LogicalOperator(value); + } + + get value(){ + return [...LogicalOperator.#values.keys()][this.#value]; + } + + /** @internal */ + get ffiValue(){ + return this.#value; + } + static #objectValues = [ + new LogicalOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 0), + new LogicalOperator(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 1), + ]; + + static And = LogicalOperator.#objectValues[0]; + static Or = LogicalOperator.#objectValues[1]; + + + constructor(value) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Member.d.ts b/bindings/js/Member.d.ts new file mode 100644 index 0000000..3eaefbd --- /dev/null +++ b/bindings/js/Member.d.ts @@ -0,0 +1,25 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a Dojo struct member (field) + */ +export class Member { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the member name + */ + name(): string; + + /** + * Returns true if this member is a key + */ + isKey(): boolean; +} \ No newline at end of file diff --git a/bindings/js/Member.mjs b/bindings/js/Member.mjs new file mode 100644 index 0000000..0ccad3c --- /dev/null +++ b/bindings/js/Member.mjs @@ -0,0 +1,76 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Member_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Member_destroy(ptr); +}); + +/** + * Represents a Dojo struct member (field) + */ +export class Member { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Member is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Member_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the member name + */ + name() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Member_name(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Returns true if this member is a key + */ + isKey() { + + const result = wasm.Member_is_key(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Model.d.ts b/bindings/js/Model.d.ts new file mode 100644 index 0000000..e83034b --- /dev/null +++ b/bindings/js/Model.d.ts @@ -0,0 +1,66 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a Dojo model + */ +export class Model { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the model name + */ + name(): string; + + /** + * Gets the model namespace + */ + namespace(): string; + + /** + * Gets the model selector (hex) + */ + selector(): string; + + /** + * Gets the model class hash (hex) + */ + classHash(): string; + + /** + * Gets the model contract address (hex) + */ + contractAddress(): string; + + /** + * Gets the packed size + */ + packedSize(): number; + + /** + * Gets the unpacked size + */ + unpackedSize(): number; + + /** + * Returns true if the model uses legacy store + */ + useLegacyStore(): boolean; + + /** + * Creates a new model from JSON + */ + static fromJson(json: string): Model; + + /** + * Serializes the model to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Model.mjs b/bindings/js/Model.mjs new file mode 100644 index 0000000..5d4119a --- /dev/null +++ b/bindings/js/Model.mjs @@ -0,0 +1,227 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Model_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Model_destroy(ptr); +}); + +/** + * Represents a Dojo model + */ +export class Model { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Model is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Model_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the model name + */ + name() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Model_name(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the model namespace + */ + namespace() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Model_namespace(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the model selector (hex) + */ + selector() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Model_selector(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the model class hash (hex) + */ + classHash() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Model_class_hash(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the model contract address (hex) + */ + contractAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Model_contract_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the packed size + */ + packedSize() { + + const result = wasm.Model_packed_size(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the unpacked size + */ + unpackedSize() { + + const result = wasm.Model_unpacked_size(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Returns true if the model uses legacy store + */ + useLegacyStore() { + + const result = wasm.Model_use_legacy_store(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates a new model from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Model_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Model(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the model to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Model_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/ModelQuery.d.ts b/bindings/js/ModelQuery.d.ts new file mode 100644 index 0000000..c32dddf --- /dev/null +++ b/bindings/js/ModelQuery.d.ts @@ -0,0 +1,26 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Model query for retrieving model definitions + */ +export class ModelQuery { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new model query + */ + static new_(): ModelQuery; + + /** + * Adds a model name to query + */ + addModel(modelName: string): void; +} \ No newline at end of file diff --git a/bindings/js/ModelQuery.mjs b/bindings/js/ModelQuery.mjs new file mode 100644 index 0000000..c6c772c --- /dev/null +++ b/bindings/js/ModelQuery.mjs @@ -0,0 +1,86 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const ModelQuery_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.ModelQuery_destroy(ptr); +}); + +/** + * Model query for retrieving model definitions + */ +export class ModelQuery { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("ModelQuery is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + ModelQuery_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new model query + */ + static new_() { + + const result = wasm.ModelQuery_new(); + + try { + return new ModelQuery(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Adds a model name to query + */ + addModel(modelName) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const modelNameSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, modelName))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.ModelQuery_add_model(diplomatReceive.buffer, this.ffiValue, modelNameSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/OrderBy.d.ts b/bindings/js/OrderBy.d.ts new file mode 100644 index 0000000..3081b94 --- /dev/null +++ b/bindings/js/OrderBy.d.ts @@ -0,0 +1,22 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { OrderDirection } from "./OrderDirection" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Ordering specification for query results + */ +export class OrderBy { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new OrderBy specification + */ + static new_(field: string, direction: OrderDirection): OrderBy; +} \ No newline at end of file diff --git a/bindings/js/OrderBy.mjs b/bindings/js/OrderBy.mjs new file mode 100644 index 0000000..acc9406 --- /dev/null +++ b/bindings/js/OrderBy.mjs @@ -0,0 +1,73 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import { OrderDirection } from "./OrderDirection.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const OrderBy_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.OrderBy_destroy(ptr); +}); + +/** + * Ordering specification for query results + */ +export class OrderBy { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("OrderBy is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + OrderBy_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new OrderBy specification + */ + static new_(field, direction) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const fieldSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, field))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.OrderBy_new(diplomatReceive.buffer, fieldSlice.ptr, direction.ffiValue); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new OrderBy(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/OrderDirection.d.ts b/bindings/js/OrderDirection.d.ts new file mode 100644 index 0000000..05426dc --- /dev/null +++ b/bindings/js/OrderDirection.d.ts @@ -0,0 +1,24 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Direction for ordering results + */ +export class OrderDirection { + + /** @internal */ + static fromValue(value: OrderDirection | string): OrderDirection; + + get value(): string; + + /** @internal */ + get ffiValue(): number; + + static Asc : OrderDirection; + static Desc : OrderDirection; + + + constructor(value: OrderDirection | string ); +} \ No newline at end of file diff --git a/bindings/js/OrderDirection.mjs b/bindings/js/OrderDirection.mjs new file mode 100644 index 0000000..1ffcba4 --- /dev/null +++ b/bindings/js/OrderDirection.mjs @@ -0,0 +1,72 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + + + +/** + * Direction for ordering results + */ +export class OrderDirection { + #value = undefined; + + static #values = new Map([ + ["Asc", 0], + ["Desc", 1] + ]); + + static getAllEntries() { + return OrderDirection.#values.entries(); + } + + #internalConstructor(value) { + if (arguments.length > 1 && arguments[0] === diplomatRuntime.internalConstructor) { + // We pass in two internalConstructor arguments to create *new* + // instances of this type, otherwise the enums are treated as singletons. + if (arguments[1] === diplomatRuntime.internalConstructor ) { + this.#value = arguments[2]; + return this; + } + return OrderDirection.#objectValues[arguments[1]]; + } + + if (value instanceof OrderDirection) { + return value; + } + + let intVal = OrderDirection.#values.get(value); + + // Nullish check, checks for null or undefined + if (intVal != null) { + return OrderDirection.#objectValues[intVal]; + } + + throw TypeError(value + " is not a OrderDirection and does not correspond to any of its enumerator values."); + } + + /** @internal */ + static fromValue(value) { + return new OrderDirection(value); + } + + get value(){ + return [...OrderDirection.#values.keys()][this.#value]; + } + + /** @internal */ + get ffiValue(){ + return this.#value; + } + static #objectValues = [ + new OrderDirection(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 0), + new OrderDirection(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 1), + ]; + + static Asc = OrderDirection.#objectValues[0]; + static Desc = OrderDirection.#objectValues[1]; + + + constructor(value) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Pagination.d.ts b/bindings/js/Pagination.d.ts new file mode 100644 index 0000000..01e8ba0 --- /dev/null +++ b/bindings/js/Pagination.d.ts @@ -0,0 +1,43 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { OrderBy } from "./OrderBy" +import type { PaginationDirection } from "./PaginationDirection" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Pagination configuration for queries + */ +export class Pagination { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new Pagination with default values + */ + static new_(): Pagination; + + /** + * Sets the cursor for pagination + */ + setCursor(cursor: string): void; + + /** + * Sets the limit for pagination + */ + setLimit(limit: number): void; + + /** + * Sets the direction for pagination + */ + setDirection(direction: PaginationDirection): void; + + /** + * Adds an ordering specification + */ + addOrderBy(orderBy: OrderBy): void; +} \ No newline at end of file diff --git a/bindings/js/Pagination.mjs b/bindings/js/Pagination.mjs new file mode 100644 index 0000000..90211bf --- /dev/null +++ b/bindings/js/Pagination.mjs @@ -0,0 +1,124 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import { OrderBy } from "./OrderBy.mjs" +import { PaginationDirection } from "./PaginationDirection.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Pagination_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Pagination_destroy(ptr); +}); + +/** + * Pagination configuration for queries + */ +export class Pagination { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Pagination is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Pagination_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new Pagination with default values + */ + static new_() { + + const result = wasm.Pagination_new(); + + try { + return new Pagination(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Sets the cursor for pagination + */ + setCursor(cursor) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const cursorSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, cursor))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Pagination_set_cursor(diplomatReceive.buffer, this.ffiValue, cursorSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Sets the limit for pagination + */ + setLimit(limit) { + wasm.Pagination_set_limit(this.ffiValue, limit); + + try {} + + finally { + } + } + + /** + * Sets the direction for pagination + */ + setDirection(direction) { + wasm.Pagination_set_direction(this.ffiValue, direction.ffiValue); + + try {} + + finally { + } + } + + /** + * Adds an ordering specification + */ + addOrderBy(orderBy) { + wasm.Pagination_add_order_by(this.ffiValue, orderBy.ffiValue); + + try {} + + finally { + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/PaginationDirection.d.ts b/bindings/js/PaginationDirection.d.ts new file mode 100644 index 0000000..fd1df6a --- /dev/null +++ b/bindings/js/PaginationDirection.d.ts @@ -0,0 +1,24 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Direction for pagination + */ +export class PaginationDirection { + + /** @internal */ + static fromValue(value: PaginationDirection | string): PaginationDirection; + + get value(): string; + + /** @internal */ + get ffiValue(): number; + + static Forward : PaginationDirection; + static Backward : PaginationDirection; + + + constructor(value: PaginationDirection | string ); +} \ No newline at end of file diff --git a/bindings/js/PaginationDirection.mjs b/bindings/js/PaginationDirection.mjs new file mode 100644 index 0000000..baf0ae9 --- /dev/null +++ b/bindings/js/PaginationDirection.mjs @@ -0,0 +1,72 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + + + +/** + * Direction for pagination + */ +export class PaginationDirection { + #value = undefined; + + static #values = new Map([ + ["Forward", 0], + ["Backward", 1] + ]); + + static getAllEntries() { + return PaginationDirection.#values.entries(); + } + + #internalConstructor(value) { + if (arguments.length > 1 && arguments[0] === diplomatRuntime.internalConstructor) { + // We pass in two internalConstructor arguments to create *new* + // instances of this type, otherwise the enums are treated as singletons. + if (arguments[1] === diplomatRuntime.internalConstructor ) { + this.#value = arguments[2]; + return this; + } + return PaginationDirection.#objectValues[arguments[1]]; + } + + if (value instanceof PaginationDirection) { + return value; + } + + let intVal = PaginationDirection.#values.get(value); + + // Nullish check, checks for null or undefined + if (intVal != null) { + return PaginationDirection.#objectValues[intVal]; + } + + throw TypeError(value + " is not a PaginationDirection and does not correspond to any of its enumerator values."); + } + + /** @internal */ + static fromValue(value) { + return new PaginationDirection(value); + } + + get value(){ + return [...PaginationDirection.#values.keys()][this.#value]; + } + + /** @internal */ + get ffiValue(){ + return this.#value; + } + static #objectValues = [ + new PaginationDirection(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 0), + new PaginationDirection(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 1), + ]; + + static Forward = PaginationDirection.#objectValues[0]; + static Backward = PaginationDirection.#objectValues[1]; + + + constructor(value) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/PatternMatching.d.ts b/bindings/js/PatternMatching.d.ts new file mode 100644 index 0000000..83e53e0 --- /dev/null +++ b/bindings/js/PatternMatching.d.ts @@ -0,0 +1,24 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Pattern matching mode for key queries + */ +export class PatternMatching { + + /** @internal */ + static fromValue(value: PatternMatching | string): PatternMatching; + + get value(): string; + + /** @internal */ + get ffiValue(): number; + + static FixedLen : PatternMatching; + static VariableLen : PatternMatching; + + + constructor(value: PatternMatching | string ); +} \ No newline at end of file diff --git a/bindings/js/PatternMatching.mjs b/bindings/js/PatternMatching.mjs new file mode 100644 index 0000000..2ceaa3c --- /dev/null +++ b/bindings/js/PatternMatching.mjs @@ -0,0 +1,72 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + + + +/** + * Pattern matching mode for key queries + */ +export class PatternMatching { + #value = undefined; + + static #values = new Map([ + ["FixedLen", 0], + ["VariableLen", 1] + ]); + + static getAllEntries() { + return PatternMatching.#values.entries(); + } + + #internalConstructor(value) { + if (arguments.length > 1 && arguments[0] === diplomatRuntime.internalConstructor) { + // We pass in two internalConstructor arguments to create *new* + // instances of this type, otherwise the enums are treated as singletons. + if (arguments[1] === diplomatRuntime.internalConstructor ) { + this.#value = arguments[2]; + return this; + } + return PatternMatching.#objectValues[arguments[1]]; + } + + if (value instanceof PatternMatching) { + return value; + } + + let intVal = PatternMatching.#values.get(value); + + // Nullish check, checks for null or undefined + if (intVal != null) { + return PatternMatching.#objectValues[intVal]; + } + + throw TypeError(value + " is not a PatternMatching and does not correspond to any of its enumerator values."); + } + + /** @internal */ + static fromValue(value) { + return new PatternMatching(value); + } + + get value(){ + return [...PatternMatching.#values.keys()][this.#value]; + } + + /** @internal */ + get ffiValue(){ + return this.#value; + } + static #objectValues = [ + new PatternMatching(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 0), + new PatternMatching(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 1), + ]; + + static FixedLen = PatternMatching.#objectValues[0]; + static VariableLen = PatternMatching.#objectValues[1]; + + + constructor(value) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/PlayerAchievementEntry.d.ts b/bindings/js/PlayerAchievementEntry.d.ts new file mode 100644 index 0000000..2522c70 --- /dev/null +++ b/bindings/js/PlayerAchievementEntry.d.ts @@ -0,0 +1,61 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents player achievement progress + */ +export class PlayerAchievementEntry { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the player address (hex) + */ + playerAddress(): string; + + /** + * Gets the total points + */ + totalPoints(): number; + + /** + * Gets the completed achievements count + */ + completedAchievements(): number; + + /** + * Gets the total achievements count + */ + totalAchievements(): number; + + /** + * Gets the completion percentage + */ + completionPercentage(): number; + + /** + * Gets the achievements count + */ + achievementsCount(): number; + + /** + * Gets the updated_at timestamp + */ + updatedAt(): bigint; + + /** + * Creates a player achievement entry from JSON + */ + static fromJson(json: string): PlayerAchievementEntry; + + /** + * Serializes the player achievement entry to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/PlayerAchievementEntry.mjs b/bindings/js/PlayerAchievementEntry.mjs new file mode 100644 index 0000000..f119463 --- /dev/null +++ b/bindings/js/PlayerAchievementEntry.mjs @@ -0,0 +1,204 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const PlayerAchievementEntry_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.PlayerAchievementEntry_destroy(ptr); +}); + +/** + * Represents player achievement progress + */ +export class PlayerAchievementEntry { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("PlayerAchievementEntry is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + PlayerAchievementEntry_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the player address (hex) + */ + playerAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.PlayerAchievementEntry_player_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the total points + */ + totalPoints() { + + const result = wasm.PlayerAchievementEntry_total_points(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the completed achievements count + */ + completedAchievements() { + + const result = wasm.PlayerAchievementEntry_completed_achievements(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the total achievements count + */ + totalAchievements() { + + const result = wasm.PlayerAchievementEntry_total_achievements(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the completion percentage + */ + completionPercentage() { + + const result = wasm.PlayerAchievementEntry_completion_percentage(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the achievements count + */ + achievementsCount() { + + const result = wasm.PlayerAchievementEntry_achievements_count(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the updated_at timestamp + */ + updatedAt() { + + const result = wasm.PlayerAchievementEntry_updated_at(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates a player achievement entry from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.PlayerAchievementEntry_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new PlayerAchievementEntry(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the player achievement entry to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.PlayerAchievementEntry_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Primitive.d.ts b/bindings/js/Primitive.d.ts new file mode 100644 index 0000000..fa221d6 --- /dev/null +++ b/bindings/js/Primitive.d.ts @@ -0,0 +1,32 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { PrimitiveType } from "./PrimitiveType" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a primitive Cairo type with its value + */ +export class Primitive { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the primitive type + */ + primitiveType(): PrimitiveType; + + /** + * Creates a primitive from JSON + */ + static fromJson(json: string): Primitive; + + /** + * Serializes the primitive to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Primitive.mjs b/bindings/js/Primitive.mjs new file mode 100644 index 0000000..8a7e2d3 --- /dev/null +++ b/bindings/js/Primitive.mjs @@ -0,0 +1,113 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import { PrimitiveType } from "./PrimitiveType.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Primitive_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Primitive_destroy(ptr); +}); + +/** + * Represents a primitive Cairo type with its value + */ +export class Primitive { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Primitive is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Primitive_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the primitive type + */ + primitiveType() { + + const result = wasm.Primitive_primitive_type(this.ffiValue); + + try { + return new PrimitiveType(diplomatRuntime.internalConstructor, result); + } + + finally { + } + } + + /** + * Creates a primitive from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Primitive_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Primitive(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the primitive to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Primitive_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/PrimitiveType.d.ts b/bindings/js/PrimitiveType.d.ts new file mode 100644 index 0000000..35e9a87 --- /dev/null +++ b/bindings/js/PrimitiveType.d.ts @@ -0,0 +1,38 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Type of primitive + */ +export class PrimitiveType { + + /** @internal */ + static fromValue(value: PrimitiveType | string): PrimitiveType; + + get value(): string; + + /** @internal */ + get ffiValue(): number; + + static I8 : PrimitiveType; + static I16 : PrimitiveType; + static I32 : PrimitiveType; + static I64 : PrimitiveType; + static I128 : PrimitiveType; + static U8 : PrimitiveType; + static U16 : PrimitiveType; + static U32 : PrimitiveType; + static U64 : PrimitiveType; + static U128 : PrimitiveType; + static U256 : PrimitiveType; + static Bool : PrimitiveType; + static Felt252 : PrimitiveType; + static ClassHash : PrimitiveType; + static ContractAddress : PrimitiveType; + static EthAddress : PrimitiveType; + + + constructor(value: PrimitiveType | string ); +} \ No newline at end of file diff --git a/bindings/js/PrimitiveType.mjs b/bindings/js/PrimitiveType.mjs new file mode 100644 index 0000000..f7ed6cb --- /dev/null +++ b/bindings/js/PrimitiveType.mjs @@ -0,0 +1,114 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + + + +/** + * Type of primitive + */ +export class PrimitiveType { + #value = undefined; + + static #values = new Map([ + ["I8", 0], + ["I16", 1], + ["I32", 2], + ["I64", 3], + ["I128", 4], + ["U8", 5], + ["U16", 6], + ["U32", 7], + ["U64", 8], + ["U128", 9], + ["U256", 10], + ["Bool", 11], + ["Felt252", 12], + ["ClassHash", 13], + ["ContractAddress", 14], + ["EthAddress", 15] + ]); + + static getAllEntries() { + return PrimitiveType.#values.entries(); + } + + #internalConstructor(value) { + if (arguments.length > 1 && arguments[0] === diplomatRuntime.internalConstructor) { + // We pass in two internalConstructor arguments to create *new* + // instances of this type, otherwise the enums are treated as singletons. + if (arguments[1] === diplomatRuntime.internalConstructor ) { + this.#value = arguments[2]; + return this; + } + return PrimitiveType.#objectValues[arguments[1]]; + } + + if (value instanceof PrimitiveType) { + return value; + } + + let intVal = PrimitiveType.#values.get(value); + + // Nullish check, checks for null or undefined + if (intVal != null) { + return PrimitiveType.#objectValues[intVal]; + } + + throw TypeError(value + " is not a PrimitiveType and does not correspond to any of its enumerator values."); + } + + /** @internal */ + static fromValue(value) { + return new PrimitiveType(value); + } + + get value(){ + return [...PrimitiveType.#values.keys()][this.#value]; + } + + /** @internal */ + get ffiValue(){ + return this.#value; + } + static #objectValues = [ + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 0), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 1), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 2), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 3), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 4), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 5), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 6), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 7), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 8), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 9), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 10), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 11), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 12), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 13), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 14), + new PrimitiveType(diplomatRuntime.internalConstructor, diplomatRuntime.internalConstructor, 15), + ]; + + static I8 = PrimitiveType.#objectValues[0]; + static I16 = PrimitiveType.#objectValues[1]; + static I32 = PrimitiveType.#objectValues[2]; + static I64 = PrimitiveType.#objectValues[3]; + static I128 = PrimitiveType.#objectValues[4]; + static U8 = PrimitiveType.#objectValues[5]; + static U16 = PrimitiveType.#objectValues[6]; + static U32 = PrimitiveType.#objectValues[7]; + static U64 = PrimitiveType.#objectValues[8]; + static U128 = PrimitiveType.#objectValues[9]; + static U256 = PrimitiveType.#objectValues[10]; + static Bool = PrimitiveType.#objectValues[11]; + static Felt252 = PrimitiveType.#objectValues[12]; + static ClassHash = PrimitiveType.#objectValues[13]; + static ContractAddress = PrimitiveType.#objectValues[14]; + static EthAddress = PrimitiveType.#objectValues[15]; + + + constructor(value) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Provider.d.ts b/bindings/js/Provider.d.ts new file mode 100644 index 0000000..f8c11b8 --- /dev/null +++ b/bindings/js/Provider.d.ts @@ -0,0 +1,31 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * JSON-RPC provider for Starknet + */ +export class Provider { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new provider from an RPC URL + */ + static new_(rpcUrl: string): Provider; + + /** + * Gets the chain ID + */ + chainId(): string; + + /** + * Gets the latest block number + */ + blockNumber(): bigint; +} \ No newline at end of file diff --git a/bindings/js/Provider.mjs b/bindings/js/Provider.mjs new file mode 100644 index 0000000..22137e2 --- /dev/null +++ b/bindings/js/Provider.mjs @@ -0,0 +1,119 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Provider_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Provider_destroy(ptr); +}); + +/** + * JSON-RPC provider for Starknet + */ +export class Provider { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Provider is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Provider_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new provider from an RPC URL + */ + static new_(rpcUrl) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const rpcUrlSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, rpcUrl))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Provider_new(diplomatReceive.buffer, rpcUrlSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Provider(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Gets the chain ID + */ + chainId() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Provider_chain_id(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + /** + * Gets the latest block number + */ + blockNumber() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 9, 8, true); + + + const result = wasm.Provider_block_number(diplomatReceive.buffer, this.ffiValue); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return (new BigUint64Array(wasm.memory.buffer, diplomatReceive.buffer, 1))[0]; + } + + finally { + diplomatReceive.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Signature.d.ts b/bindings/js/Signature.d.ts new file mode 100644 index 0000000..1404be9 --- /dev/null +++ b/bindings/js/Signature.d.ts @@ -0,0 +1,31 @@ +// generated by diplomat-tool +import type { FieldElement } from "./FieldElement" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a signature (r, s pair) + */ +export class Signature { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new signature from r and s components + */ + static new_(r: FieldElement, s: FieldElement): Signature; + + /** + * Gets the r component + */ + r(): string; + + /** + * Gets the s component + */ + s(): string; +} \ No newline at end of file diff --git a/bindings/js/Signature.mjs b/bindings/js/Signature.mjs new file mode 100644 index 0000000..d0f8dbb --- /dev/null +++ b/bindings/js/Signature.mjs @@ -0,0 +1,94 @@ +// generated by diplomat-tool +import { FieldElement } from "./FieldElement.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Signature_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Signature_destroy(ptr); +}); + +/** + * Represents a signature (r, s pair) + */ +export class Signature { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Signature is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Signature_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new signature from r and s components + */ + static new_(r, s) { + + const result = wasm.Signature_new(r.ffiValue, s.ffiValue); + + try { + return new Signature(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Gets the r component + */ + r() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Signature_r(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the s component + */ + s() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Signature_s(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/SigningKey.d.ts b/bindings/js/SigningKey.d.ts new file mode 100644 index 0000000..2cb42d4 --- /dev/null +++ b/bindings/js/SigningKey.d.ts @@ -0,0 +1,44 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { FieldElement } from "./FieldElement" +import type { Signature } from "./Signature" +import type { VerifyingKey } from "./VerifyingKey" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a signing key for Starknet transactions + */ +export class SigningKey { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new signing key from a secret scalar + */ + static new_(secretScalar: string): SigningKey; + + /** + * Generates a new random signing key + */ + static fromRandom(): SigningKey; + + /** + * Returns the secret scalar of the signing key + */ + secretScalar(): string; + + /** + * Signs a message hash + */ + sign(hash: FieldElement): Signature; + + /** + * Returns the verifying key + */ + verifyingKey(): VerifyingKey; +} \ No newline at end of file diff --git a/bindings/js/SigningKey.mjs b/bindings/js/SigningKey.mjs new file mode 100644 index 0000000..80b87fb --- /dev/null +++ b/bindings/js/SigningKey.mjs @@ -0,0 +1,144 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import { FieldElement } from "./FieldElement.mjs" +import { Signature } from "./Signature.mjs" +import { VerifyingKey } from "./VerifyingKey.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const SigningKey_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.SigningKey_destroy(ptr); +}); + +/** + * Represents a signing key for Starknet transactions + */ +export class SigningKey { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("SigningKey is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + SigningKey_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new signing key from a secret scalar + */ + static new_(secretScalar) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const secretScalarSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, secretScalar))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.SigningKey_new(diplomatReceive.buffer, secretScalarSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new SigningKey(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Generates a new random signing key + */ + static fromRandom() { + + const result = wasm.SigningKey_from_random(); + + try { + return new SigningKey(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + /** + * Returns the secret scalar of the signing key + */ + secretScalar() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.SigningKey_secret_scalar(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Signs a message hash + */ + sign(hash) { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.SigningKey_sign(diplomatReceive.buffer, this.ffiValue, hash.ffiValue); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Signature(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + diplomatReceive.free(); + } + } + + /** + * Returns the verifying key + */ + verifyingKey() { + + const result = wasm.SigningKey_verifying_key(this.ffiValue); + + try { + return new VerifyingKey(diplomatRuntime.internalConstructor, result, []); + } + + finally { + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Struct.d.ts b/bindings/js/Struct.d.ts new file mode 100644 index 0000000..909a92f --- /dev/null +++ b/bindings/js/Struct.d.ts @@ -0,0 +1,36 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a Dojo struct + */ +export class Struct { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the struct name + */ + name(): string; + + /** + * Gets the number of children (members) + */ + childrenCount(): number; + + /** + * Creates a new struct from JSON schema + */ + static fromJson(json: string): Struct; + + /** + * Serializes the struct to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Struct.mjs b/bindings/js/Struct.mjs new file mode 100644 index 0000000..9a24491 --- /dev/null +++ b/bindings/js/Struct.mjs @@ -0,0 +1,129 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Struct_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Struct_destroy(ptr); +}); + +/** + * Represents a Dojo struct + */ +export class Struct { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Struct is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Struct_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the struct name + */ + name() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Struct_name(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the number of children (members) + */ + childrenCount() { + + const result = wasm.Struct_children_count(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates a new struct from JSON schema + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Struct_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Struct(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the struct to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Struct_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Subscription.d.ts b/bindings/js/Subscription.d.ts new file mode 100644 index 0000000..aef1f37 --- /dev/null +++ b/bindings/js/Subscription.d.ts @@ -0,0 +1,20 @@ +// generated by diplomat-tool +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Subscription handle for managing event streams + */ +export class Subscription { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the subscription ID + */ + id(): bigint; +} \ No newline at end of file diff --git a/bindings/js/Subscription.mjs b/bindings/js/Subscription.mjs new file mode 100644 index 0000000..8b82500 --- /dev/null +++ b/bindings/js/Subscription.mjs @@ -0,0 +1,59 @@ +// generated by diplomat-tool +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Subscription_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Subscription_destroy(ptr); +}); + +/** + * Subscription handle for managing event streams + */ +export class Subscription { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Subscription is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Subscription_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the subscription ID + */ + id() { + + const result = wasm.Subscription_id(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Token.d.ts b/bindings/js/Token.d.ts new file mode 100644 index 0000000..d25b85c --- /dev/null +++ b/bindings/js/Token.d.ts @@ -0,0 +1,51 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a token (ERC20, ERC721, or ERC1155) + */ +export class Token { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the contract address (hex) + */ + contractAddress(): string; + + /** + * Gets the token name + */ + name(): string; + + /** + * Gets the token symbol + */ + symbol(): string; + + /** + * Gets the token decimals + */ + decimals(): number; + + /** + * Gets the metadata as JSON string + */ + metadata(): string; + + /** + * Creates a token from JSON + */ + static fromJson(json: string): Token; + + /** + * Serializes the token to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Token.mjs b/bindings/js/Token.mjs new file mode 100644 index 0000000..aedc39b --- /dev/null +++ b/bindings/js/Token.mjs @@ -0,0 +1,180 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Token_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Token_destroy(ptr); +}); + +/** + * Represents a token (ERC20, ERC721, or ERC1155) + */ +export class Token { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Token is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Token_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the contract address (hex) + */ + contractAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Token_contract_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the token name + */ + name() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Token_name(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the token symbol + */ + symbol() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Token_symbol(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the token decimals + */ + decimals() { + + const result = wasm.Token_decimals(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the metadata as JSON string + */ + metadata() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Token_metadata(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Creates a token from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Token_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Token(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the token to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Token_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/TokenBalance.d.ts b/bindings/js/TokenBalance.d.ts new file mode 100644 index 0000000..fd70bea --- /dev/null +++ b/bindings/js/TokenBalance.d.ts @@ -0,0 +1,41 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a token balance for an account + */ +export class TokenBalance { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the account address (hex) + */ + accountAddress(): string; + + /** + * Gets the contract address (hex) + */ + contractAddress(): string; + + /** + * Gets the balance as a string + */ + balance(): string; + + /** + * Creates a token balance from JSON + */ + static fromJson(json: string): TokenBalance; + + /** + * Serializes the token balance to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/TokenBalance.mjs b/bindings/js/TokenBalance.mjs new file mode 100644 index 0000000..5cab146 --- /dev/null +++ b/bindings/js/TokenBalance.mjs @@ -0,0 +1,148 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const TokenBalance_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.TokenBalance_destroy(ptr); +}); + +/** + * Represents a token balance for an account + */ +export class TokenBalance { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("TokenBalance is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + TokenBalance_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the account address (hex) + */ + accountAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.TokenBalance_account_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the contract address (hex) + */ + contractAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.TokenBalance_contract_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the balance as a string + */ + balance() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.TokenBalance_balance(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Creates a token balance from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.TokenBalance_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new TokenBalance(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the token balance to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.TokenBalance_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/TokenContract.d.ts b/bindings/js/TokenContract.d.ts new file mode 100644 index 0000000..1f9a245 --- /dev/null +++ b/bindings/js/TokenContract.d.ts @@ -0,0 +1,36 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a token contract + */ +export class TokenContract { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the contract address (hex) + */ + contractAddress(): string; + + /** + * Gets the contract type as string + */ + contractType(): string; + + /** + * Creates a token contract from JSON + */ + static fromJson(json: string): TokenContract; + + /** + * Serializes the token contract to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/TokenContract.mjs b/bindings/js/TokenContract.mjs new file mode 100644 index 0000000..b3bf86d --- /dev/null +++ b/bindings/js/TokenContract.mjs @@ -0,0 +1,131 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const TokenContract_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.TokenContract_destroy(ptr); +}); + +/** + * Represents a token contract + */ +export class TokenContract { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("TokenContract is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + TokenContract_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the contract address (hex) + */ + contractAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.TokenContract_contract_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the contract type as string + */ + contractType() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.TokenContract_contract_type(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Creates a token contract from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.TokenContract_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new TokenContract(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the token contract to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.TokenContract_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/TokenTransfer.d.ts b/bindings/js/TokenTransfer.d.ts new file mode 100644 index 0000000..34b7185 --- /dev/null +++ b/bindings/js/TokenTransfer.d.ts @@ -0,0 +1,51 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a token transfer event + */ +export class TokenTransfer { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the from address (hex) + */ + fromAddress(): string; + + /** + * Gets the to address (hex) + */ + toAddress(): string; + + /** + * Gets the contract address (hex) + */ + contractAddress(): string; + + /** + * Gets the amount as a string + */ + amount(): string; + + /** + * Gets the executed_at timestamp + */ + executedAt(): bigint; + + /** + * Creates a token transfer from JSON + */ + static fromJson(json: string): TokenTransfer; + + /** + * Serializes the token transfer to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/TokenTransfer.mjs b/bindings/js/TokenTransfer.mjs new file mode 100644 index 0000000..c774754 --- /dev/null +++ b/bindings/js/TokenTransfer.mjs @@ -0,0 +1,180 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const TokenTransfer_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.TokenTransfer_destroy(ptr); +}); + +/** + * Represents a token transfer event + */ +export class TokenTransfer { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("TokenTransfer is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + TokenTransfer_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the from address (hex) + */ + fromAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.TokenTransfer_from_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the to address (hex) + */ + toAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.TokenTransfer_to_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the contract address (hex) + */ + contractAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.TokenTransfer_contract_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the amount as a string + */ + amount() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.TokenTransfer_amount(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the executed_at timestamp + */ + executedAt() { + + const result = wasm.TokenTransfer_executed_at(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates a token transfer from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.TokenTransfer_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new TokenTransfer(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the token transfer to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.TokenTransfer_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/ToriiClient.d.ts b/bindings/js/ToriiClient.d.ts new file mode 100644 index 0000000..cd19a56 --- /dev/null +++ b/bindings/js/ToriiClient.d.ts @@ -0,0 +1,32 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { FieldElement } from "./FieldElement" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Opaque handle to a Torii client instance + */ +export class ToriiClient { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new Torii client instance + */ + static new_(toriiUrl: string): ToriiClient; + + /** + * Gets information about the Torii server + */ + info(): string; + + /** + * Publishes a message to the network + */ + publishMessage(messageJson: string, signatureR: FieldElement, signatureS: FieldElement, worldAddress: FieldElement): string; +} \ No newline at end of file diff --git a/bindings/js/ToriiClient.mjs b/bindings/js/ToriiClient.mjs new file mode 100644 index 0000000..64f304f --- /dev/null +++ b/bindings/js/ToriiClient.mjs @@ -0,0 +1,128 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import { FieldElement } from "./FieldElement.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const ToriiClient_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.ToriiClient_destroy(ptr); +}); + +/** + * Opaque handle to a Torii client instance + */ +export class ToriiClient { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("ToriiClient is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + ToriiClient_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new Torii client instance + */ + static new_(toriiUrl) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const toriiUrlSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, toriiUrl))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.ToriiClient_new(diplomatReceive.buffer, toriiUrlSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new ToriiClient(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Gets information about the Torii server + */ + info() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.ToriiClient_info(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + /** + * Publishes a message to the network + */ + publishMessage(messageJson, signatureR, signatureS, worldAddress) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const messageJsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, messageJson))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.ToriiClient_publish_message(diplomatReceive.buffer, this.ffiValue, messageJsonSlice.ptr, signatureR.ffiValue, signatureS.ffiValue, worldAddress.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/Transaction.d.ts b/bindings/js/Transaction.d.ts new file mode 100644 index 0000000..fca5530 --- /dev/null +++ b/bindings/js/Transaction.d.ts @@ -0,0 +1,61 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a transaction + */ +export class Transaction { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the transaction hash (hex) + */ + transactionHash(): string; + + /** + * Gets the sender address (hex) + */ + senderAddress(): string; + + /** + * Gets the max fee as string + */ + maxFee(): string; + + /** + * Gets the signature as JSON array string + */ + signature(): string; + + /** + * Gets the nonce as string + */ + nonce(): string; + + /** + * Gets the block timestamp + */ + blockTimestamp(): bigint; + + /** + * Gets the block number + */ + blockNumber(): bigint; + + /** + * Creates a transaction from JSON + */ + static fromJson(json: string): Transaction; + + /** + * Serializes the transaction to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/Transaction.mjs b/bindings/js/Transaction.mjs new file mode 100644 index 0000000..8173122 --- /dev/null +++ b/bindings/js/Transaction.mjs @@ -0,0 +1,212 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const Transaction_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.Transaction_destroy(ptr); +}); + +/** + * Represents a transaction + */ +export class Transaction { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("Transaction is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + Transaction_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the transaction hash (hex) + */ + transactionHash() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Transaction_transaction_hash(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the sender address (hex) + */ + senderAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Transaction_sender_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the max fee as string + */ + maxFee() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Transaction_max_fee(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the signature as JSON array string + */ + signature() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Transaction_signature(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the nonce as string + */ + nonce() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.Transaction_nonce(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the block timestamp + */ + blockTimestamp() { + + const result = wasm.Transaction_block_timestamp(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Gets the block number + */ + blockNumber() { + + const result = wasm.Transaction_block_number(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates a transaction from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.Transaction_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new Transaction(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the transaction to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.Transaction_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/TypedData.d.ts b/bindings/js/TypedData.d.ts new file mode 100644 index 0000000..b9826ac --- /dev/null +++ b/bindings/js/TypedData.d.ts @@ -0,0 +1,21 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a typed data structure for EIP-712 style signing + */ +export class TypedData { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new TypedData from JSON string + */ + static newFromJson(json: string): TypedData; +} \ No newline at end of file diff --git a/bindings/js/TypedData.mjs b/bindings/js/TypedData.mjs new file mode 100644 index 0000000..10b0e40 --- /dev/null +++ b/bindings/js/TypedData.mjs @@ -0,0 +1,72 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const TypedData_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.TypedData_destroy(ptr); +}); + +/** + * Represents a typed data structure for EIP-712 style signing + */ +export class TypedData { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("TypedData is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + TypedData_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new TypedData from JSON string + */ + static newFromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.TypedData_new_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new TypedData(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/U256.d.ts b/bindings/js/U256.d.ts new file mode 100644 index 0000000..475f766 --- /dev/null +++ b/bindings/js/U256.d.ts @@ -0,0 +1,36 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a 256-bit unsigned integer + */ +export class U256 { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Creates a new U256 from a hexadecimal string + */ + static newFromHex(hex: string): U256; + + /** + * Creates a new U256 from big-endian bytes + */ + static newFromBytes(bytes: Array): U256; + + /** + * Returns the U256 as a hexadecimal string + */ + toHex(): string; + + /** + * Returns the U256 as bytes (big-endian) + */ + toBytes(result: Array): void; +} \ No newline at end of file diff --git a/bindings/js/U256.mjs b/bindings/js/U256.mjs new file mode 100644 index 0000000..e0a2224 --- /dev/null +++ b/bindings/js/U256.mjs @@ -0,0 +1,133 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const U256_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.U256_destroy(ptr); +}); + +/** + * Represents a 256-bit unsigned integer + */ +export class U256 { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("U256 is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + U256_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Creates a new U256 from a hexadecimal string + */ + static newFromHex(hex) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const hexSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, hex))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.U256_new_from_hex(diplomatReceive.buffer, hexSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new U256(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Creates a new U256 from big-endian bytes + */ + static newFromBytes(bytes) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const bytesSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.slice(wasm, bytes, "u8"))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.U256_new_from_bytes(diplomatReceive.buffer, bytesSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new U256(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Returns the U256 as a hexadecimal string + */ + toHex() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.U256_to_hex(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Returns the U256 as bytes (big-endian) + */ + toBytes(result) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const resultSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.slice(wasm, result, "u8"))); + wasm.U256_to_bytes(this.ffiValue, resultSlice.ptr); + + try {} + + finally { + functionCleanupArena.free(); + + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/VerifyingKey.d.ts b/bindings/js/VerifyingKey.d.ts new file mode 100644 index 0000000..7352d8e --- /dev/null +++ b/bindings/js/VerifyingKey.d.ts @@ -0,0 +1,28 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { FieldElement } from "./FieldElement" +import type { Signature } from "./Signature" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a verifying key for signature verification + */ +export class VerifyingKey { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Returns the scalar value of the verifying key + */ + scalar(): string; + + /** + * Verifies a signature + */ + verify(hash: FieldElement, signature: Signature): boolean; +} \ No newline at end of file diff --git a/bindings/js/VerifyingKey.mjs b/bindings/js/VerifyingKey.mjs new file mode 100644 index 0000000..b5b5603 --- /dev/null +++ b/bindings/js/VerifyingKey.mjs @@ -0,0 +1,86 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import { FieldElement } from "./FieldElement.mjs" +import { Signature } from "./Signature.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const VerifyingKey_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.VerifyingKey_destroy(ptr); +}); + +/** + * Represents a verifying key for signature verification + */ +export class VerifyingKey { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("VerifyingKey is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + VerifyingKey_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Returns the scalar value of the verifying key + */ + scalar() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.VerifyingKey_scalar(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Verifies a signature + */ + verify(hash, signature) { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 1, true); + + + const result = wasm.VerifyingKey_verify(diplomatReceive.buffer, this.ffiValue, hash.ffiValue, signature.ffiValue); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return (new Uint8Array(wasm.memory.buffer, diplomatReceive.buffer, 1))[0] === 1; + } + + finally { + diplomatReceive.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/World.d.ts b/bindings/js/World.d.ts new file mode 100644 index 0000000..537fae0 --- /dev/null +++ b/bindings/js/World.d.ts @@ -0,0 +1,36 @@ +// generated by diplomat-tool +import type { DojoError } from "./DojoError" +import type { pointer, codepoint } from "./diplomat-runtime.d.ts"; + + + +/** + * Represents a Dojo world + */ +export class World { + /** @internal */ + get ffiValue(): pointer; + /** @internal */ + constructor(); + + + /** + * Gets the world address (hex) + */ + worldAddress(): string; + + /** + * Gets the number of models in this world + */ + modelsCount(): number; + + /** + * Creates a new world from JSON + */ + static fromJson(json: string): World; + + /** + * Serializes the world to JSON + */ + toJson(): string; +} \ No newline at end of file diff --git a/bindings/js/World.mjs b/bindings/js/World.mjs new file mode 100644 index 0000000..9e3a388 --- /dev/null +++ b/bindings/js/World.mjs @@ -0,0 +1,129 @@ +// generated by diplomat-tool +import { DojoError } from "./DojoError.mjs" +import wasm from "./diplomat-wasm.mjs"; +import * as diplomatRuntime from "./diplomat-runtime.mjs"; + +const World_box_destroy_registry = new FinalizationRegistry((ptr) => { + wasm.World_destroy(ptr); +}); + +/** + * Represents a Dojo world + */ +export class World { + // Internal ptr reference: + #ptr = null; + + // Lifetimes are only to keep dependencies alive. + // Since JS won't garbage collect until there are no incoming edges. + #selfEdge = []; + + #internalConstructor(symbol, ptr, selfEdge) { + if (symbol !== diplomatRuntime.internalConstructor) { + console.error("World is an Opaque type. You cannot call its constructor."); + return; + } + this.#ptr = ptr; + this.#selfEdge = selfEdge; + + // Are we being borrowed? If not, we can register. + if (this.#selfEdge.length === 0) { + World_box_destroy_registry.register(this, this.#ptr); + } + + return this; + } + /** @internal */ + get ffiValue() { + return this.#ptr; + } + + + /** + * Gets the world address (hex) + */ + worldAddress() { + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + wasm.World_world_address(this.ffiValue, write.buffer); + + try { + return write.readString8(); + } + + finally { + write.free(); + } + } + + /** + * Gets the number of models in this world + */ + modelsCount() { + + const result = wasm.World_models_count(this.ffiValue); + + try { + return result; + } + + finally { + } + } + + /** + * Creates a new world from JSON + */ + static fromJson(json) { + let functionCleanupArena = new diplomatRuntime.CleanupArena(); + + const jsonSlice = functionCleanupArena.alloc(diplomatRuntime.DiplomatBuf.sliceWrapper(wasm, diplomatRuntime.DiplomatBuf.str8(wasm, json))); + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + + const result = wasm.World_from_json(diplomatReceive.buffer, jsonSlice.ptr); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return new World(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + } + + finally { + functionCleanupArena.free(); + + diplomatReceive.free(); + } + } + + /** + * Serializes the world to JSON + */ + toJson() { + const diplomatReceive = new diplomatRuntime.DiplomatReceiveBuf(wasm, 5, 4, true); + + const write = new diplomatRuntime.DiplomatWriteBuf(wasm); + + + const result = wasm.World_to_json(diplomatReceive.buffer, this.ffiValue, write.buffer); + + try { + if (!diplomatReceive.resultFlag) { + const cause = new DojoError(diplomatRuntime.internalConstructor, diplomatRuntime.ptrRead(wasm, diplomatReceive.buffer), []); + throw new globalThis.Error('DojoError: ' + cause.toString(), { cause }); + } + return write.readString8(); + } + + finally { + diplomatReceive.free(); + write.free(); + } + } + + constructor(symbol, ptr, selfEdge) { + return this.#internalConstructor(...arguments) + } +} \ No newline at end of file diff --git a/bindings/js/diplomat-runtime.d.ts b/bindings/js/diplomat-runtime.d.ts new file mode 100644 index 0000000..800840e --- /dev/null +++ b/bindings/js/diplomat-runtime.d.ts @@ -0,0 +1,15 @@ +/// A [codepoint] is a Unicode code point, such as `a`, or `💡`. +/// +/// The recommended way to obtain a `codepoint` is to create it from a +/// `String`, which is conceptually a list of `codepoint`s. For example, +/// `'a'.codePointAt(0)` is equal to the `char` `a`. +/// +/// JS does not have a character/codepoint literal, so integer literals +/// need to be used. For example the Unicode code point U+1F4A1, `💡`, +/// can be represented by `0x1F4A1`. Note that only values in the ranges +/// `0x0..0xD7FF` and `0xE000..0x10FFFF` (both inclusive) are Unicode +/// code points, and hence valid `codepoint`s. +/// +/// A `String` can be constructed from a `codepoint` using `String.fromCodePoint()`. +export type codepoint = number; +export type pointer = number; \ No newline at end of file diff --git a/bindings/js/diplomat-runtime.mjs b/bindings/js/diplomat-runtime.mjs new file mode 100644 index 0000000..793fac4 --- /dev/null +++ b/bindings/js/diplomat-runtime.mjs @@ -0,0 +1,680 @@ +/** For internal Diplomat use when constructing opaques or out structs. + * This is for when we're handling items that we don't want the user to touch, like an structure that's only meant to be output, or de-referencing a pointer we're handed from WASM. + */ +export const internalConstructor = Symbol("constructor"); +/** For internal Diplomat use when accessing a from-fields/from-value constructor that's been overridden by a default constructor. + * If we want to pass in arguments without also passing in internalConstructor to avoid triggering some logic we don't want, we use exposeConstructor. + */ +export const exposeConstructor = Symbol("exposeConstructor"); + +export function readString8(wasm, ptr, len) { + const buf = new Uint8Array(wasm.memory.buffer, ptr, len); + return (new TextDecoder("utf-8")).decode(buf) +} + +export function readString16(wasm, ptr, len) { + const buf = new Uint16Array(wasm.memory.buffer, ptr, len); + return String.fromCharCode.apply(null, buf) +} + +export function withDiplomatWrite(wasm, callback) { + const write = wasm.diplomat_buffer_write_create(0); + try { + callback(write); + const outStringPtr = wasm.diplomat_buffer_write_get_bytes(write); + if (outStringPtr === null) { + throw Error("Out of memory"); + } + const outStringLen = wasm.diplomat_buffer_write_len(write); + return readString8(wasm, outStringPtr, outStringLen); + } finally { + wasm.diplomat_buffer_write_destroy(write); + } +} + +/** + * Get the pointer returned by an FFI function. + * + * It's tempting to call `(new Uint32Array(wasm.memory.buffer, FFI_func(), 1))[0]`. + * However, there's a chance that `wasm.memory.buffer` will be resized between + * the time it's accessed and the time it's used, invalidating the view. + * This function ensures that the view into wasm memory is fresh. + * + * This is used for methods that return multiple types into a wasm buffer, where + * one of those types is another ptr. Call this method to get access to the returned + * ptr, so the return buffer can be freed. + * @param {WebAssembly.Exports} wasm Provided by diplomat generated files. + * @param {number} ptr Pointer of a pointer, to be read. + * @returns {number} The underlying pointer. + */ +export function ptrRead(wasm, ptr) { + return (new Uint32Array(wasm.memory.buffer, ptr, 1))[0]; +} + +/** + * Get the flag of a result type. + */ +export function resultFlag(wasm, ptr, offset) { + return (new Uint8Array(wasm.memory.buffer, ptr + offset, 1))[0]; +} + +/** + * Get the discriminant of a Rust enum. +*/ +export function enumDiscriminant(wasm, ptr) { + return (new Int32Array(wasm.memory.buffer, ptr, 1))[0] +} + +/** + * Return an array of paddingCount zeroes to be spread into a function call + * if needsPaddingFields is true, else empty + */ +export function maybePaddingFields(needsPaddingFields, paddingCount) { + if (needsPaddingFields) { + return Array(paddingCount).fill(0); + } else { + return []; + } +} + +/** +* Write a value of width `width` to a an ArrayBuffer `arrayBuffer` +* at byte offset `offset`, treating it as a buffer of kind `typedArrayKind` +* (which is a `TypedArray` variant like `Uint8Array` or `Int16Array`) +*/ +export function writeToArrayBuffer(arrayBuffer, offset, value, typedArrayKind) { + let buffer = new typedArrayKind(arrayBuffer, offset); + buffer[0] = value; +} + +/** +* Take `jsValue` and write it to arrayBuffer at offset `offset` if it is non-null +* calling `writeToArrayBufferCallback(arrayBuffer, offset, jsValue)` to write to the buffer, +* also writing a tag bit. +* +* `size` and `align` are the size and alignment of T, not of Option +*/ +export function writeOptionToArrayBuffer(arrayBuffer, offset, jsValue, size, align, writeToArrayBufferCallback) { + // perform a nullish check, not a null check, + // we want identical behavior for undefined + if (jsValue != null) { + writeToArrayBufferCallback(arrayBuffer, offset, jsValue); + writeToArrayBuffer(arrayBuffer, offset + size, 1, Uint8Array); + } +} + +/** +* For Option of given size/align (of T, not the overall option type), +* return an array of fields suitable for passing down to a parameter list. +* +* Calls writeToArrayBufferCallback(arrayBuffer, offset, jsValue) for non-null jsValues +* +* This array will have size/align elements for the actual T, then one element +* for the is_ok bool, and then align - 1 elements for padding. +* +* See wasm_abi_quirks.md's section on Unions for understanding this ABI. +*/ +export function optionToArgsForCalling(jsValue, size, align, writeToArrayBufferCallback) { + let args; + // perform a nullish check, not a null check, + // we want identical behavior for undefined + if (jsValue != null) { + let buffer; + // We need our originator array to be properly aligned + if (align == 8) { + buffer = new BigUint64Array(size / align); + } else if (align == 4) { + buffer = new Uint32Array(size / align); + } else if (align == 2) { + buffer = new Uint16Array(size / align); + } else { + buffer = new Uint8Array(size / align); + } + + + writeToArrayBufferCallback(buffer.buffer, 0, jsValue); + args = Array.from(buffer); + args.push(1); + } else { + args = Array(size / align).fill(0); + args.push(0); + } + + // Unconditionally add padding + args = args.concat(Array(align - 1).fill(0)); + return args; +} + +export function optionToBufferForCalling(wasm, jsValue, size, align, allocator, writeToArrayBufferCallback) { + let buf = DiplomatBuf.struct(wasm, size, align); + + let buffer; + // Add 1 to the size since we're also accounting for the 0 or 1 is_ok field: + if (align == 8) { + buffer = new BigUint64Array(wasm.memory.buffer, buf, size / align + 1); + } else if (align == 4) { + buffer = new Uint32Array(wasm.memory.buffer, buf, size / align + 1); + } else if (align == 2) { + buffer = new Uint16Array(wasm.memory.buffer, buf, size / align + 1); + } else { + buffer = new Uint8Array(wasm.memory.buffer, buf, size / align + 1); + } + + buffer.fill(0); + + if (jsValue != null) { + writeToArrayBufferCallback(buffer.buffer, 0, jsValue); + buffer[buffer.length - 1] = 1; + } + + allocator.alloc(buf); +} + + +/** +* Given `ptr` in Wasm memory, treat it as an Option with size for type T, +* and return the converted T (converted using `readCallback(wasm, ptr)`) if the Option is Some +* else None. +*/ +export function readOption(wasm, ptr, size, readCallback) { + // Don't need the alignment: diplomat types don't have overridden alignment, + // so the flag will immediately be after the inner struct. + let flag = resultFlag(wasm, ptr, size); + if (flag) { + return readCallback(wasm, ptr); + } else { + return null; + } +} + +/** + * A wrapper around a slice of WASM memory that can be freed manually or + * automatically by the garbage collector. + * + * This type is necessary for Rust functions that take a `&str` or `&[T]`, since + * they can create an edge to this object if they borrow from the str/slice, + * or we can manually free the WASM memory if they don't. + */ +export class DiplomatBuf { + static str8 = (wasm, string) => { + var utf8Length = 0; + for (const codepointString of string) { + let codepoint = codepointString.codePointAt(0); + if (codepoint < 0x80) { + utf8Length += 1 + } else if (codepoint < 0x800) { + utf8Length += 2 + } else if (codepoint < 0x10000) { + utf8Length += 3 + } else { + utf8Length += 4 + } + } + + const ptr = wasm.diplomat_alloc(utf8Length, 1); + + const result = (new TextEncoder()).encodeInto(string, new Uint8Array(wasm.memory.buffer, ptr, utf8Length)); + console.assert(string.length === result.read && utf8Length === result.written, "UTF-8 write error"); + + return new DiplomatBuf(ptr, utf8Length, () => wasm.diplomat_free(ptr, utf8Length, 1)); + } + + static str16 = (wasm, string) => { + const byteLength = string.length * 2; + const ptr = wasm.diplomat_alloc(byteLength, 2); + + const destination = new Uint16Array(wasm.memory.buffer, ptr, string.length); + for (let i = 0; i < string.length; i++) { + destination[i] = string.charCodeAt(i); + } + + return new DiplomatBuf(ptr, string.length, () => wasm.diplomat_free(ptr, byteLength, 2)); + } + + static sliceWrapper = (wasm, buf) => { + const ptr = wasm.diplomat_alloc(8, 4); + let dst = new Uint32Array(wasm.memory.buffer, ptr, 2); + + dst[0] = buf.ptr; + dst[1] = buf.size; + return new DiplomatBuf(ptr, 8, () => { + wasm.diplomat_free(ptr, 8, 4); + buf.free(); + }); + } + + static slice = (wasm, list, rustType) => { + const elementSize = rustType === "u8" || rustType === "i8" || rustType === "boolean" ? 1 : + rustType === "u16" || rustType === "i16" ? 2 : + rustType === "u64" || rustType === "i64" || rustType === "f64" ? 8 : + 4; + + const byteLength = list.length * elementSize; + const ptr = wasm.diplomat_alloc(byteLength, elementSize); + + /** + * Create an array view of the buffer. This gives us the `set` method which correctly handles untyped values + */ + const destination = + rustType === "u8" || rustType === "boolean" ? new Uint8Array(wasm.memory.buffer, ptr, byteLength) : + rustType === "i8" ? new Int8Array(wasm.memory.buffer, ptr, byteLength) : + rustType === "u16" ? new Uint16Array(wasm.memory.buffer, ptr, byteLength) : + rustType === "i16" ? new Int16Array(wasm.memory.buffer, ptr, byteLength) : + rustType === "i32" ? new Int32Array(wasm.memory.buffer, ptr, byteLength) : + rustType === "u64" ? new BigUint64Array(wasm.memory.buffer, ptr, byteLength) : + rustType === "i64" ? new BigInt64Array(wasm.memory.buffer, ptr, byteLength) : + rustType === "f32" ? new Float32Array(wasm.memory.buffer, ptr, byteLength) : + rustType === "f64" ? new Float64Array(wasm.memory.buffer, ptr, byteLength) : + new Uint32Array(wasm.memory.buffer, ptr, byteLength); + destination.set(list); + + return new DiplomatBuf(ptr, list.length, () => wasm.diplomat_free(ptr, byteLength, elementSize)); + } + + static strs = (wasm, strings, encoding) => { + let encodeStr = (encoding === "string16") ? DiplomatBuf.str16 : DiplomatBuf.str8; + + const byteLength = strings.length * 4 * 2; + + const ptr = wasm.diplomat_alloc(byteLength, 4); + + const destination = new Uint32Array(wasm.memory.buffer, ptr, byteLength); + + const stringsAlloc = []; + + for (let i = 0; i < strings.length; i++) { + stringsAlloc.push(encodeStr(wasm, strings[i])); + + destination[2 * i] = stringsAlloc[i].ptr; + destination[(2 * i) + 1] = stringsAlloc[i].size; + } + + return new DiplomatBuf(ptr, strings.length, () => { + wasm.diplomat_free(ptr, byteLength, 4); + for (let i = 0; i < stringsAlloc.length; i++) { + stringsAlloc[i].free(); + } + }); + } + + static struct = (wasm, size, align) => { + const ptr = wasm.diplomat_alloc(size, align); + + return new DiplomatBuf(ptr, size, () => { + wasm.diplomat_free(ptr, size, align); + }); + } + + /** + * Generated code calls one of methods these for each allocation, to either + * free directly after the FFI call, to leak (to create a &'static), or to + * register the buffer with the garbage collector (to create a &'a). + */ + free; + + constructor(ptr, size, free) { + this.ptr = ptr; + this.size = size; + this.free = free; + this.leak = () => { }; + this.releaseToGarbageCollector = () => DiplomatBufferFinalizer.register(this, this.free); + } + + splat() { + return [this.ptr, this.size]; + } + + /** + * Write the (ptr, len) pair to an array buffer at byte offset `offset` + */ + writePtrLenToArrayBuffer(arrayBuffer, offset) { + writeToArrayBuffer(arrayBuffer, offset, this.ptr, Uint32Array); + writeToArrayBuffer(arrayBuffer, offset + 4, this.size, Uint32Array); + } +} + +/** + * Helper class for creating and managing `diplomat_buffer_write`. + * Meant to minimize direct calls to `wasm`. + */ +export class DiplomatWriteBuf { + leak; + + #wasm; + #buffer; + + constructor(wasm) { + this.#wasm = wasm; + this.#buffer = this.#wasm.diplomat_buffer_write_create(0); + + this.leak = () => { }; + } + + free() { + this.#wasm.diplomat_buffer_write_destroy(this.#buffer); + } + + releaseToGarbageCollector() { + DiplomatBufferFinalizer.register(this, this.free); + } + + readString8() { + return readString8(this.#wasm, this.ptr, this.size); + } + + get buffer() { + return this.#buffer; + } + + get ptr() { + return this.#wasm.diplomat_buffer_write_get_bytes(this.#buffer); + } + + get size() { + return this.#wasm.diplomat_buffer_write_len(this.#buffer); + } +} + +/** + * Represents an underlying slice that we've grabbed from WebAssembly. + * You can treat this in JS as a regular slice of primitives, but it handles additional data for you behind the scenes. + */ +export class DiplomatSlice { + #wasm; + + #bufferType; + get bufferType() { + return this.#bufferType; + } + + #buffer; + get buffer() { + return this.#buffer; + } + + #lifetimeEdges; + + constructor(wasm, buffer, bufferType, lifetimeEdges) { + this.#wasm = wasm; + + const [ptr, size] = new Uint32Array(this.#wasm.memory.buffer, buffer, 2); + + this.#buffer = new bufferType(this.#wasm.memory.buffer, ptr, size); + this.#bufferType = bufferType; + + this.#lifetimeEdges = lifetimeEdges; + } + + getValue() { + return this.#buffer; + } + + [Symbol.toPrimitive]() { + return this.getValue(); + } + + valueOf() { + return this.getValue(); + } +} + +export class DiplomatSlicePrimitive extends DiplomatSlice { + constructor(wasm, buffer, sliceType, lifetimeEdges) { + const [ptr, size] = new Uint32Array(wasm.memory.buffer, buffer, 2); + + let arrayType; + switch (sliceType) { + case "u8": + case "boolean": + arrayType = Uint8Array; + break; + case "i8": + arrayType = Int8Array; + break; + case "u16": + arrayType = Uint16Array; + break; + case "i16": + arrayType = Int16Array; + break; + case "i32": + arrayType = Int32Array; + break; + case "u32": + arrayType = Uint32Array; + break; + case "i64": + arrayType = BigInt64Array; + break; + case "u64": + arrayType = BigUint64Array; + break; + case "f32": + arrayType = Float32Array; + break; + case "f64": + arrayType = Float64Array; + break; + default: + console.error("Unrecognized bufferType ", bufferType); + } + + super(wasm, buffer, arrayType, lifetimeEdges); + } +} + +export class DiplomatSliceStr extends DiplomatSlice { + #decoder; + + constructor(wasm, buffer, stringEncoding, lifetimeEdges) { + let encoding; + switch (stringEncoding) { + case "string8": + encoding = Uint8Array; + break; + case "string16": + encoding = Uint16Array; + break; + default: + console.error("Unrecognized stringEncoding ", stringEncoding); + break; + } + super(wasm, buffer, encoding, lifetimeEdges); + + if (stringEncoding === "string8") { + this.#decoder = new TextDecoder('utf-8'); + } + } + + getValue() { + switch (this.bufferType) { + case Uint8Array: + return this.#decoder.decode(super.getValue()); + case Uint16Array: + return String.fromCharCode.apply(null, super.getValue()); + default: + return null; + } + } + + toString() { + return this.getValue(); + } +} + +export class DiplomatSliceStrings extends DiplomatSlice { + #strings = []; + constructor(wasm, buffer, stringEncoding, lifetimeEdges) { + super(wasm, buffer, Uint32Array, lifetimeEdges); + + for (let i = this.buffer.byteOffset; i < this.buffer.byteLength; i += this.buffer.BYTES_PER_ELEMENT * 2) { + this.#strings.push(new DiplomatSliceStr(wasm, i, stringEncoding, lifetimeEdges)); + } + } + + getValue() { + return this.#strings; + } +} + +/** + * A number of Rust functions in WebAssembly require a buffer to populate struct, slice, Option<> or Result<> types with information. + * {@link DiplomatReceiveBuf} allocates a buffer in WebAssembly, which can then be passed into functions with the {@link DiplomatReceiveBuf.buffer} + * property. + */ +export class DiplomatReceiveBuf { + #wasm; + + #size; + #align; + + #hasResult; + + #buffer; + + constructor(wasm, size, align, hasResult) { + this.#wasm = wasm; + + this.#size = size; + this.#align = align; + + this.#hasResult = hasResult; + + this.#buffer = this.#wasm.diplomat_alloc(this.#size, this.#align); + + this.leak = () => { }; + } + + free() { + this.#wasm.diplomat_free(this.#buffer, this.#size, this.#align); + } + + get buffer() { + return this.#buffer; + } + + /** + * Only for when a DiplomatReceiveBuf is allocating a buffer for an `Option<>` or a `Result<>` type. + * + * This just checks the last byte for a successful result (assuming that Rust's compiler does not change). + */ + get resultFlag() { + if (this.#hasResult) { + return resultFlag(this.#wasm, this.#buffer, this.#size - 1); + } else { + return true; + } + } +} + +/** + * For preallocating owned slices + * + * Doesn't actually do anything, but helps code readability of generated code + */ +export class OwnedSliceLeaker { + constructor() { + } + + /** + * Leak an item + * @param {DiplomatBuf} item + * @returns {DiplomatBuf} + */ + static alloc(item) { + item.leak(); + return item; + } +} + +/** + * For cleaning up slices inside struct _intoFFI functions. + * Based somewhat on how the Dart backend handles slice cleanup. + * + * We want to ensure a slice only lasts as long as its struct, so we have a `functionCleanupArena` CleanupArena that we use in each method for any slice that needs to be cleaned up. It lasts only as long as the function is called for. + * + * Then we have `createWith`, which is meant for longer lasting slices. It takes an array of edges and will last as long as those edges do. Cleanup is only called later. + */ +export class CleanupArena { + #items = []; + + constructor() { + } + + /** + * When this arena is freed, call .free() on the given item. + * @param {DiplomatBuf} item + * @returns {DiplomatBuf} + */ + alloc(item) { + this.#items.push(item); + return item; + } + /** + * Create a new CleanupArena, append it to any edge arrays passed down, and return it. + * @param {Array} edgeArrays + * @returns {CleanupArena} + */ + static createWith(...edgeArrays) { + let self = new CleanupArena(); + for (let edgeArray of edgeArrays) { + if (edgeArray != null) { + edgeArray.push(self); + } + } + DiplomatBufferFinalizer.register(self, self.free); + return self; + } + + /** + * If given edge arrays, create a new CleanupArena, append it to any edge arrays passed down, and return it. + * Else return the function-local cleanup arena + * @param {CleanupArena} functionCleanupArena + * @param {Array} edgeArrays + * @returns {DiplomatBuf} + */ + static maybeCreateWith(functionCleanupArena, ...edgeArrays) { + if (edgeArrays.length > 0) { + return CleanupArena.createWith(...edgeArrays); + } else { + return functionCleanupArena + } + } + + free() { + this.#items.forEach((i) => { + i.free(); + }); + + this.#items.length = 0; + } +} + +/** + * Similar to {@link CleanupArena}, but for holding on to slices until a method is called, + * after which we rely on the GC to free them. + * + * This is when you may want to use a slice longer than the body of the method. + * + * At first glance this seems unnecessary, since we will be holding these slices in edge arrays anyway, + * however, if an edge array ends up unused, then we do actually need something to hold it for the duration + * of the method call. + */ +export class GarbageCollectorGrip { + #items = []; + + alloc(item) { + this.#items.push(item); + return item; + } + + releaseToGarbageCollector() { + this.#items.forEach((i) => { + i.releaseToGarbageCollector(); + }); + + this.#items.length = 0; + } +} + +const DiplomatBufferFinalizer = new FinalizationRegistry(free => free()); diff --git a/bindings/js/diplomat-wasm.mjs b/bindings/js/diplomat-wasm.mjs new file mode 100644 index 0000000..010ab35 --- /dev/null +++ b/bindings/js/diplomat-wasm.mjs @@ -0,0 +1,52 @@ +import cfg from '../diplomat.config.mjs'; +import {readString8} from './diplomat-runtime.mjs' + +let wasm; + +const imports = { +env: { + diplomat_console_debug_js(ptr, len) { + console.debug(readString8(wasm, ptr, len)); + }, + diplomat_console_error_js(ptr, len) { + console.error(readString8(wasm, ptr, len)); + }, + diplomat_console_info_js(ptr, len) { + console.info(readString8(wasm, ptr, len)); + }, + diplomat_console_log_js(ptr, len) { + console.log(readString8(wasm, ptr, len)); + }, + diplomat_console_warn_js(ptr, len) { + console.warn(readString8(wasm, ptr, len)); + }, + diplomat_throw_error_js(ptr, len) { + throw new Error(readString8(wasm, ptr, len)); + } +} +} + +if (globalThis.process?.getBuiltinModule) { + // Node (>=22) + const fs = globalThis.process.getBuiltinModule('fs'); + const wasmFile = new Uint8Array(fs.readFileSync(cfg['wasm_path'])); + const loadedWasm = await WebAssembly.instantiate(wasmFile, imports); + wasm = loadedWasm.instance.exports; +} else if (globalThis.process) { + // Node (<22) + const fs = await import('fs'); + const wasmFile = new Uint8Array(fs.readFileSync(cfg['wasm_path'])); + const loadedWasm = await WebAssembly.instantiate(wasmFile, imports); + wasm = loadedWasm.instance.exports; +} else { + // Browser + const loadedWasm = await WebAssembly.instantiateStreaming(fetch(cfg['wasm_path']), imports); + wasm = loadedWasm.instance.exports; +} + +wasm.diplomat_init(); +if (cfg['init'] !== undefined) { + cfg['init'](wasm); +} + +export default wasm; diff --git a/bindings/js/index.d.ts b/bindings/js/index.d.ts new file mode 100644 index 0000000..f5c3723 --- /dev/null +++ b/bindings/js/index.d.ts @@ -0,0 +1,101 @@ + +export { codepoint } from './diplomat-runtime'; + + +export { Account } from "./Account" + +export { Provider } from "./Provider" + +export { Achievement } from "./Achievement" + +export { PlayerAchievementEntry } from "./PlayerAchievementEntry" + +export { Activity } from "./Activity" + +export { AggregationEntry } from "./AggregationEntry" + +export { ToriiClient } from "./ToriiClient" + +export { Contract } from "./Contract" + +export { SigningKey } from "./SigningKey" + +export { TypedData } from "./TypedData" + +export { VerifyingKey } from "./VerifyingKey" + +export { DojoError } from "./DojoError" + +export { Event } from "./Event" + +export { Transaction } from "./Transaction" + +export { Entity } from "./Entity" + +export { Enum } from "./Enum" + +export { EnumOption } from "./EnumOption" + +export { Member } from "./Member" + +export { Model } from "./Model" + +export { Primitive } from "./Primitive" + +export { Struct } from "./Struct" + +export { World } from "./World" + +export { Clause } from "./Clause" + +export { EntityQuery } from "./EntityQuery" + +export { KeysClause } from "./KeysClause" + +export { ModelQuery } from "./ModelQuery" + +export { Subscription } from "./Subscription" + +export { Token } from "./Token" + +export { TokenBalance } from "./TokenBalance" + +export { TokenContract } from "./TokenContract" + +export { TokenTransfer } from "./TokenTransfer" + +export { BlockId } from "./BlockId" + +export { Call } from "./Call" + +export { CallList } from "./CallList" + +export { FieldElement } from "./FieldElement" + +export { OrderBy } from "./OrderBy" + +export { Pagination } from "./Pagination" + +export { Signature } from "./Signature" + +export { U256 } from "./U256" + +export { BlockTag } from "./BlockTag" + +export { CallType } from "./CallType" + +export { ComparisonOperator } from "./ComparisonOperator" + +export { ContractType } from "./ContractType" + +export { LogicalOperator } from "./LogicalOperator" + +export { OrderDirection } from "./OrderDirection" + +export { PaginationDirection } from "./PaginationDirection" + +export { PatternMatching } from "./PatternMatching" + +export { ErrorType } from "./ErrorType" + +export { PrimitiveType } from "./PrimitiveType" diff --git a/bindings/js/index.mjs b/bindings/js/index.mjs new file mode 100644 index 0000000..737131d --- /dev/null +++ b/bindings/js/index.mjs @@ -0,0 +1,99 @@ + + +export { Account } from "./Account.mjs" + +export { Provider } from "./Provider.mjs" + +export { Achievement } from "./Achievement.mjs" + +export { PlayerAchievementEntry } from "./PlayerAchievementEntry.mjs" + +export { Activity } from "./Activity.mjs" + +export { AggregationEntry } from "./AggregationEntry.mjs" + +export { ToriiClient } from "./ToriiClient.mjs" + +export { Contract } from "./Contract.mjs" + +export { SigningKey } from "./SigningKey.mjs" + +export { TypedData } from "./TypedData.mjs" + +export { VerifyingKey } from "./VerifyingKey.mjs" + +export { DojoError } from "./DojoError.mjs" + +export { Event } from "./Event.mjs" + +export { Transaction } from "./Transaction.mjs" + +export { Entity } from "./Entity.mjs" + +export { Enum } from "./Enum.mjs" + +export { EnumOption } from "./EnumOption.mjs" + +export { Member } from "./Member.mjs" + +export { Model } from "./Model.mjs" + +export { Primitive } from "./Primitive.mjs" + +export { Struct } from "./Struct.mjs" + +export { World } from "./World.mjs" + +export { Clause } from "./Clause.mjs" + +export { EntityQuery } from "./EntityQuery.mjs" + +export { KeysClause } from "./KeysClause.mjs" + +export { ModelQuery } from "./ModelQuery.mjs" + +export { Subscription } from "./Subscription.mjs" + +export { Token } from "./Token.mjs" + +export { TokenBalance } from "./TokenBalance.mjs" + +export { TokenContract } from "./TokenContract.mjs" + +export { TokenTransfer } from "./TokenTransfer.mjs" + +export { BlockId } from "./BlockId.mjs" + +export { Call } from "./Call.mjs" + +export { CallList } from "./CallList.mjs" + +export { FieldElement } from "./FieldElement.mjs" + +export { OrderBy } from "./OrderBy.mjs" + +export { Pagination } from "./Pagination.mjs" + +export { Signature } from "./Signature.mjs" + +export { U256 } from "./U256.mjs" + +export { BlockTag } from "./BlockTag.mjs" + +export { CallType } from "./CallType.mjs" + +export { ComparisonOperator } from "./ComparisonOperator.mjs" + +export { ContractType } from "./ContractType.mjs" + +export { LogicalOperator } from "./LogicalOperator.mjs" + +export { OrderDirection } from "./OrderDirection.mjs" + +export { PaginationDirection } from "./PaginationDirection.mjs" + +export { PatternMatching } from "./PatternMatching.mjs" + +export { ErrorType } from "./ErrorType.mjs" + +export { PrimitiveType } from "./PrimitiveType.mjs" diff --git a/build.rs b/build.rs index 09b6c34..4ea0425 100644 --- a/build.rs +++ b/build.rs @@ -1,121 +1,59 @@ -use std::env; - -fn main() { - let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); - - cbindgen::Builder::new() - .with_config({ - let mut config = cbindgen::Config { - language: cbindgen::Language::C, - braces: cbindgen::Braces::SameLine, - cpp_compat: true, - style: cbindgen::Style::Both, - layout: cbindgen::LayoutConfig { ..Default::default() }, - enumeration: cbindgen::EnumConfig { - derive_helper_methods: true, - // prefix_with_name: true, - ..Default::default() - }, - export: cbindgen::ExportConfig { - mangle: cbindgen::MangleConfig { - remove_underscores: true, - ..Default::default() - }, - ..Default::default() - }, - namespace: Some("dojo_bindings".to_string()), +use std::path::Path; + +use diplomat_tool::{ + config::{Config, SharedConfig}, + DocsUrlGenerator, +}; + +pub fn main() { + // Generate C bindings + diplomat_tool::gen( + Path::new("src/lib.rs"), + "c", + Path::new("bindings/c"), + &DocsUrlGenerator::default(), + Config { + shared_config: SharedConfig { + lib_name: Some("dojo_c".to_string()), ..Default::default() - }; - - config.defines.insert( - "target_pointer_width = 32".to_string(), - "TARGET_POINTER_WIDTH_32".to_string(), - ); - - config - }) - .with_crate(crate_dir.clone()) - .generate() - .expect("Unable to generate bindings") - .write_to_file("dojo.h"); - - cbindgen::Builder::new() - .with_config({ - let mut config = cbindgen::Config { - language: cbindgen::Language::Cxx, - braces: cbindgen::Braces::SameLine, - style: cbindgen::Style::Both, - layout: cbindgen::LayoutConfig { ..Default::default() }, - enumeration: cbindgen::EnumConfig { - derive_helper_methods: true, - // prefix_with_name: true, - ..Default::default() - }, - export: cbindgen::ExportConfig { - mangle: cbindgen::MangleConfig { - remove_underscores: true, - ..Default::default() - }, - ..Default::default() - }, - namespace: Some("dojo_bindings".to_string()), + }, + ..Config::default() + }, + false, + ) + .unwrap(); + + // Generate C++ bindings + diplomat_tool::gen( + Path::new("src/lib.rs"), + "cpp", + Path::new("bindings/cpp"), + &DocsUrlGenerator::default(), + Config { + shared_config: SharedConfig { + lib_name: Some("dojo_c".to_string()), ..Default::default() - }; - - config.defines.insert( - "target_pointer_width = 32".to_string(), - "TARGET_POINTER_WIDTH_32".to_string(), - ); - - config - }) - .with_crate(crate_dir.clone()) - .generate() - .expect("Unable to generate bindings") - .write_to_file("dojo.hpp"); - - cbindgen::Builder::new() - .with_config({ - let mut config = cbindgen::Config { - language: cbindgen::Language::Cython, - braces: cbindgen::Braces::SameLine, - style: cbindgen::Style::Both, - layout: cbindgen::LayoutConfig { ..Default::default() }, - enumeration: cbindgen::EnumConfig { - derive_helper_methods: true, - // prefix_with_name: true, - ..Default::default() - }, - export: cbindgen::ExportConfig { - mangle: cbindgen::MangleConfig { - remove_underscores: true, - ..Default::default() - }, - ..Default::default() - }, - namespace: Some("dojo_bindings".to_string()), + }, + ..Config::default() + }, + false, + ) + .unwrap(); + + // Generate JavaScript/WASM bindings + diplomat_tool::gen( + Path::new("src/lib.rs"), + "js", + Path::new("bindings/js"), + &DocsUrlGenerator::default(), + Config { + shared_config: SharedConfig { + lib_name: Some("dojo_c".to_string()), ..Default::default() - }; - - config.defines.insert( - "target_pointer_width = 32".to_string(), - "TARGET_POINTER_WIDTH_32".to_string(), - ); - - config - }) - .with_crate(crate_dir.clone()) - .generate() - .expect("Unable to generate bindings") - .write_to_file("dojo.pyx"); - - // NOTE: disable for now. use c2cs to generate csharp bindings - // generics not supported - // csbindgen::Builder::default() - // .input_extern_file("src/lib.rs") - // .input_extern_file("src/types.rs") - // .csharp_dll_name("libtorii_c.dylib") - // .csharp_namespace("Dojo") - // .generate_csharp_file("./Dojo.g.cs") - // .unwrap(); + }, + ..Config::default() + }, + false, + ) + .unwrap(); } diff --git a/controller.c b/controller.c new file mode 160000 index 0000000..c93013b --- /dev/null +++ b/controller.c @@ -0,0 +1 @@ +Subproject commit c93013b0f8c14eb2ba1e86db97f8870613ae9e93 diff --git a/dojo.h b/dojo.h index 06869e7..1ba21d6 100644 --- a/dojo.h +++ b/dojo.h @@ -1584,6 +1584,92 @@ struct Resultbool client_update_aggregation_subscription(struct ToriiClient *cli const char *const *entity_ids, uintptr_t entity_ids_len); +/** + * Retrieves achievements matching query parameter + * + * # Parameters + * * `client` - Pointer to ToriiClient instance + * * `query` - AchievementQuery containing world_addresses, namespaces, hidden filter, and + * pagination + * + * # Returns + * Result containing Page of Achievement or error + */ +struct ResultPageAchievement client_achievements(struct ToriiClient *client, + struct AchievementQuery query); + +/** + * Retrieves player achievement data matching query parameter + * + * # Parameters + * * `client` - Pointer to ToriiClient instance + * * `query` - PlayerAchievementQuery containing world_addresses, namespaces, player_addresses, and + * pagination + * + * # Returns + * Result containing Page of PlayerAchievementEntry or error + */ +struct ResultPagePlayerAchievementEntry client_player_achievements(struct ToriiClient *client, + struct PlayerAchievementQuery query); + +/** + * Subscribes to achievement progression updates + * + * # Parameters + * * `client` - Pointer to ToriiClient instance + * * `world_addresses` - Array of world addresses to subscribe to + * * `world_addresses_len` - Length of world_addresses array + * * `namespaces` - Array of namespaces to subscribe to + * * `namespaces_len` - Length of namespaces array + * * `player_addresses` - Array of player addresses to subscribe to + * * `player_addresses_len` - Length of player_addresses array + * * `achievement_ids` - Array of achievement IDs to subscribe to + * * `achievement_ids_len` - Length of achievement_ids array + * * `callback` - Function called when updates occur + * + * # Returns + * Result containing pointer to Subscription or error + */ +struct ResultSubscription client_on_achievement_progression_update(struct ToriiClient *client, + const struct FieldElement *world_addresses, + uintptr_t world_addresses_len, + const char *const *namespaces, + uintptr_t namespaces_len, + const struct FieldElement *player_addresses, + uintptr_t player_addresses_len, + const char *const *achievement_ids, + uintptr_t achievement_ids_len, + void (*callback)(struct AchievementProgression)); + +/** + * Updates an existing achievement progression subscription with new parameters + * + * # Parameters + * * `client` - Pointer to ToriiClient instance + * * `subscription` - Pointer to existing Subscription + * * `world_addresses` - Array of world addresses to subscribe to + * * `world_addresses_len` - Length of world_addresses array + * * `namespaces` - Array of namespaces to subscribe to + * * `namespaces_len` - Length of namespaces array + * * `player_addresses` - Array of player addresses to subscribe to + * * `player_addresses_len` - Length of player_addresses array + * * `achievement_ids` - Array of achievement IDs to subscribe to + * * `achievement_ids_len` - Length of achievement_ids array + * + * # Returns + * Result containing success boolean or error + */ +struct Resultbool client_update_achievement_progression_subscription(struct ToriiClient *client, + struct Subscription *subscription, + const struct FieldElement *world_addresses, + uintptr_t world_addresses_len, + const char *const *namespaces, + uintptr_t namespaces_len, + const struct FieldElement *player_addresses, + uintptr_t player_addresses_len, + const char *const *achievement_ids, + uintptr_t achievement_ids_len); + /** * Retrieves activities (user session tracking) matching query parameter * diff --git a/dojo.hpp b/dojo.hpp index 0139393..7cad767 100644 --- a/dojo.hpp +++ b/dojo.hpp @@ -1401,6 +1401,83 @@ Result client_update_aggregation_subscription(ToriiClient *client, const char *const *entity_ids, uintptr_t entity_ids_len); +/// Retrieves achievements matching query parameter +/// +/// # Parameters +/// * `client` - Pointer to ToriiClient instance +/// * `query` - AchievementQuery containing world_addresses, namespaces, hidden filter, and +/// pagination +/// +/// # Returns +/// Result containing Page of Achievement or error +Result> client_achievements(ToriiClient *client, AchievementQuery query); + +/// Retrieves player achievement data matching query parameter +/// +/// # Parameters +/// * `client` - Pointer to ToriiClient instance +/// * `query` - PlayerAchievementQuery containing world_addresses, namespaces, player_addresses, and +/// pagination +/// +/// # Returns +/// Result containing Page of PlayerAchievementEntry or error +Result> client_player_achievements(ToriiClient *client, + PlayerAchievementQuery query); + +/// Subscribes to achievement progression updates +/// +/// # Parameters +/// * `client` - Pointer to ToriiClient instance +/// * `world_addresses` - Array of world addresses to subscribe to +/// * `world_addresses_len` - Length of world_addresses array +/// * `namespaces` - Array of namespaces to subscribe to +/// * `namespaces_len` - Length of namespaces array +/// * `player_addresses` - Array of player addresses to subscribe to +/// * `player_addresses_len` - Length of player_addresses array +/// * `achievement_ids` - Array of achievement IDs to subscribe to +/// * `achievement_ids_len` - Length of achievement_ids array +/// * `callback` - Function called when updates occur +/// +/// # Returns +/// Result containing pointer to Subscription or error +Result client_on_achievement_progression_update(ToriiClient *client, + const FieldElement *world_addresses, + uintptr_t world_addresses_len, + const char *const *namespaces, + uintptr_t namespaces_len, + const FieldElement *player_addresses, + uintptr_t player_addresses_len, + const char *const *achievement_ids, + uintptr_t achievement_ids_len, + void (*callback)(AchievementProgression)); + +/// Updates an existing achievement progression subscription with new parameters +/// +/// # Parameters +/// * `client` - Pointer to ToriiClient instance +/// * `subscription` - Pointer to existing Subscription +/// * `world_addresses` - Array of world addresses to subscribe to +/// * `world_addresses_len` - Length of world_addresses array +/// * `namespaces` - Array of namespaces to subscribe to +/// * `namespaces_len` - Length of namespaces array +/// * `player_addresses` - Array of player addresses to subscribe to +/// * `player_addresses_len` - Length of player_addresses array +/// * `achievement_ids` - Array of achievement IDs to subscribe to +/// * `achievement_ids_len` - Length of achievement_ids array +/// +/// # Returns +/// Result containing success boolean or error +Result client_update_achievement_progression_subscription(ToriiClient *client, + Subscription *subscription, + const FieldElement *world_addresses, + uintptr_t world_addresses_len, + const char *const *namespaces, + uintptr_t namespaces_len, + const FieldElement *player_addresses, + uintptr_t player_addresses_len, + const char *const *achievement_ids, + uintptr_t achievement_ids_len); + /// Retrieves activities (user session tracking) matching query parameter /// /// # Parameters diff --git a/dojo.pyx b/dojo.pyx index 447f332..0a73301 100644 --- a/dojo.pyx +++ b/dojo.pyx @@ -1125,6 +1125,83 @@ cdef extern from *: const char *const *entity_ids, uintptr_t entity_ids_len); + # Retrieves achievements matching query parameter + # + # # Parameters + # * `client` - Pointer to ToriiClient instance + # * `query` - AchievementQuery containing world_addresses, namespaces, hidden filter, and + # pagination + # + # # Returns + # Result containing Page of Achievement or error + ResultPageAchievement client_achievements(ToriiClient *client, AchievementQuery query); + + # Retrieves player achievement data matching query parameter + # + # # Parameters + # * `client` - Pointer to ToriiClient instance + # * `query` - PlayerAchievementQuery containing world_addresses, namespaces, player_addresses, and + # pagination + # + # # Returns + # Result containing Page of PlayerAchievementEntry or error + ResultPagePlayerAchievementEntry client_player_achievements(ToriiClient *client, + PlayerAchievementQuery query); + + # Subscribes to achievement progression updates + # + # # Parameters + # * `client` - Pointer to ToriiClient instance + # * `world_addresses` - Array of world addresses to subscribe to + # * `world_addresses_len` - Length of world_addresses array + # * `namespaces` - Array of namespaces to subscribe to + # * `namespaces_len` - Length of namespaces array + # * `player_addresses` - Array of player addresses to subscribe to + # * `player_addresses_len` - Length of player_addresses array + # * `achievement_ids` - Array of achievement IDs to subscribe to + # * `achievement_ids_len` - Length of achievement_ids array + # * `callback` - Function called when updates occur + # + # # Returns + # Result containing pointer to Subscription or error + ResultSubscription client_on_achievement_progression_update(ToriiClient *client, + const FieldElement *world_addresses, + uintptr_t world_addresses_len, + const char *const *namespaces, + uintptr_t namespaces_len, + const FieldElement *player_addresses, + uintptr_t player_addresses_len, + const char *const *achievement_ids, + uintptr_t achievement_ids_len, + void (*callback)(AchievementProgression)); + + # Updates an existing achievement progression subscription with new parameters + # + # # Parameters + # * `client` - Pointer to ToriiClient instance + # * `subscription` - Pointer to existing Subscription + # * `world_addresses` - Array of world addresses to subscribe to + # * `world_addresses_len` - Length of world_addresses array + # * `namespaces` - Array of namespaces to subscribe to + # * `namespaces_len` - Length of namespaces array + # * `player_addresses` - Array of player addresses to subscribe to + # * `player_addresses_len` - Length of player_addresses array + # * `achievement_ids` - Array of achievement IDs to subscribe to + # * `achievement_ids_len` - Length of achievement_ids array + # + # # Returns + # Result containing success boolean or error + Resultbool client_update_achievement_progression_subscription(ToriiClient *client, + Subscription *subscription, + const FieldElement *world_addresses, + uintptr_t world_addresses_len, + const char *const *namespaces, + uintptr_t namespaces_len, + const FieldElement *player_addresses, + uintptr_t player_addresses_len, + const char *const *achievement_ids, + uintptr_t achievement_ids_len); + # Retrieves activities (user session tracking) matching query parameter # # # Parameters diff --git a/examples/diplomat_example.c b/examples/diplomat_example.c new file mode 100644 index 0000000..ee70455 --- /dev/null +++ b/examples/diplomat_example.c @@ -0,0 +1,158 @@ +/** + * Example demonstrating the new Diplomat-generated C bindings for dojo.c + * + * Compile with: + * clang examples/diplomat_example.c -I bindings/c -L target/debug -ldojo_c -o diplomat_example + * + * Run with: + * LD_LIBRARY_PATH=target/debug ./diplomat_example + */ + +#include +#include +#include +#include "../bindings/c/SigningKey.h" +#include "../bindings/c/FieldElement.h" +#include "../bindings/c/ToriiClient.h" +#include "../bindings/c/Provider.h" +#include "../bindings/c/Account.h" +#include "../bindings/c/CallList.h" +#include "../bindings/c/DojoError.h" + +void print_write(DiplomatWrite* write) { + if (write->len > 0) { + char* str = malloc(write->len + 1); + memcpy(str, write->buf, write->len); + str[write->len] = '\0'; + printf("%s\n", str); + free(str); + } +} + +int main() { + printf("=== Diplomat Dojo C Bindings Example ===\n\n"); + + // 1. Create a random signing key + printf("1. Creating random signing key...\n"); + SigningKey* signer = SigningKey_from_random(); + + char secret_buffer[256] = {0}; + DiplomatWrite secret_write = {secret_buffer, 256, 0, false}; + SigningKey_secret_scalar(signer, &secret_write); + printf(" Secret scalar: "); + print_write(&secret_write); + + // 2. Create a field element from hex + printf("\n2. Creating field element from hex...\n"); + const char* hex_value = "0x1234567890abcdef"; + DiplomatStringView hex_view = {hex_value, strlen(hex_value)}; + + FieldElement_new_from_hex_result felt_result = FieldElement_new_from_hex(hex_view); + if (felt_result.is_ok) { + FieldElement* felt = felt_result.ok; + char felt_buffer[256] = {0}; + DiplomatWrite felt_write = {felt_buffer, 256, 0, false}; + FieldElement_to_hex(felt, &felt_write); + printf(" Field element: "); + print_write(&felt_write); + FieldElement_destroy(felt); + } else { + printf(" Error creating field element\n"); + DojoError_destroy(felt_result.err); + } + + // 3. Create a Torii client + printf("\n3. Creating Torii client...\n"); + const char* torii_url = "http://localhost:8080"; + DiplomatStringView url_view = {torii_url, strlen(torii_url)}; + + ToriiClient_new_result client_result = ToriiClient_new(url_view); + if (client_result.is_ok) { + ToriiClient* client = client_result.ok; + printf(" Client created successfully\n"); + + char info_buffer[256] = {0}; + DiplomatWrite info_write = {info_buffer, 256, 0, false}; + ToriiClient_info_result info_result = ToriiClient_info(client, &info_write); + if (info_result.is_ok) { + printf(" Info: "); + print_write(&info_write); + } + + ToriiClient_destroy(client); + } else { + printf(" Error creating client: "); + char err_buffer[512] = {0}; + DiplomatWrite err_write = {err_buffer, 512, 0, false}; + DojoError_message(client_result.err, &err_write); + print_write(&err_write); + DojoError_destroy(client_result.err); + } + + // 4. Create a provider + printf("\n4. Creating JSON-RPC provider...\n"); + const char* rpc_url = "https://api.cartridge.gg/x/starknet/mainnet"; + DiplomatStringView rpc_view = {rpc_url, strlen(rpc_url)}; + + Provider_new_result provider_result = Provider_new(rpc_view); + if (provider_result.is_ok) { + Provider* provider = provider_result.ok; + printf(" Provider created successfully\n"); + + char chain_buffer[256] = {0}; + DiplomatWrite chain_write = {chain_buffer, 256, 0, false}; + Provider_chain_id_result chain_result = Provider_chain_id(provider, &chain_write); + if (chain_result.is_ok) { + printf(" Chain ID: "); + print_write(&chain_write); + } else { + printf(" Could not fetch chain ID (network may be unavailable)\n"); + DojoError_destroy(chain_result.err); + } + + Provider_destroy(provider); + } else { + printf(" Error creating provider\n"); + DojoError_destroy(provider_result.err); + } + + // 5. Sign a message + printf("\n5. Signing a message...\n"); + const char* message_hex = "0xdeadbeef"; + DiplomatStringView message_view = {message_hex, strlen(message_hex)}; + + FieldElement_new_from_hex_result msg_felt_result = FieldElement_new_from_hex(message_view); + if (msg_felt_result.is_ok) { + FieldElement* msg_felt = msg_felt_result.ok; + SigningKey_sign_result sig_result = SigningKey_sign(signer, msg_felt); + if (sig_result.is_ok) { + Signature* sig = sig_result.ok; + printf(" Message signed successfully\n"); + + char r_buffer[256] = {0}; + DiplomatWrite r_write = {r_buffer, 256, 0, false}; + Signature_r(sig, &r_write); + printf(" Signature R: "); + print_write(&r_write); + + char s_buffer[256] = {0}; + DiplomatWrite s_write = {s_buffer, 256, 0, false}; + Signature_s(sig, &s_write); + printf(" Signature S: "); + print_write(&s_write); + + Signature_destroy(sig); + } else { + printf(" Error signing message\n"); + DojoError_destroy(sig_result.err); + } + FieldElement_destroy(msg_felt); + } + + // Cleanup + SigningKey_destroy(signer); + + printf("\n=== Example completed ===\n"); + return 0; +} + diff --git a/examples/diplomat_example.js b/examples/diplomat_example.js new file mode 100644 index 0000000..695b4e9 --- /dev/null +++ b/examples/diplomat_example.js @@ -0,0 +1,90 @@ +/** + * Example demonstrating the new Diplomat-generated JavaScript bindings for dojo.c + * + * Run with Node.js: + * node examples/diplomat_example.js + * + * Or in a browser by importing from the generated bindings + */ + +import { SigningKey, FieldElement, ToriiClient, Provider } from '../bindings/js/index.mjs'; + +async function main() { + console.log('=== Diplomat Dojo JavaScript Bindings Example ===\n'); + + try { + // 1. Create a random signing key + console.log('1. Creating random signing key...'); + const signer = SigningKey.fromRandom(); + const secretScalar = signer.secretScalar(); + console.log(` Secret scalar: ${secretScalar}`); + + // 2. Create a field element from hex + console.log('\n2. Creating field element from hex...'); + const hexValue = '0x1234567890abcdef'; + try { + const felt = FieldElement.newFromHex(hexValue); + const feltHex = felt.toHex(); + console.log(` Field element: ${feltHex}`); + } catch (err) { + console.log(` Error creating field element: ${err.message()}`); + } + + // 3. Create a Torii client + console.log('\n3. Creating Torii client...'); + try { + const client = ToriiClient.new_('http://localhost:8080'); + console.log(' Client created successfully'); + + const info = client.info(); + console.log(` Info: ${info}`); + } catch (err) { + console.log(` Error creating client: ${err.message()}`); + } + + // 4. Create a provider + console.log('\n4. Creating JSON-RPC provider...'); + try { + const provider = Provider.new_('https://api.cartridge.gg/x/starknet/mainnet'); + console.log(' Provider created successfully'); + + try { + const chainId = provider.chainId(); + console.log(` Chain ID: ${chainId}`); + } catch (err) { + console.log(' Could not fetch chain ID (network may be unavailable)'); + } + } catch (err) { + console.log(' Error creating provider'); + } + + // 5. Sign a message + console.log('\n5. Signing a message...'); + try { + const msgFelt = FieldElement.newFromHex('0xdeadbeef'); + const signature = signer.sign(msgFelt); + console.log(' Message signed successfully'); + console.log(` Signature R: ${signature.r()}`); + console.log(` Signature S: ${signature.s()}`); + } catch (err) { + console.log(` Error signing message: ${err.message()}`); + } + + // 6. Cryptographic operations + console.log('\n6. Cryptographic operations...'); + try { + const verifyingKey = signer.verifyingKey(); + const pubKeyHex = verifyingKey.scalar(); + console.log(` Public key: ${pubKeyHex}`); + } catch (err) { + console.log(` Error getting verifying key: ${err.message()}`); + } + + console.log('\n=== Example completed ==='); + } catch (error) { + console.error('Unexpected error:', error); + } +} + +main().catch(console.error); + diff --git a/src/ffi/account.rs b/src/ffi/account.rs new file mode 100644 index 0000000..3a438f3 --- /dev/null +++ b/src/ffi/account.rs @@ -0,0 +1,137 @@ +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::{DiplomatStr, DiplomatWrite}; + use lazy_static::lazy_static; + use std::fmt::Write; + use std::sync::Arc; + use starknet::accounts::{Account as StarknetAccount, ConnectedAccount, SingleOwnerAccount, ExecutionEncoding}; + use starknet::providers::jsonrpc::HttpTransport; + use starknet::providers::{JsonRpcClient, Provider as _}; + use starknet::signers::LocalWallet; + use starknet_crypto::Felt; + use tokio::runtime::Runtime; + use url::Url; + + use crate::ffi::crypto::ffi::SigningKey; + use crate::ffi::error::ffi::{DojoError, ErrorType}; + use crate::ffi::types::ffi::{CallList, FieldElement}; + + lazy_static! { + static ref RUNTIME: Arc = + Arc::new(Runtime::new().expect("Failed to create Tokio runtime")); + } + + /// JSON-RPC provider for Starknet + #[diplomat::opaque] + pub struct Provider { + pub(crate) inner: Arc>, + } + + impl Provider { + /// Creates a new provider from an RPC URL + pub fn new(rpc_url: &DiplomatStr) -> Result, Box> { + let url_str = std::str::from_utf8(rpc_url)?; + let url = Url::parse(url_str)?; + let provider = JsonRpcClient::new(HttpTransport::new(url)); + + Ok(Box::new(Provider { + inner: Arc::new(provider), + })) + } + + /// Gets the chain ID + pub fn chain_id(&self, result: &mut DiplomatWrite) -> Result<(), Box> { + let chain_id = RUNTIME.block_on(self.inner.chain_id()) + .map_err(|e| DojoError::new(ErrorType::ProviderError, &format!("Failed to get chain ID: {}", e)))?; + + write!(result, "{:#x}", chain_id).unwrap(); + Ok(()) + } + + /// Gets the latest block number + pub fn block_number(&self) -> Result> { + RUNTIME.block_on(self.inner.block_number()) + .map_err(|e| DojoError::new(ErrorType::ProviderError, &format!("Failed to get block number: {}", e))) + } + } + + /// Starknet account for signing and executing transactions + #[diplomat::opaque] + pub struct Account { + pub(crate) inner: SingleOwnerAccount>, LocalWallet>, + } + + impl Account { + /// Creates a new account + pub fn new( + provider: &Provider, + signer: &SigningKey, + address: &FieldElement, + chain_id: &FieldElement, + ) -> Box { + let wallet = LocalWallet::from_signing_key(signer.0.clone()); + let account = SingleOwnerAccount::new( + provider.inner.clone(), + wallet, + address.0, + chain_id.0, + ExecutionEncoding::New, + ); + + Box::new(Account { inner: account }) + } + + /// Gets the account address + pub fn address(&self, result: &mut DiplomatWrite) { + write!(result, "{:#x}", self.inner.address()).unwrap(); + } + + /// Gets the chain ID + pub fn chain_id(&self, result: &mut DiplomatWrite) { + write!(result, "{:#x}", self.inner.chain_id()).unwrap(); + } + + /// Executes a transaction with the given calls + pub fn execute( + &self, + calls: &CallList, + result: &mut DiplomatWrite, + ) -> Result<(), Box> { + let execution = self.inner.execute_v3(calls.calls.clone()); + + let tx_result = RUNTIME.block_on(execution.send()) + .map_err(|e| DojoError::new(ErrorType::TransactionError, &format!("Failed to execute: {}", e)))?; + + write!(result, "{:#x}", tx_result.transaction_hash).unwrap(); + Ok(()) + } + + /// Gets the nonce for the account + pub fn nonce(&self) -> Result> { + let nonce = RUNTIME.block_on(self.inner.get_nonce()) + .map_err(|e| DojoError::new(ErrorType::AccountError, &format!("Failed to get nonce: {}", e)))?; + + // Convert Felt to u64 - this may truncate for large values + Ok(nonce.to_string().parse().unwrap_or(0)) + } + } + + /// Computes the contract address from class hash, salt, and constructor calldata + pub fn compute_contract_address( + deployer_address: &FieldElement, + salt: &FieldElement, + class_hash: &FieldElement, + constructor_calldata: &[Box], + ) -> Box { + let calldata: Vec = constructor_calldata.iter().map(|f| f.0).collect(); + let address = starknet::core::utils::get_contract_address( + salt.0, + class_hash.0, + &calldata, + deployer_address.0, + ); + + Box::new(FieldElement(address)) + } +} + diff --git a/src/ffi/achievements.rs b/src/ffi/achievements.rs new file mode 100644 index 0000000..aa19176 --- /dev/null +++ b/src/ffi/achievements.rs @@ -0,0 +1,127 @@ + +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::{DiplomatStr, DiplomatWrite}; + use std::fmt::Write; + use crate::ffi::error::ffi::DojoError; + + /// Represents an achievement + #[diplomat::opaque] + pub struct Achievement { + pub(crate) inner: torii_proto::Achievement, + } + + impl Achievement { + /// Gets the achievement ID + pub fn id(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.id).unwrap(); + } + + /// Gets the world address (hex) + pub fn world_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.world_address).unwrap(); + } + + /// Gets the namespace + pub fn namespace(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.namespace).unwrap(); + } + + /// Gets the achievement title + pub fn title(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.title).unwrap(); + } + + /// Gets the achievement description + pub fn description(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.description).unwrap(); + } + + /// Gets the hidden flag + pub fn hidden(&self) -> bool { + self.inner.hidden + } + + /// Gets the icon URI + pub fn icon(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.icon).unwrap(); + } + + /// Gets the points for this achievement + pub fn points(&self) -> u32 { + self.inner.points + } + + /// Creates an achievement from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::Achievement = serde_json::from_str(s)?; + Ok(Box::new(Achievement { inner })) + } + + /// Serializes the achievement to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents player achievement progress + #[diplomat::opaque] + pub struct PlayerAchievementEntry { + pub(crate) inner: torii_proto::PlayerAchievementEntry, + } + + impl PlayerAchievementEntry { + /// Gets the player address (hex) + pub fn player_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.player_address).unwrap(); + } + + /// Gets the total points + pub fn total_points(&self) -> u32 { + self.inner.stats.total_points + } + + /// Gets the completed achievements count + pub fn completed_achievements(&self) -> u32 { + self.inner.stats.completed_achievements + } + + /// Gets the total achievements count + pub fn total_achievements(&self) -> u32 { + self.inner.stats.total_achievements + } + + /// Gets the completion percentage + pub fn completion_percentage(&self) -> f64 { + self.inner.stats.completion_percentage + } + + /// Gets the achievements count + pub fn achievements_count(&self) -> u32 { + self.inner.achievements.len() as u32 + } + + /// Gets the updated_at timestamp + pub fn updated_at(&self) -> u64 { + self.inner.stats.updated_at.timestamp() as u64 + } + + /// Creates a player achievement entry from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::PlayerAchievementEntry = serde_json::from_str(s)?; + Ok(Box::new(PlayerAchievementEntry { inner })) + } + + /// Serializes the player achievement entry to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } +} + diff --git a/src/ffi/activity.rs b/src/ffi/activity.rs new file mode 100644 index 0000000..f5a199b --- /dev/null +++ b/src/ffi/activity.rs @@ -0,0 +1,137 @@ + +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::{DiplomatStr, DiplomatWrite}; + use std::fmt::Write; + use crate::ffi::error::ffi::DojoError; + + /// Represents an activity + #[diplomat::opaque] + pub struct Activity { + pub(crate) inner: torii_proto::Activity, + } + + impl Activity { + /// Gets the activity ID + pub fn id(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.id).unwrap(); + } + + /// Gets the world address (hex) + pub fn world_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.world_address).unwrap(); + } + + /// Gets the namespace + pub fn namespace(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.namespace).unwrap(); + } + + /// Gets the caller address (hex) + pub fn caller_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.caller_address).unwrap(); + } + + /// Gets the session start timestamp + pub fn session_start(&self) -> u64 { + self.inner.session_start.timestamp() as u64 + } + + /// Gets the session end timestamp + pub fn session_end(&self) -> u64 { + self.inner.session_end.timestamp() as u64 + } + + /// Gets the action count + pub fn action_count(&self) -> u32 { + self.inner.action_count + } + + /// Gets the updated_at timestamp + pub fn updated_at(&self) -> u64 { + self.inner.updated_at.timestamp() as u64 + } + + /// Creates an activity from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::Activity = serde_json::from_str(s)?; + Ok(Box::new(Activity { inner })) + } + + /// Serializes the activity to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents an aggregation entry + #[diplomat::opaque] + pub struct AggregationEntry { + pub(crate) inner: torii_proto::AggregationEntry, + } + + impl AggregationEntry { + /// Gets the aggregation ID + pub fn id(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.id).unwrap(); + } + + /// Gets the aggregator ID + pub fn aggregator_id(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.aggregator_id).unwrap(); + } + + /// Gets the entity ID + pub fn entity_id(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.entity_id).unwrap(); + } + + /// Gets the model ID + pub fn model_id(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.model_id).unwrap(); + } + + /// Gets the aggregation value + pub fn value(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.value).unwrap(); + } + + /// Gets the display value + pub fn display_value(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.display_value).unwrap(); + } + + /// Gets the position + pub fn position(&self) -> u64 { + self.inner.position + } + + /// Gets the created_at timestamp + pub fn created_at(&self) -> u64 { + self.inner.created_at.timestamp() as u64 + } + + /// Gets the updated_at timestamp + pub fn updated_at(&self) -> u64 { + self.inner.updated_at.timestamp() as u64 + } + + /// Creates an aggregation entry from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::AggregationEntry = serde_json::from_str(s)?; + Ok(Box::new(AggregationEntry { inner })) + } + + /// Serializes the aggregation entry to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } +} + diff --git a/src/ffi/client.rs b/src/ffi/client.rs new file mode 100644 index 0000000..c6a1602 --- /dev/null +++ b/src/ffi/client.rs @@ -0,0 +1,68 @@ +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::{DiplomatStr, DiplomatWrite}; + use lazy_static::lazy_static; + use std::fmt::Write; + use std::sync::Arc; + use tokio::runtime::Runtime; + use torii_client::Client as TClient; + + use crate::ffi::error::ffi::{DojoError, ErrorType}; + + lazy_static! { + static ref RUNTIME: Arc = + Arc::new(Runtime::new().expect("Failed to create Tokio runtime")); + } + + /// Opaque handle to a Torii client instance + #[diplomat::opaque] + pub struct ToriiClient { + pub(crate) inner: Arc, + } + + impl ToriiClient { + /// Creates a new Torii client instance + pub fn new(torii_url: &DiplomatStr) -> Result, Box> { + let url = std::str::from_utf8(torii_url)?.to_string(); + + let client = RUNTIME.block_on(TClient::new(url)) + .map_err(|e| DojoError::new(ErrorType::ClientError, &format!("Failed to create client: {}", e)))?; + + Ok(Box::new(ToriiClient { + inner: Arc::new(client), + })) + } + + /// Gets information about the Torii server + pub fn info(&self, result: &mut DiplomatWrite) -> Result<(), Box> { + write!(result, "Torii client connected").unwrap(); + Ok(()) + } + + /// Publishes a message to the network + pub fn publish_message( + &self, + message_json: &DiplomatStr, + signature_r: &crate::ffi::types::ffi::FieldElement, + signature_s: &crate::ffi::types::ffi::FieldElement, + world_address: &crate::ffi::types::ffi::FieldElement, + result: &mut DiplomatWrite, + ) -> Result<(), Box> { + use torii_proto::Message; + + let message_str = std::str::from_utf8(message_json)?.to_string(); + let message = Message { + message: message_str, + signature: vec![signature_r.0, signature_s.0], + world_address: world_address.0, + }; + + let response = RUNTIME.block_on(self.inner.publish_message(message)) + .map_err(|e| DojoError::new(ErrorType::ClientError, &format!("Failed to publish message: {}", e)))?; + + write!(result, "{}", response).unwrap(); + Ok(()) + } + } +} + diff --git a/src/ffi/contracts.rs b/src/ffi/contracts.rs new file mode 100644 index 0000000..faca30d --- /dev/null +++ b/src/ffi/contracts.rs @@ -0,0 +1,68 @@ + +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::{DiplomatStr, DiplomatWrite}; + use std::fmt::Write; + use crate::ffi::error::ffi::DojoError; + + /// Represents a contract + #[diplomat::opaque] + pub struct Contract { + pub(crate) inner: torii_proto::Contract, + } + + impl Contract { + /// Gets the contract address (hex) + pub fn contract_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.contract_address).unwrap(); + } + + /// Gets the contract type as string + pub fn contract_type(&self, write: &mut DiplomatWrite) { + let type_str = match self.inner.contract_type { + torii_proto::ContractType::WORLD => "WORLD", + torii_proto::ContractType::ERC20 => "ERC20", + torii_proto::ContractType::ERC721 => "ERC721", + torii_proto::ContractType::ERC1155 => "ERC1155", + torii_proto::ContractType::UDC => "UDC", + torii_proto::ContractType::OTHER => "OTHER", + }; + write!(write, "{}", type_str).unwrap(); + } + + /// Gets the head block number (if any) + pub fn head(&self) -> u64 { + self.inner.head.unwrap_or(0) + } + + /// Gets the TPS (transactions per second) if available + pub fn tps(&self) -> u64 { + self.inner.tps.unwrap_or(0) + } + + /// Gets the created_at timestamp + pub fn created_at(&self) -> u64 { + self.inner.created_at.timestamp() as u64 + } + + /// Gets the updated_at timestamp + pub fn updated_at(&self) -> u64 { + self.inner.updated_at.timestamp() as u64 + } + + /// Creates a contract from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::Contract = serde_json::from_str(s)?; + Ok(Box::new(Contract { inner })) + } + + /// Serializes the contract to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } +} + diff --git a/src/ffi/crypto.rs b/src/ffi/crypto.rs new file mode 100644 index 0000000..3523fb4 --- /dev/null +++ b/src/ffi/crypto.rs @@ -0,0 +1,113 @@ +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::{DiplomatStr, DiplomatWrite}; + use starknet::signers::{SigningKey as StarknetSigningKey, VerifyingKey as StarknetVerifyingKey}; + use starknet_crypto::Felt; + use std::fmt::Write; + + use crate::ffi::error::ffi::{DojoError, ErrorType}; + use crate::ffi::types::ffi::{FieldElement, Signature}; + + /// Represents a signing key for Starknet transactions + #[diplomat::opaque] + pub struct SigningKey(pub StarknetSigningKey); + + impl SigningKey { + /// Creates a new signing key from a secret scalar + pub fn new(secret_scalar: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(secret_scalar)?; + let felt = Felt::from_hex(s) + .map_err(|e| DojoError::new(ErrorType::ParseError, &format!("Invalid secret scalar: {}", e)))?; + let key = StarknetSigningKey::from_secret_scalar(felt); + Ok(Box::new(SigningKey(key))) + } + + /// Generates a new random signing key + pub fn from_random() -> Box { + Box::new(SigningKey(StarknetSigningKey::from_random())) + } + + /// Returns the secret scalar of the signing key + pub fn secret_scalar(&self, result: &mut DiplomatWrite) { + write!(result, "{:#x}", self.0.secret_scalar()).unwrap(); + } + + /// Signs a message hash + pub fn sign(&self, hash: &FieldElement) -> Result, Box> { + let sig = self.0.sign(&hash.0) + .map_err(|e| DojoError::new(ErrorType::SigningError, &format!("Failed to sign: {}", e)))?; + + Ok(Box::new(Signature { + r: sig.r, + s: sig.s, + })) + } + + /// Returns the verifying key + pub fn verifying_key(&self) -> Box { + Box::new(VerifyingKey(self.0.verifying_key())) + } + } + + /// Represents a verifying key for signature verification + #[diplomat::opaque] + pub struct VerifyingKey(pub StarknetVerifyingKey); + + impl VerifyingKey { + /// Returns the scalar value of the verifying key + pub fn scalar(&self, result: &mut DiplomatWrite) { + write!(result, "{:#x}", self.0.scalar()).unwrap(); + } + + /// Verifies a signature + pub fn verify( + &self, + hash: &FieldElement, + signature: &Signature, + ) -> Result> { + let sig = starknet::core::crypto::Signature { + r: signature.r, + s: signature.s, + }; + + self.0.verify(&hash.0, &sig) + .map_err(|e| DojoError::new(ErrorType::SigningError, &format!("Verification failed: {}", e))) + } + } + + /// Represents a typed data structure for EIP-712 style signing + #[diplomat::opaque] + pub struct TypedData(pub starknet::core::types::TypedData); + + impl TypedData { + /// Creates a new TypedData from JSON string + pub fn new_from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let typed_data: starknet::core::types::TypedData = serde_json::from_str(s) + .map_err(|e| DojoError::new(ErrorType::ParseError, &format!("Invalid typed data JSON: {}", e)))?; + Ok(Box::new(TypedData(typed_data))) + } + } + + /// Computes Poseidon hash of multiple field elements + pub fn poseidon_hash(felts: &[Box]) -> Box { + let felt_values: Vec = felts.iter().map(|f| f.0).collect(); + let hash = starknet_crypto::poseidon_hash_many(&felt_values); + Box::new(FieldElement(hash)) + } + + /// Computes pedersen hash of two field elements + pub fn pedersen_hash(a: &FieldElement, b: &FieldElement) -> Box { + let hash = starknet_crypto::pedersen_hash(&a.0, &b.0); + Box::new(FieldElement(hash)) + } + + /// Computes a selector from a name + pub fn get_selector_from_name(name: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(name)?; + let selector = starknet::core::utils::get_selector_from_name(s) + .map_err(|e| DojoError::new(ErrorType::ParseError, &format!("Invalid selector name: {}", e)))?; + Ok(Box::new(FieldElement(selector))) + } +} + diff --git a/src/ffi/enums.rs b/src/ffi/enums.rs new file mode 100644 index 0000000..b9d7ab7 --- /dev/null +++ b/src/ffi/enums.rs @@ -0,0 +1,246 @@ +#[diplomat::bridge] +pub mod ffi { + /// Block tag for identifying specific blocks + pub enum BlockTag { + Latest, + PreConfirmed, + } + + /// Type of contract + #[allow(clippy::upper_case_acronyms)] + pub enum ContractType { + WORLD, + ERC20, + ERC721, + ERC1155, + UDC, + OTHER, + } + + /// Direction for pagination + pub enum PaginationDirection { + Forward, + Backward, + } + + /// Direction for ordering results + pub enum OrderDirection { + Asc, + Desc, + } + + /// Pattern matching mode for key queries + pub enum PatternMatching { + FixedLen, + VariableLen, + } + + /// Logical operator for combining clauses + pub enum LogicalOperator { + And, + Or, + } + + /// Comparison operators for member clauses + pub enum ComparisonOperator { + Eq, + Neq, + Gt, + Gte, + Lt, + Lte, + In, + NotIn, + Contains, + ContainsAll, + ContainsAny, + ArrayLengthEq, + ArrayLengthGt, + ArrayLengthLt, + } + + /// Type of call in a transaction + pub enum CallType { + Execute, + ExecuteFromOutside, + } + + // Conversion implementations for torii_proto types + impl From for starknet::core::types::BlockTag { + fn from(val: BlockTag) -> Self { + match val { + BlockTag::Latest => starknet::core::types::BlockTag::Latest, + BlockTag::PreConfirmed => starknet::core::types::BlockTag::PreConfirmed, + } + } + } + + impl From for BlockTag { + fn from(val: starknet::core::types::BlockTag) -> Self { + match val { + starknet::core::types::BlockTag::Latest => BlockTag::Latest, + starknet::core::types::BlockTag::PreConfirmed => BlockTag::PreConfirmed, + _ => BlockTag::Latest, // Default for other tags + } + } + } + + impl From for torii_proto::ContractType { + fn from(val: ContractType) -> Self { + match val { + ContractType::WORLD => torii_proto::ContractType::WORLD, + ContractType::ERC20 => torii_proto::ContractType::ERC20, + ContractType::ERC721 => torii_proto::ContractType::ERC721, + ContractType::ERC1155 => torii_proto::ContractType::ERC1155, + ContractType::UDC => torii_proto::ContractType::UDC, + ContractType::OTHER => torii_proto::ContractType::OTHER, + } + } + } + + impl From for ContractType { + fn from(val: torii_proto::ContractType) -> Self { + match val { + torii_proto::ContractType::WORLD => ContractType::WORLD, + torii_proto::ContractType::ERC20 => ContractType::ERC20, + torii_proto::ContractType::ERC721 => ContractType::ERC721, + torii_proto::ContractType::ERC1155 => ContractType::ERC1155, + torii_proto::ContractType::UDC => ContractType::UDC, + torii_proto::ContractType::OTHER => ContractType::OTHER, + } + } + } + + impl From for torii_proto::PaginationDirection { + fn from(val: PaginationDirection) -> Self { + match val { + PaginationDirection::Forward => torii_proto::PaginationDirection::Forward, + PaginationDirection::Backward => torii_proto::PaginationDirection::Backward, + } + } + } + + impl From for PaginationDirection { + fn from(val: torii_proto::PaginationDirection) -> Self { + match val { + torii_proto::PaginationDirection::Forward => PaginationDirection::Forward, + torii_proto::PaginationDirection::Backward => PaginationDirection::Backward, + } + } + } + + impl From for torii_proto::OrderDirection { + fn from(val: OrderDirection) -> Self { + match val { + OrderDirection::Asc => torii_proto::OrderDirection::Asc, + OrderDirection::Desc => torii_proto::OrderDirection::Desc, + } + } + } + + impl From for OrderDirection { + fn from(val: torii_proto::OrderDirection) -> Self { + match val { + torii_proto::OrderDirection::Asc => OrderDirection::Asc, + torii_proto::OrderDirection::Desc => OrderDirection::Desc, + } + } + } + + impl From for torii_proto::PatternMatching { + fn from(val: PatternMatching) -> Self { + match val { + PatternMatching::FixedLen => torii_proto::PatternMatching::FixedLen, + PatternMatching::VariableLen => torii_proto::PatternMatching::VariableLen, + } + } + } + + impl From for PatternMatching { + fn from(val: torii_proto::PatternMatching) -> Self { + match val { + torii_proto::PatternMatching::FixedLen => PatternMatching::FixedLen, + torii_proto::PatternMatching::VariableLen => PatternMatching::VariableLen, + } + } + } + + impl From for torii_proto::LogicalOperator { + fn from(val: LogicalOperator) -> Self { + match val { + LogicalOperator::And => torii_proto::LogicalOperator::And, + LogicalOperator::Or => torii_proto::LogicalOperator::Or, + } + } + } + + impl From for LogicalOperator { + fn from(val: torii_proto::LogicalOperator) -> Self { + match val { + torii_proto::LogicalOperator::And => LogicalOperator::And, + torii_proto::LogicalOperator::Or => LogicalOperator::Or, + } + } + } + + impl From for torii_proto::ComparisonOperator { + fn from(val: ComparisonOperator) -> Self { + match val { + ComparisonOperator::Eq => torii_proto::ComparisonOperator::Eq, + ComparisonOperator::Neq => torii_proto::ComparisonOperator::Neq, + ComparisonOperator::Gt => torii_proto::ComparisonOperator::Gt, + ComparisonOperator::Gte => torii_proto::ComparisonOperator::Gte, + ComparisonOperator::Lt => torii_proto::ComparisonOperator::Lt, + ComparisonOperator::Lte => torii_proto::ComparisonOperator::Lte, + ComparisonOperator::In => torii_proto::ComparisonOperator::In, + ComparisonOperator::NotIn => torii_proto::ComparisonOperator::NotIn, + ComparisonOperator::Contains => torii_proto::ComparisonOperator::Contains, + ComparisonOperator::ContainsAll => torii_proto::ComparisonOperator::ContainsAll, + ComparisonOperator::ContainsAny => torii_proto::ComparisonOperator::ContainsAny, + ComparisonOperator::ArrayLengthEq => torii_proto::ComparisonOperator::ArrayLengthEq, + ComparisonOperator::ArrayLengthGt => torii_proto::ComparisonOperator::ArrayLengthGt, + ComparisonOperator::ArrayLengthLt => torii_proto::ComparisonOperator::ArrayLengthLt, + } + } + } + + impl From for ComparisonOperator { + fn from(val: torii_proto::ComparisonOperator) -> Self { + match val { + torii_proto::ComparisonOperator::Eq => ComparisonOperator::Eq, + torii_proto::ComparisonOperator::Neq => ComparisonOperator::Neq, + torii_proto::ComparisonOperator::Gt => ComparisonOperator::Gt, + torii_proto::ComparisonOperator::Gte => ComparisonOperator::Gte, + torii_proto::ComparisonOperator::Lt => ComparisonOperator::Lt, + torii_proto::ComparisonOperator::Lte => ComparisonOperator::Lte, + torii_proto::ComparisonOperator::In => ComparisonOperator::In, + torii_proto::ComparisonOperator::NotIn => ComparisonOperator::NotIn, + torii_proto::ComparisonOperator::Contains => ComparisonOperator::Contains, + torii_proto::ComparisonOperator::ContainsAll => ComparisonOperator::ContainsAll, + torii_proto::ComparisonOperator::ContainsAny => ComparisonOperator::ContainsAny, + torii_proto::ComparisonOperator::ArrayLengthEq => ComparisonOperator::ArrayLengthEq, + torii_proto::ComparisonOperator::ArrayLengthGt => ComparisonOperator::ArrayLengthGt, + torii_proto::ComparisonOperator::ArrayLengthLt => ComparisonOperator::ArrayLengthLt, + } + } + } + + impl From for torii_proto::CallType { + fn from(val: CallType) -> Self { + match val { + CallType::Execute => torii_proto::CallType::Execute, + CallType::ExecuteFromOutside => torii_proto::CallType::ExecuteFromOutside, + } + } + } + + impl From for CallType { + fn from(val: torii_proto::CallType) -> Self { + match val { + torii_proto::CallType::Execute => CallType::Execute, + torii_proto::CallType::ExecuteFromOutside => CallType::ExecuteFromOutside, + } + } + } +} + diff --git a/src/ffi/error.rs b/src/ffi/error.rs new file mode 100644 index 0000000..fcd9111 --- /dev/null +++ b/src/ffi/error.rs @@ -0,0 +1,125 @@ +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::DiplomatWrite; + use std::fmt::Write; + + /// Error types for Dojo operations + #[diplomat::opaque] + pub struct DojoError { + pub(crate) error_type: ErrorType, + pub(crate) message: String, + } + + pub enum ErrorType { + ClientError, + ParseError, + EntityError, + QueryError, + SubscriptionError, + TransactionError, + AccountError, + SigningError, + ProviderError, + StorageError, + ControllerError, + InvalidInput, + RuntimeError, + } + + impl DojoError { + pub fn new(error_type: ErrorType, message: &str) -> Box { + Box::new(DojoError { + error_type, + message: message.to_string(), + }) + } + + /// Gets the error message + pub fn message(&self, result: &mut DiplomatWrite) { + write!(result, "{}", self.message).unwrap(); + } + + /// Gets the error type + pub fn error_type(&self) -> ErrorType { + self.error_type + } + } + + // Implement From traits for common error types + impl From for Box { + fn from(e: anyhow::Error) -> Self { + Box::new(DojoError { + error_type: ErrorType::RuntimeError, + message: e.to_string(), + }) + } + } + + impl From for Box { + fn from(e: std::str::Utf8Error) -> Self { + Box::new(DojoError { + error_type: ErrorType::InvalidInput, + message: format!("Invalid UTF-8: {}", e), + }) + } + } + + impl From for Box { + fn from(e: url::ParseError) -> Self { + Box::new(DojoError { + error_type: ErrorType::InvalidInput, + message: format!("Invalid URL: {}", e), + }) + } + } + + impl From for Box { + fn from(e: starknet::core::types::FromStrError) -> Self { + Box::new(DojoError { + error_type: ErrorType::ParseError, + message: format!("Parse error: {}", e), + }) + } + } + + impl From for Box { + fn from(e: serde_json::Error) -> Self { + Box::new(DojoError { + error_type: ErrorType::ParseError, + message: format!("JSON parse error: {}", e), + }) + } + } + + impl From for Box { + fn from(e: torii_client::error::Error) -> Self { + Box::new(DojoError { + error_type: ErrorType::ClientError, + message: format!("Torii client error: {:?}", e), + }) + } + } + + impl From> + for Box + { + fn from( + e: starknet::accounts::AccountError, + ) -> Self { + Box::new(DojoError { + error_type: ErrorType::AccountError, + message: format!("Starknet account error: {:?}", e), + }) + } + } + + impl From for Box { + fn from(e: starknet::signers::local_wallet::SignError) -> Self { + Box::new(DojoError { + error_type: ErrorType::SigningError, + message: format!("Starknet signing error: {:?}", e), + }) + } + } +} + diff --git a/src/ffi/events.rs b/src/ffi/events.rs new file mode 100644 index 0000000..34d6ec0 --- /dev/null +++ b/src/ffi/events.rs @@ -0,0 +1,123 @@ + +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::{DiplomatStr, DiplomatWrite}; + use std::fmt::Write; + use crate::ffi::error::ffi::DojoError; + + /// Represents a Dojo event message + #[diplomat::opaque] + pub struct Event { + pub(crate) inner: torii_proto::Event, + } + + impl Event { + /// Gets the keys as JSON array string + pub fn keys(&self, write: &mut DiplomatWrite) { + write!(write, "[").unwrap(); + for (i, key) in self.inner.keys.iter().enumerate() { + if i > 0 { + write!(write, ",").unwrap(); + } + write!(write, "\"{:#x}\"", key).unwrap(); + } + write!(write, "]").unwrap(); + } + + /// Gets the data as JSON array string + pub fn data(&self, write: &mut DiplomatWrite) { + write!(write, "[").unwrap(); + for (i, d) in self.inner.data.iter().enumerate() { + if i > 0 { + write!(write, ",").unwrap(); + } + write!(write, "\"{:#x}\"", d).unwrap(); + } + write!(write, "]").unwrap(); + } + + /// Gets the transaction hash (hex) + pub fn transaction_hash(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.transaction_hash).unwrap(); + } + + /// Creates an event from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::Event = serde_json::from_str(s)?; + Ok(Box::new(Event { inner })) + } + + /// Serializes the event to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents a transaction + #[diplomat::opaque] + pub struct Transaction { + pub(crate) inner: torii_proto::Transaction, + } + + impl Transaction { + /// Gets the transaction hash (hex) + pub fn transaction_hash(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.transaction_hash).unwrap(); + } + + /// Gets the sender address (hex) + pub fn sender_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.sender_address).unwrap(); + } + + /// Gets the max fee as string + pub fn max_fee(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.max_fee).unwrap(); + } + + /// Gets the signature as JSON array string + pub fn signature(&self, write: &mut DiplomatWrite) { + write!(write, "[").unwrap(); + for (i, sig) in self.inner.signature.iter().enumerate() { + if i > 0 { + write!(write, ",").unwrap(); + } + write!(write, "\"{:#x}\"", sig).unwrap(); + } + write!(write, "]").unwrap(); + } + + /// Gets the nonce as string + pub fn nonce(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.nonce).unwrap(); + } + + /// Gets the block timestamp + pub fn block_timestamp(&self) -> u64 { + self.inner.block_timestamp.timestamp() as u64 + } + + /// Gets the block number + pub fn block_number(&self) -> u64 { + self.inner.block_number + } + + /// Creates a transaction from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::Transaction = serde_json::from_str(s)?; + Ok(Box::new(Transaction { inner })) + } + + /// Serializes the transaction to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } +} + diff --git a/src/ffi/mod.rs b/src/ffi/mod.rs new file mode 100644 index 0000000..4f98b13 --- /dev/null +++ b/src/ffi/mod.rs @@ -0,0 +1,16 @@ +// Diplomat FFI bridge modules +pub mod error; +pub mod enums; +pub mod types; +pub mod models; +pub mod tokens; +pub mod events; +pub mod activity; +pub mod achievements; +pub mod contracts; +pub mod client; +pub mod account; +pub mod crypto; +pub mod query; +pub mod subscription; + diff --git a/src/ffi/models.rs b/src/ffi/models.rs new file mode 100644 index 0000000..f6411a8 --- /dev/null +++ b/src/ffi/models.rs @@ -0,0 +1,313 @@ + +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::{DiplomatStr, DiplomatWrite}; + use std::fmt::Write; + use crate::ffi::error::ffi::DojoError; + + /// Type of primitive + pub enum PrimitiveType { + I8, + I16, + I32, + I64, + I128, + U8, + U16, + U32, + U64, + U128, + U256, + Bool, + Felt252, + ClassHash, + ContractAddress, + EthAddress, + } + + /// Represents a primitive Cairo type with its value + #[diplomat::opaque] + pub struct Primitive { + pub(crate) inner: dojo_types::primitive::Primitive, + } + + impl Primitive { + /// Gets the primitive type + pub fn primitive_type(&self) -> PrimitiveType { + match &self.inner { + dojo_types::primitive::Primitive::I8(_) => PrimitiveType::I8, + dojo_types::primitive::Primitive::I16(_) => PrimitiveType::I16, + dojo_types::primitive::Primitive::I32(_) => PrimitiveType::I32, + dojo_types::primitive::Primitive::I64(_) => PrimitiveType::I64, + dojo_types::primitive::Primitive::I128(_) => PrimitiveType::I128, + dojo_types::primitive::Primitive::U8(_) => PrimitiveType::U8, + dojo_types::primitive::Primitive::U16(_) => PrimitiveType::U16, + dojo_types::primitive::Primitive::U32(_) => PrimitiveType::U32, + dojo_types::primitive::Primitive::U64(_) => PrimitiveType::U64, + dojo_types::primitive::Primitive::U128(_) => PrimitiveType::U128, + dojo_types::primitive::Primitive::U256(_) => PrimitiveType::U256, + dojo_types::primitive::Primitive::Bool(_) => PrimitiveType::Bool, + dojo_types::primitive::Primitive::Felt252(_) => PrimitiveType::Felt252, + dojo_types::primitive::Primitive::ClassHash(_) => PrimitiveType::ClassHash, + dojo_types::primitive::Primitive::ContractAddress(_) => PrimitiveType::ContractAddress, + dojo_types::primitive::Primitive::EthAddress(_) => PrimitiveType::EthAddress, + } + } + + /// Creates a primitive from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: dojo_types::primitive::Primitive = serde_json::from_str(s)?; + Ok(Box::new(Primitive { inner })) + } + + /// Serializes the primitive to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents a Dojo struct member (field) + #[diplomat::opaque] + pub struct Member { + pub(crate) inner: dojo_types::schema::Member, + } + + impl Member { + /// Gets the member name + pub fn name(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.name).unwrap(); + } + + /// Returns true if this member is a key + pub fn is_key(&self) -> bool { + self.inner.key + } + } + + /// Represents a Dojo struct + #[diplomat::opaque] + pub struct Struct { + pub(crate) inner: dojo_types::schema::Struct, + } + + impl Struct { + /// Gets the struct name + pub fn name(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.name).unwrap(); + } + + /// Gets the number of children (members) + pub fn children_count(&self) -> u32 { + self.inner.children.len() as u32 + } + + /// Creates a new struct from JSON schema + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: dojo_types::schema::Struct = serde_json::from_str(s)?; + Ok(Box::new(Struct { inner })) + } + + /// Serializes the struct to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents a Dojo enum option (variant) + #[diplomat::opaque] + pub struct EnumOption { + pub(crate) inner: dojo_types::schema::EnumOption, + } + + impl EnumOption { + /// Gets the option name + pub fn name(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.name).unwrap(); + } + } + + /// Represents a Dojo enum + #[diplomat::opaque] + pub struct Enum { + pub(crate) inner: dojo_types::schema::Enum, + } + + impl Enum { + /// Gets the enum name + pub fn name(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.name).unwrap(); + } + + /// Gets the current option (selected variant) index + pub fn option(&self) -> u8 { + self.inner.option.unwrap_or(0) + } + + /// Gets the number of options (variants) + pub fn options_count(&self) -> u32 { + self.inner.options.len() as u32 + } + + /// Creates a new enum from JSON schema + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: dojo_types::schema::Enum = serde_json::from_str(s)?; + Ok(Box::new(Enum { inner })) + } + + /// Serializes the enum to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents a Dojo model + #[diplomat::opaque] + pub struct Model { + pub(crate) inner: torii_proto::Model, + } + + impl Model { + /// Gets the model name + pub fn name(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.name).unwrap(); + } + + /// Gets the model namespace + pub fn namespace(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.namespace).unwrap(); + } + + /// Gets the model selector (hex) + pub fn selector(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.selector).unwrap(); + } + + /// Gets the model class hash (hex) + pub fn class_hash(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.class_hash).unwrap(); + } + + /// Gets the model contract address (hex) + pub fn contract_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.contract_address).unwrap(); + } + + /// Gets the packed size + pub fn packed_size(&self) -> u32 { + self.inner.packed_size + } + + /// Gets the unpacked size + pub fn unpacked_size(&self) -> u32 { + self.inner.unpacked_size + } + + /// Returns true if the model uses legacy store + pub fn use_legacy_store(&self) -> bool { + self.inner.use_legacy_store + } + + /// Creates a new model from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::Model = serde_json::from_str(s)?; + Ok(Box::new(Model { inner })) + } + + /// Serializes the model to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents a Dojo entity + #[diplomat::opaque] + pub struct Entity { + pub(crate) inner: torii_proto::schema::Entity, + } + + impl Entity { + /// Gets the hashed keys (hex) + pub fn hashed_keys(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.hashed_keys).unwrap(); + } + + /// Gets the number of models in this entity + pub fn models_count(&self) -> u32 { + self.inner.models.len() as u32 + } + + /// Gets the created_at timestamp + pub fn created_at(&self) -> u64 { + self.inner.created_at.timestamp() as u64 + } + + /// Gets the updated_at timestamp + pub fn updated_at(&self) -> u64 { + self.inner.updated_at.timestamp() as u64 + } + + /// Gets the executed_at timestamp + pub fn executed_at(&self) -> u64 { + self.inner.executed_at.timestamp() as u64 + } + + /// Creates a new entity from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::schema::Entity = serde_json::from_str(s)?; + Ok(Box::new(Entity { inner })) + } + + /// Serializes the entity to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents a Dojo world + #[diplomat::opaque] + pub struct World { + pub(crate) inner: torii_proto::World, + } + + impl World { + /// Gets the world address (hex) + pub fn world_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.world_address).unwrap(); + } + + /// Gets the number of models in this world + pub fn models_count(&self) -> u32 { + self.inner.models.len() as u32 + } + + /// Creates a new world from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::World = serde_json::from_str(s)?; + Ok(Box::new(World { inner })) + } + + /// Serializes the world to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } +} + diff --git a/src/ffi/query.rs b/src/ffi/query.rs new file mode 100644 index 0000000..dd9413d --- /dev/null +++ b/src/ffi/query.rs @@ -0,0 +1,96 @@ +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::DiplomatStr; + + use crate::ffi::error::ffi::DojoError; + use crate::ffi::types::ffi::FieldElement; + + /// Query clause for filtering entities + #[diplomat::opaque] + pub struct Clause { + pub(crate) inner: torii_proto::Clause, + } + + /// Keys clause for filtering by entity keys + #[diplomat::opaque] + pub struct KeysClause { + pub(crate) keys: Vec, + pub(crate) pattern_matching: torii_proto::PatternMatching, + pub(crate) models: Vec, + } + + impl KeysClause { + /// Creates a new keys clause + pub fn new() -> Box { + Box::new(KeysClause { + keys: Vec::new(), + pattern_matching: torii_proto::PatternMatching::FixedLen, + models: Vec::new(), + }) + } + + /// Adds a key to filter by + pub fn add_key(&mut self, key: &FieldElement) { + self.keys.push(key.0); + } + + /// Adds a model to filter by + pub fn add_model(&mut self, model: &DiplomatStr) -> Result<(), Box> { + let s = std::str::from_utf8(model)?; + self.models.push(s.to_string()); + Ok(()) + } + } + + /// Entity query for retrieving entities from Torii + #[diplomat::opaque] + pub struct EntityQuery { + pub(crate) clause: Option, + pub(crate) limit: u32, + pub(crate) offset: u32, + } + + impl EntityQuery { + /// Creates a new entity query + pub fn new() -> Box { + Box::new(EntityQuery { + clause: None, + limit: 100, + offset: 0, + }) + } + + /// Sets the limit for the query + pub fn set_limit(&mut self, limit: u32) { + self.limit = limit; + } + + /// Sets the offset for the query + pub fn set_offset(&mut self, offset: u32) { + self.offset = offset; + } + } + + /// Model query for retrieving model definitions + #[diplomat::opaque] + pub struct ModelQuery { + pub(crate) model_names: Vec, + } + + impl ModelQuery { + /// Creates a new model query + pub fn new() -> Box { + Box::new(ModelQuery { + model_names: Vec::new(), + }) + } + + /// Adds a model name to query + pub fn add_model(&mut self, model_name: &DiplomatStr) -> Result<(), Box> { + let s = std::str::from_utf8(model_name)?; + self.model_names.push(s.to_string()); + Ok(()) + } + } +} + diff --git a/src/ffi/subscription.rs b/src/ffi/subscription.rs new file mode 100644 index 0000000..90f175a --- /dev/null +++ b/src/ffi/subscription.rs @@ -0,0 +1,19 @@ +#[diplomat::bridge] +pub mod ffi { + use stream_cancel::Trigger; + + /// Subscription handle for managing event streams + #[diplomat::opaque] + pub struct Subscription { + pub(crate) id: u64, + pub(crate) trigger: Trigger, + } + + impl Subscription { + /// Gets the subscription ID + pub fn id(&self) -> u64 { + self.id + } + } +} + diff --git a/src/ffi/tokens.rs b/src/ffi/tokens.rs new file mode 100644 index 0000000..5ee4b1f --- /dev/null +++ b/src/ffi/tokens.rs @@ -0,0 +1,171 @@ + +#[diplomat::bridge] +pub mod ffi { + use diplomat_runtime::{DiplomatStr, DiplomatWrite}; + use std::fmt::Write; + use crate::ffi::error::ffi::DojoError; + + /// Represents a token (ERC20, ERC721, or ERC1155) + #[diplomat::opaque] + pub struct Token { + pub(crate) inner: torii_proto::Token, + } + + impl Token { + /// Gets the contract address (hex) + pub fn contract_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.contract_address).unwrap(); + } + + /// Gets the token name + pub fn name(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.name).unwrap(); + } + + /// Gets the token symbol + pub fn symbol(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.symbol).unwrap(); + } + + /// Gets the token decimals + pub fn decimals(&self) -> u8 { + self.inner.decimals + } + + /// Gets the metadata as JSON string + pub fn metadata(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.metadata).unwrap(); + } + + /// Creates a token from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::Token = serde_json::from_str(s)?; + Ok(Box::new(Token { inner })) + } + + /// Serializes the token to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents a token balance for an account + #[diplomat::opaque] + pub struct TokenBalance { + pub(crate) inner: torii_proto::TokenBalance, + } + + impl TokenBalance { + /// Gets the account address (hex) + pub fn account_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.account_address).unwrap(); + } + + /// Gets the contract address (hex) + pub fn contract_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.contract_address).unwrap(); + } + + /// Gets the balance as a string + pub fn balance(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.balance).unwrap(); + } + + /// Creates a token balance from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::TokenBalance = serde_json::from_str(s)?; + Ok(Box::new(TokenBalance { inner })) + } + + /// Serializes the token balance to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents a token transfer event + #[diplomat::opaque] + pub struct TokenTransfer { + pub(crate) inner: torii_proto::TokenTransfer, + } + + impl TokenTransfer { + /// Gets the from address (hex) + pub fn from_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.from_address).unwrap(); + } + + /// Gets the to address (hex) + pub fn to_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.to_address).unwrap(); + } + + /// Gets the contract address (hex) + pub fn contract_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.contract_address).unwrap(); + } + + /// Gets the amount as a string + pub fn amount(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.amount).unwrap(); + } + + /// Gets the executed_at timestamp + pub fn executed_at(&self) -> u64 { + self.inner.executed_at.timestamp() as u64 + } + + /// Creates a token transfer from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::TokenTransfer = serde_json::from_str(s)?; + Ok(Box::new(TokenTransfer { inner })) + } + + /// Serializes the token transfer to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } + + /// Represents a token contract + #[diplomat::opaque] + pub struct TokenContract { + pub(crate) inner: torii_proto::TokenContract, + } + + impl TokenContract { + /// Gets the contract address (hex) + pub fn contract_address(&self, write: &mut DiplomatWrite) { + write!(write, "{:#x}", self.inner.contract_address).unwrap(); + } + + /// Gets the contract type as string + pub fn contract_type(&self, write: &mut DiplomatWrite) { + write!(write, "{}", self.inner.r#type).unwrap(); + } + + /// Creates a token contract from JSON + pub fn from_json(json: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(json)?; + let inner: torii_proto::TokenContract = serde_json::from_str(s)?; + Ok(Box::new(TokenContract { inner })) + } + + /// Serializes the token contract to JSON + pub fn to_json(&self, write: &mut DiplomatWrite) -> Result<(), Box> { + let json = serde_json::to_string(&self.inner)?; + write!(write, "{}", json).unwrap(); + Ok(()) + } + } +} + diff --git a/src/ffi/types.rs b/src/ffi/types.rs new file mode 100644 index 0000000..a20fc0a --- /dev/null +++ b/src/ffi/types.rs @@ -0,0 +1,253 @@ +#[diplomat::bridge] +pub mod ffi { + use crypto_bigint::Encoding; + use diplomat_runtime::{DiplomatStr, DiplomatWrite}; + use starknet_crypto::Felt; + use std::fmt::Write; + + use crate::ffi::error::ffi::{DojoError, ErrorType}; + + /// Represents a Starknet field element (Felt) + #[diplomat::opaque] + pub struct FieldElement(pub Felt); + + impl FieldElement { + /// Creates a new FieldElement from a hexadecimal string + pub fn new_from_hex(hex: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(hex)?; + let felt = Felt::from_hex(s).map_err(|e| { + DojoError::new(ErrorType::ParseError, &format!("Invalid felt hex: {}", e)) + })?; + Ok(Box::new(FieldElement(felt))) + } + + /// Creates a new FieldElement from big-endian bytes + pub fn new_from_bytes(bytes: &[u8]) -> Box { + Box::new(FieldElement(Felt::from_bytes_be_slice(bytes))) + } + + /// Returns the field element as a hexadecimal string + pub fn to_hex(&self, result: &mut DiplomatWrite) { + write!(result, "{:#x}", self.0).unwrap(); + } + + /// Returns the field element as bytes (big-endian) + pub fn to_bytes(&self, result: &mut [u8]) { + let bytes = self.0.to_bytes_be(); + result[..bytes.len()].copy_from_slice(&bytes); + } + } + + /// Represents a 256-bit unsigned integer + #[diplomat::opaque] + pub struct U256(pub crypto_bigint::U256); + + impl U256 { + /// Creates a new U256 from a hexadecimal string + pub fn new_from_hex(hex: &DiplomatStr) -> Result, Box> { + let s = std::str::from_utf8(hex)?; + let trimmed = s.trim_start_matches("0x"); + let value = crypto_bigint::U256::from_be_hex(trimmed); + Ok(Box::new(U256(value))) + } + + /// Creates a new U256 from big-endian bytes + pub fn new_from_bytes(bytes: &[u8]) -> Result, Box> { + if bytes.len() != 32 { + return Err(DojoError::new( + ErrorType::InvalidInput, + "U256 requires exactly 32 bytes", + )); + } + let mut arr = [0u8; 32]; + arr.copy_from_slice(bytes); + Ok(Box::new(U256(crypto_bigint::U256::from_be_bytes(arr)))) + } + + /// Returns the U256 as a hexadecimal string + pub fn to_hex(&self, result: &mut DiplomatWrite) { + write!(result, "0x{:x}", self.0).unwrap(); + } + + /// Returns the U256 as bytes (big-endian) + pub fn to_bytes(&self, result: &mut [u8]) { + let bytes = self.0.to_be_bytes(); + result[..32].copy_from_slice(&bytes); + } + } + + /// Represents a Starknet call + #[diplomat::opaque] + pub struct Call(pub starknet::core::types::Call); + + impl Call { + /// Creates a new Call + pub fn new( + to: &FieldElement, + selector: &FieldElement, + ) -> Box { + Box::new(Call(starknet::core::types::Call { + to: to.0, + selector: selector.0, + calldata: Vec::new(), + })) + } + + /// Adds a field element to the calldata + pub fn push_calldata(&mut self, felt: &FieldElement) { + self.0.calldata.push(felt.0); + } + + /// Creates a call from selector name + pub fn new_from_selector_name( + to: &FieldElement, + selector_name: &DiplomatStr, + ) -> Result, Box> { + let name = std::str::from_utf8(selector_name)?; + let selector = starknet::core::utils::get_selector_from_name(name) + .map_err(|e| DojoError::new(ErrorType::ParseError, &format!("Invalid selector: {}", e)))?; + + Ok(Box::new(Call(starknet::core::types::Call { + to: to.0, + selector, + calldata: Vec::new(), + }))) + } + } + + /// List of calls for batch transactions + #[diplomat::opaque] + pub struct CallList { + pub(crate) calls: Vec, + } + + impl CallList { + /// Creates a new empty call list + pub fn new() -> Box { + Box::new(CallList { calls: Vec::new() }) + } + + /// Adds a call to the list + pub fn add_call(&mut self, call: &Call) { + self.calls.push(call.0.clone()); + } + + /// Returns the number of calls in the list + pub fn len(&self) -> usize { + self.calls.len() + } + } + + /// Represents a signature (r, s pair) + #[diplomat::opaque] + pub struct Signature { + pub(crate) r: Felt, + pub(crate) s: Felt, + } + + impl Signature { + /// Creates a new signature from r and s components + pub fn new(r: &FieldElement, s: &FieldElement) -> Box { + Box::new(Signature { r: r.0, s: s.0 }) + } + + /// Gets the r component + pub fn r(&self, result: &mut DiplomatWrite) { + write!(result, "{:#x}", self.r).unwrap(); + } + + /// Gets the s component + pub fn s(&self, result: &mut DiplomatWrite) { + write!(result, "{:#x}", self.s).unwrap(); + } + } + + use crate::ffi::enums::ffi::{BlockTag, OrderDirection, PaginationDirection}; + + /// Block identifier (hash, number, or tag) + #[diplomat::opaque] + pub struct BlockId(pub(crate) starknet::core::types::BlockId); + + impl BlockId { + /// Creates a BlockId from a block hash + pub fn from_hash(hash: &FieldElement) -> Box { + Box::new(BlockId(starknet::core::types::BlockId::Hash(hash.0))) + } + + /// Creates a BlockId from a block number + pub fn from_number(number: u64) -> Box { + Box::new(BlockId(starknet::core::types::BlockId::Number(number))) + } + + /// Creates a BlockId from a block tag + pub fn from_tag(tag: BlockTag) -> Box { + Box::new(BlockId(starknet::core::types::BlockId::Tag(tag.into()))) + } + } + + /// Ordering specification for query results + #[diplomat::opaque] + pub struct OrderBy { + pub(crate) field: String, + pub(crate) direction: torii_proto::OrderDirection, + } + + impl OrderBy { + /// Creates a new OrderBy specification + pub fn new(field: &DiplomatStr, direction: OrderDirection) -> Result, Box> { + let field = std::str::from_utf8(field)?.to_string(); + Ok(Box::new(OrderBy { + field, + direction: direction.into(), + })) + } + } + + /// Pagination configuration for queries + #[diplomat::opaque] + pub struct Pagination { + pub(crate) cursor: Option, + pub(crate) limit: Option, + pub(crate) direction: torii_proto::PaginationDirection, + pub(crate) order_by: Vec, + } + + impl Pagination { + /// Creates a new Pagination with default values + pub fn new() -> Box { + Box::new(Pagination { + cursor: None, + limit: Some(100), + direction: torii_proto::PaginationDirection::Forward, + order_by: Vec::new(), + }) + } + + /// Sets the cursor for pagination + pub fn set_cursor(&mut self, cursor: &DiplomatStr) -> Result<(), Box> { + let s = std::str::from_utf8(cursor)?; + self.cursor = Some(s.to_string()); + Ok(()) + } + + /// Sets the limit for pagination + pub fn set_limit(&mut self, limit: u32) { + self.limit = Some(limit); + } + + /// Sets the direction for pagination + pub fn set_direction(&mut self, direction: PaginationDirection) { + self.direction = direction.into(); + } + + /// Adds an ordering specification + pub fn add_order_by(&mut self, order_by: &OrderBy) { + self.order_by.push(torii_proto::OrderBy { + field: order_by.field.clone(), + direction: order_by.direction.clone(), + }); + } + } +} + + diff --git a/src/lib.rs b/src/lib.rs index fd7abea..ecef553 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,13 @@ mod constants; mod types; mod utils; +// Diplomat FFI bridge modules +mod ffi; + +// Re-export diplomat-generated FFI +pub use ffi::*; + +// Keep old modules for reference during migration #[cfg(not(target_arch = "wasm32"))] mod c; #[cfg(target_arch = "wasm32")]