Skip to content

Instantly share code, notes, and snippets.

@OkoliEvans
Last active May 27, 2024 09:51
Show Gist options
  • Save OkoliEvans/2b387ff8bfd00fca9062a3f1ef1f6403 to your computer and use it in GitHub Desktop.
Save OkoliEvans/2b387ff8bfd00fca9062a3f1ef1f6403 to your computer and use it in GitHub Desktop.
// ANCHOR: library_dispatcher
#[starknet::interface]
pub trait IMathUtils<T> {
fn add(ref self: T, x: u32, y: u32) -> u32;
fn set_class_hash(ref self: T, class_hash: starknet::ClassHash);
}
// create and declare contract class for contract A
#[starknet::contract]
pub mod MathUtils {
#[storage]
struct Storage {}
#[abi(embed_v0)]
impl ImathUtilsImpl of super::IMathUtils<ContractState>{
fn add(ref self: ContractState, x: u32, y: u32) -> u32 {
x + y
}
fn set_class_hash(ref self: ContractState, class_hash: starknet::ClassHash) {}
}
}
// create contract B to make library call to contract A
#[starknet::contract]
pub mod MathUtilsLibraryCall {
use starknet::{class_hash::class_hash_const, ContractAddress};
use super::{ IMathUtilsDispatcherTrait, IMathUtilsLibraryDispatcher };
#[storage]
struct Storage {
value: u32,
lib_class_hash: starknet::ClassHash,
}
#[abi(embed_v0)]
impl MathUtils of super::IMathUtils<ContractState> {
fn add(ref self: ContractState, x: u32, y: u32) -> u32 {
IMathUtilsLibraryDispatcher { class_hash: class_hash_const::<0x1234>() }
.add(x , y)
}
#[abi(embed_v0)]
fn set_class_hash(ref self: ContractState, class_hash: starknet::ClassHash) {
self.lib_class_hash.write(class_hash);
}
}
}
// ANCHOR_END: library_dispatcher
mod tests {
use starknet::syscalls::{ deploy_syscall };
use starknet::SyscallResultTrait;
use library_calls::library_call::{ MathUtils ,MathUtilsLibraryCall, IMathUtilsDispatcher, IMathUtilsDispatcherTrait};
#[test]
#[available_gas(20000000)]
fn test_library_dispatcher() {
let math_utils_class_hash: starknet::ClassHash = MathUtils::TEST_CLASS_HASH.try_into().unwrap();
let mut calldata: Array<felt252> = array![];
let (address, _) = deploy_syscall(
MathUtilsLibraryCall::TEST_CLASS_HASH.try_into().unwrap(), 0, calldata.span(), false
)
.unwrap_syscall();
let mut contract = IMathUtilsDispatcher { contract_address: address };
contract.set_class_hash(math_utils_class_hash);
let mut result = contract.add(30, 5);
assert_eq!(result, 35, "Wrong result");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment