Crate wasi_sol

Source
Expand description

Β§πŸ¦€ Wasi Sol

wasi-sol-logo

made-with-rust Netlify Status Netlify Status Netlify Status Rust Maintenance Crates.io Crates.io Downloads docs License

Open in GitHub Codespaces

GigaDAO Discord

FrameworkDemoLive Demo
Yewyew-demoNetlify Status
Dioxusdioxus-demoNetlify Status
Leptosleptos-demoNetlify Status

A Solana Wallet adapter for WASM frameworks.

Β§πŸ”’ Wallets Support

WalletSupportedFeatures
Phantomβœ…All
Solflareβœ…All
Backpackβœ…All

§🌐 Wasm Frameworks Support

FrameworkSupported
Yewβœ…
Dioxusβœ…
Leptosβœ…

Β§βš™οΈ Features

MethodSupportedTested
connectβœ…βœ…
disconnectβœ…βœ…
sign_inβœ…βœ…
sign_messageβœ…βœ…
sign_transactionβœ…βœ…
send_transactionβœ…βœ…

Β§πŸ”₯ Getting Started

Wasi Sol provides providers and hooks that you can use to bring all wallet adapter functionalities to your app. To begin, wrap your main App component with the corresponding providers:

β“˜
// Yew Component

#[function_component]
pub fn App() -> Html {
    let endpoint = "https://api.mainnet-beta.solana.com";
    let wallets = vec![
        Wallet::Phantom.into(),
        Wallet::Solflare.into(),
        Wallet::Backpack.into(),
    ];

    html! {
        <ConnectionProvider {endpoint}>
            <WalletProvider {wallets}>
                <LoginPage />
            </WalletProvider>
        </ConnectionProvider>
    }
}

This will allow you to use the hooks to create the wallet adapter that exists in the wallets vector:

β“˜
// Yew Component

#[function_component]
pub fn LoginPage() -> Html {
    let phantom_context = use_wallet::<Wallet>(Wallet::Phantom);
    let solflare_context = use_wallet::<Wallet>(Wallet::Solflare);
    let backpack_context = use_wallet::<Wallet>(Wallet::Backpack);

    // ...snip...

    html! {
        <>
        </>
    }
}

Now you can choose the wallets you want to add to allow users to connect to. Wasi Sol comes with built-in reusable components that encapsulate all connect and disconnect logic so that you can develop web apps quickly:

β“˜
// Yew Component

#[function_component]
pub fn LoginPage() -> Html {
    // ...snip...

    html! {
        <LoginForm
            phantom={Some(phantom_wallet_adapter)}
            solflare={Some(solflare_wallet_adapter)}
            backpack={None}
            {connected}
        />
    }
}

This will select the Phantom and Solflare wallets and allow users to connect them to the app. The Backpack wallet is disabled in this case.

More detailed implementations can be found in the examples below.

Β§πŸš€ Examples

FrameworkExample
YewGithub
DioxusGithub
LeptosGithub

§🎧 Event Listener

Event Emitter Pattern

This crate implements a handy event listener pattern with a built-in emitter object that you can use to subscribe to particular events. This functionality allows you to set state in the UI, perform actions on wallet connect, and more.

β“˜
// Yew Component
// ...snip...

#[function_component]
pub fn LoginPage() -> Html {
    let wallet_context = use_wallet();
    let connected = use_state(|| false);
    let wallet_adapter = use_state(|| wallet_context);

    let connect_wallet = {
        // ...snip...

        Callback::from(move |_| {
            // ...snip...

            spawn_local(async move {
                let mut wallet_info = (*wallet_adapter).clone();

                wallet_info.emitter.on("connect", move |public_key: Pubkey| {
                    log::info!("Event Listener: Got pubkey {}", public_key);
                    wallet_adapter.set(wallet_info);
                    connected.set(true);
                });

                match wallet_info.connect().await {
                    Ok(_) => {
                    }
                    Err(err) => {
                        log::error!("Failed to connect wallet: {}", err);
                    }
                }
            });
        })
    };

    // ...snip...

    html! {
        <>
        </>
    }
}

event emitter demo

Β§πŸ‘₯ Contributing

Contributions and feedback are welcome! If you’d like to contribute, report an issue, or suggest an enhancement, please engage with the project on GitHub. Your contributions help improve this library for the community.

Β§πŸ“ License

This project is licensed under the MIT License.

ModulesΒ§

account
The Solana Account type.
account_info
Account information.
account_utils
Useful extras for Account state.
address_lookup_table
The address lookup table program.
address_lookup_table_accountDeprecated
alt_bn128
big_mod_exp
blake3
Hashing with the blake3 hash function.
borsh
Utilities for the borsh serialization format.
borsh0_9
Utilities for the borsh serialization format, version 0.9.
borsh0_10
Utilities for the borsh serialization format, version 0.10.
borsh1
Utilities for the borsh serialization format, version 1.
bpf_loader
The latest BPF loader native program.
bpf_loader_deprecated
The original and now deprecated Solana BPF loader.
bpf_loader_upgradeable
An upgradeable BPF loader native program.
bs58
Another Base58 codec implementation.
clientfull
Defines traits for blocking (synchronous) and non-blocking (asynchronous) communication with a Solana server as well a a trait that encompasses both.
clock
Information about the network’s clock, ticks, slots, etc.
commitment_configfull
Definitions of commitment levels.
compute_budgetfull
The compute budget native program.
config
The config native program.
core
debug_account_data
Debug-formatting of account data.
decode_error
Converting custom error codes to enums.
derivation_path
BIP-44 derivation paths.
deserialize_utils
Serde helpers.
ed25519_instructionfull
Instructions for the ed25519 native program.
ed25519_program
The ed25519 native program.
entrypoint
The Rust-based BPF program entrypoint supported by the latest BPF loader.
entrypoint_deprecated
The Rust-based BPF program entrypoint supported by the original BPF loader.
epoch_info
Information about the current epoch.
epoch_rewards
A type to hold data for the EpochRewards sysvar.
epoch_rewards_hasher
epoch_rewards_partition_data
epoch_schedule
Configuration for epochs and slots.
exit
Used by validators to run events on exit.
feature
Methods for working with Feature accounts.
feature_set
Collection of all runtime features.
fee
Fee structures.
fee_calculator
Calculation of transaction fees.
forms
genesis_configfull
The chain’s genesis config.
hard_forksfull
The list of slot boundaries at which a hard fork should occur.
hash
Hashing with the SHA-256 hash function, and a general Hash type.
incinerator
A designated address for burning lamports.
inflation
configuration for network inflation
inner_instruction
instruction
Types for directing the execution of Solana programs.
keccak
Hashing with the keccak (SHA-3) hash function.
lamports
Defines the LamportsError type.
loader_instruction
Instructions for the non-upgradable BPF loader.
loader_upgradeable_instruction
Instructions for the upgradable BPF loader.
loader_v4
The v4 built-in loader program.
loader_v4_instruction
Instructions for the v4 built-in loader program.
message
Sequences of Instructions executed within a single transaction.
native_loader
The native loader native program.
native_token
Definitions for the native SOL token and its fractional lamports.
net
nonce
Durable transaction nonces.
nonce_account
Functions related to nonce accounts.
offchain_messagefull
Off-chain message container for storing non-transaction messages.
packet
The definition of a Solana network packet.
poh_config
Definitions of Solana’s proof of history.
poseidon
Hashing with the Poseidon hash function.
precompilesfull
Solana precompiled programs.
program
Cross-program invocation.
program_error
The ProgramError type and related definitions.
program_memory
Basic low-level memory operations.
program_option
A C representation of Rust’s Option, used across the FFI boundary for Solana program interfaces.
program_pack
The Pack serialization trait.
program_stubsNon-target_os="solana"
Implementations of syscalls used when solana-program is built for non-SBF targets.
program_utils
Contains a single utility function for deserializing from bincode.
provider
pubkey
Solana account addresses.
quicfull
Definitions related to Solana over QUIC.
recent_blockhashes_account
Helpers for the recent blockhashes sysvar.
rent
Configuration for network rent.
reward_type
Enumeration of reward types.
rpc_port
RPC default port numbers.
sanitize
A trait for sanitizing values and members of over the wire messages.
sdk_ids
A vector of Solana SDK IDs.
secp256k1_instructionfull
Instructions for the secp256k1 native program.
secp256k1_program
The secp256k1 native program.
secp256k1_recover
Public key recovery from secp256k1 ECDSA signatures.
serde_varint
Integers that serialize to variable size.
serialize_utils
Helpers for reading and writing bytes.
short_vec
Compact serde-encoding of vectors with small length.
shred_versionfull
Calculation of shred versions.
signaturefull
Functionality for public and private keys.
signerfull
Abstractions and implementations for transaction signers.
simple_vote_transaction_checkerfull
slot_hashes
A type to hold data for the SlotHashes sysvar.
slot_history
A type to hold data for the SlotHistory sysvar.
stake
The stake native program.
stake_history
A type to hold data for the StakeHistory sysvar.
syscalls
Declarations of Solana program syscalls.
system_instruction
Instructions and constructors for the system program.
system_program
The system native program.
system_transactionfull
The system_transaction module provides functionality for creating system transactions.
sysvar
Access to special accounts with dynamically-updated data.
timing
The timing module provides std::time utility functions.
transactionfull
Atomically-committed sequences of instructions.
transaction_context
Data shared between program runtime and built-in programs as well as SBF programs.
transportfull
Defines the TransportError type.
vote
The vote native program.

MacrosΒ§

custom_heap_default
Define the default global allocator.
custom_panic_default
Define the default global panic handler.
declare_deprecated_id
declare_deprecated_sysvar_id
Same as declare_sysvar_id except that it reports that this ID has been deprecated.
declare_id
declare_sysvar_id
Declares an ID that implements SysvarId.
entrypointDeprecated
entrypoint_deprecatedDeprecated
impl_sysvar_get
Implements the Sysvar::get method for both SBF and host targets.
msg
Print a message to the log.
program_stubsDeprecated
pubkey
pubkeys
respan
A proc-macro which respans the tokens in its first argument (a Path) to be resolved at the tokens of its second argument. For internal use only.
saturating_add_assign
Convenience macro for AddAssign with saturating arithmetic. Replace by std::num::Saturating once stable
unchecked_div_by_const
Convenience macro for doing integer division where the operation’s safety can be checked at compile-time.

FunctionsΒ§

spawn_local
Runs a Rust Future on the current thread.

Attribute MacrosΒ§

wasm_bindgen
A list of all the attributes can be found here: https://rustwasm.github.io/docs/wasm-bindgen/reference/attributes/index.html