Smart Wallet
#![no_std]
#[contract]
struct SmartWallet;
use soroban_sdk::{auth::Context, contract, contractimpl, contracttype, BytesN, Env, Vec, log};
#[derive(Clone)]
#[contracttype]
pub enum DataKey {
Owner,
}
#[contractimpl]
impl SmartWallet {
// Initialize the contract with an owner's ed25519 public key.
pub fn init(env: Env, public_key: BytesN<32>) {
if env.storage().instance().has(&DataKey::Owner) {
panic!("Owner is already set");
}
env.storage().instance().set(&DataKey::Owner, &public_key);
/// @dev should remove logs before deploying smart contracts
log!(&env, "Public key: {}", public_key);
}
// Verifies the contract is authorized by the owner.
#[allow(non_snake_case)]
pub fn __check_auth(
env: Env,
signature_payload: BytesN<32>,
signature: BytesN<64>,
_auth_context: Vec<Context>,
) {
let public_key: BytesN<32> = env
.storage()
.instance()
.get::<_, BytesN<32>>(&DataKey::Owner)
.unwrap();
/// @dev should remove logs before deploying smart contracts
log!(&env, "Public key: {}", public_key);
env.crypto()
.ed25519_verify(&public_key, &signature_payload.into(), &signature);
}
}
Explanation
#![no_std]
This attribute prevents linking to the standard library, making the code lighter and more efficient for Soroban contracts. It's big so we save on size.
use soroban_sdk::{contract, contractimpl, Env, log}
Imports stuffs from the Soroban SDK. Env
is basic Soroban type, we need it because we can't use the Rust standard library.
#[derive(Clone)]
This allows copying the DataKey enum easily. #[contracttype]
Exposes this enum to other contracts.
init
checks if the Owner
key already exists in the contract's storage. If it doesn't exist, the function sets the Owner
key in the storage to the provided public key. If it already exists, the function panics with an error message. This prevents accidentally overwriting the owner's key.
#[allow(non_snake_case)]
This allows the function name to be __check_auth which doesn't follow Rust's snake_case convention. This might be necessary for compatibility with Soroban's API.
__check_auth
retrieves the stored owner's public key from the contract's storage using the DataKey::Owner
. It then uses the ed25519_verify
function from the crypto
module of the Soroban SDK to verify the signature. This ensures that the caller has the private key corresponding to the stored public key (i.e., the owner).
Run in Playground
Loading playground...