Skip to main content

Tutorial 1: time based restriction on token transfers

Imagine a multi-sig account contract where certain actions, like transferring tokens, need to be controlled by the time elapsed between consecutive transfers. For example, a token transfer should only be allowed if a certain period of time has passed since the last transfer. This can be useful in scenarios where you want to limit the frequency of transactions to prevent misuse or to implement rate limiting.

Base concepts

Time-based restrictions

The idea is to enforce a minimum time interval between consecutive token transfers. Each token can have its own time limit, and the contract will track the last transfer time for each token.

Data storage

The contract will store the time limit and last transfer time for each token in its storage to keep track of these values across transactions.

Code walkthrough

Contract structure and imports

Contract initialization

  1. Initializes the contract with a list of signers’ public keys
  2. Stores the count of signers in the contract’s storage

Setting time limits

  1. Allows setting a time limit for a specific token
  2. Ensures that only the contract itself can set these limits by requiring the contract’s authorization

Custom authentication and authorization

  1. Authenticates the signatures
  2. Checks if all required signers have signed
  3. Iterates through the authorization context to verify the authorization policy

Authentication logic

  1. Verifies that the signatures are in the correct order and that each signer is authorized
  2. Uses ed25519_verify function to verify each signature

Authorization policy verification

  1. Checks if the function being called is a transfer or approve function
  2. Enforces the time-based restriction by comparing the current time with the last transfer time
  3. Updates the last transfer time if the transfer is allowed

Summary

The contract begins by initializing with a set of authorized signers. It allows setting a time limit for token transfers, which controls how frequently a token can be transferred. The __check_auth function is the core of the authorization process, ensuring that all necessary signatures are valid and checking the time-based restriction for token transfers. If the required time has not passed since the last transfer, the contract will deny the operation, enforcing the desired rate limiting. By tracking the last transfer time and enforcing a minimum time interval between transfers, the contract effectively limits the frequency of token transfers, resolving the issue of potential abuse through rapid consecutive transactions.

Complete code

Here are all the snippets stacked together in a single file for convenience:
These are the test cases. Put them in src/test.rs, which the mod test; line at the end of the contract loads. They need these dev-dependencies in the contract’s Cargo.toml:

Tutorial 2: implementing a smart wallet (WebAuthn)

Imagine a world where traditional passwords are obsolete. In this world, WebAuthn (Web Authentication) has become the standard for secure online interactions. Alice, a blockchain enthusiast, wants to create a wallet that leverages WebAuthn technology for enhanced security. She decides to implement a WebAuthn wallet on Stellar, allowing users to manage their digital assets using their device’s biometric features or security keys (e.g., YubiKey, Google Titan Security Key, etc.).
This contract is an unaudited teaching example. Do not use it to hold real funds. For a production wallet, use passkey-kit or OpenZeppelin Smart Accounts, which the guestbook tutorial uses.

Base concepts

WebAuthn is a web standard for passwordless authentication. It allows users to authenticate using biometrics (like fingerprints or facial recognition). The WebAuthn wallet implemented in this tutorial will be able to:
  1. Register and manage user credentials (public keys)
  2. Authenticate users for transaction signing
  3. Differentiate between admin and regular users
  4. Allow contract updates for future improvements
This tutorial is a simplified version of the smart-wallet contract in stellar/passkey-kit.

Code walkthrough

Contract structure and imports

This section sets up the contract structure and imports necessary components from the Soroban SDK. It also defines constants: a week of ledgers, used in the TTL extensions, the instance storage key for the admin signer count, and the WebAuthn size limits and flag that __check_auth checks. The contract parses the WebAuthn client data JSON with serde and serde-json-core. Add them to the contract’s Cargo.toml:

Error definitions

This enum defines possible errors that can occur during contract execution.

Event definitions

These typed events are published when a signer is added or removed. Their topics start with sw_v1 and the action name, then the fields marked #[topic]. The event data is the one remaining field, or void when there is none. See Publish events from a Rust contract for more about #[contractevent].
A SignerAdded event looks like this in the XDR JSON form. The getEvents RPC method returns the same shape in topicJson and valueJson when you request xdrFormat: "json".
A SignerRemoved event has the topics sw_v1, remove and the signer id, with "data": "void".

Core contract functions

These functions handle adding and removing signers, updating the contract, and managing admin counts. The constructor sets the first admin signer when the contract is deployed, so the wallet never exists without an owner. After that, add always requires the wallet’s own authorization. The admin signer count goes up only when an ID becomes an admin, so remove refuses to delete the last admin.

Signature structure

Signature represents a WebAuthn signature. ClientDataJson holds the challenge and type fields that __check_auth reads from the client data JSON.

CustomAccountInterface implementation

This implements the core authentication logic for the WebAuthn wallet. After it finds the signer’s public key, __check_auth checks the WebAuthn data in this order:
  1. authenticator_data is 37 to 1024 bytes long.
  2. The User Present flag (bit 0 of byte 32 of authenticator_data) is set. User Verification is not required.
  3. client_data_json is at most 1024 bytes, so it fits the parse buffer. Without this check, to_buffer::<1024>() panics.
  4. The client data type is webauthn.get.
  5. The client data challenge is the base64 URL encoding of the signature payload. This binds the WebAuthn signature to this authorization.
Each failed check returns its own Error variant. Only then does the contract verify the secp256r1 signature over authenticator_data followed by the SHA-256 hash of client_data_json. The host panics if the signature is not valid.

Base64 url encoding

This function provides Base64 URL encoding functionality used in the WebAuthn process.

Written explanation of code

The WebAuthn wallet contract manages user credentials and authentication. It allows adding and removing signers, distinguishing between admin and regular users. The constructor stores the first admin signer at deploy time. The add function registers new signers with the wallet’s authorization, storing admin keys persistently and regular keys temporarily. The remove function deletes signers, and update allows contract upgrades. The core of the wallet’s security is the __check_auth function, which verifies WebAuthn signatures. It checks the size and flags of the authenticator data, checks the type and challenge in the client data JSON, and then verifies the signature against the stored public key. The contract uses Soroban’s storage capabilities to manage keys and admin counts, with different TTLs (Time To Live) for persistent and temporary storage.

Test cases

These are test cases to ensure our WebAuthn wallet is functioning correctly. We’ll use the Soroban SDK’s testing utilities to create and run these tests. The second test re-adds the only admin and checks that the wallet still refuses to remove it.

Summary

This WebAuthn wallet implementation provides a secure and user-friendly way to manage digital assets on Stellar. It leverages the security benefits of WebAuthn while maintaining the flexibility needed for blockchain interactions.

Complete code

Here are all the snippets stacked together in a single file for convenience. The file needs the serde and serde-json-core dependencies from Contract structure and imports.