Skip to content

r0gue-io/PSP34

 
 

Repository files navigation

PSP34 Non-Fungible Token

This is the PSP34 implementation from Cardinal Cryptography.

Note that both the implementation and the psp34 standard are under development and are subjected to change. Not production-ready as of yet.

PSP34 is a non-fungible token standard for WebAssembly smart contracts running on blockchains based on the Substrate framework. It is an equivalent of Ethereum's ERC-721. The definition of the PSP34 standard can be found here.

This repository contains a simple, minimal implementation of the PSP34 token in ink! programming language.

How to use this repository

To use this crate please add the following line in your Cargo.toml:

psp34 = { git = "https://github.com/r0gue-io/PSP34.git", default-features = false }

The contents of this repository can be used in following ways:

1. Ready to use contract

The file lib.rs contains a ready to use implementation of basic PSP34 token contract. To use it, please check out this repository and compile its contents with Pop CLI:

$ pop build --release

2. Cross contract calling with traits

The PSP34 trait contains all the methods defined in the PSP34 standard. The trait can be used together with ink!'s contract_ref macro to allow for convenient cross-contract calling.

In your contract, if you would like to make a call to some other contract implementing the PSP34 standard, all you need to do is:

use ink::contract_ref;
use psp34::PSP34;

let mut token: contract_ref!(PSP34) = other_address.into();

// Now `token` has all the PSP34 methods
let balance = token.balance_of(some_account);
token.transfer(recipient, value, vec![]); // returns Result<(), PSP34Error>

The same method can be used with other traits (PSP34Metadata, PSP34Burnable, PSP34Mintable) defined in this crate. See the contents of traits.rs.

3. Custom implementation of PSP34 logic with PSP34Data

The PSP34Data class can be used to extend your contract with PSP34 token logic. In other words, you can easily build contracts that implement PSP34 interface alongside some other functionalities defined by the business logic of your project.

The methods of the PSP34Data class correspond directly to queries and operations defined by the PSP34 token standard. To make your contract become a PSP34 token, you need to:

  • Put a single PSP34Data instance in your contract's storage and initialize it with some starting supply of tokens.
  • Add definitions of Transfer, Approval and AttributeSet events in the body of your contract.
  • Add the impl PSP34 for [struct_name] block with implementation of PSP34 trait messages using PSP34Data methods. Each method which mutates the state of the token database returns a Result<Vec<PSP34Event>, PSP34Error> with all events generated by that operation. Please make sure to handle errors correctly and emit the resulting events (see the emit_events function).
  • Optionally implement also the PSP34Metadata trait to make your token play nice with other ecosystem tools.

The contract in lib.rs contains an example implementation following all the above steps. Feel free to copy-paste parts of it.

4. Burnable and Mintable extensions

The PSP34Data class contains also burn and mint methods, which can be used to implement PSP34Burnable and PSP34Mintable extensions and make your token burnable and/or mintable. An example implementation follows the same pattern as for the base trait:

impl PSP34Burnable for Token {
    #[ink(message)]
    fn burn(&mut self, value: u128) -> Result<(), PSP34Error> {
        // Check if the caller is allowed to burn!
        let events = self.data.burn(self.env().caller(), value)?;
        self.emit_events(events);
        Ok(())
    }
}

Please note that PSP34Data burn and mint methods do not enforce any form of access control. It's probably not a good idea to have a token which can be minted and burned by anyone anytime. When implementing Burnable and Mintable extensions, please make sure that their usage is restricted according to your project's business logic. For example:

#[ink(storage)]
pub struct Token {
    data: PSP34Data,
    owner: AccountId, // creator of the token
}

impl Token {
    #[ink(constructor)]
    pub fn new() -> Self {
        Self {
            data: PSP34Data::new(),
            owner: Self::env().caller(),
        }
    }
// ...
}

impl PSP34Burnable for Token {
    #[ink(message)]
    fn burn(&mut self, id: Id) -> Result<(), PSP34Error> {
        if self.env().caller() != self.owner {
            return PSP34Error::Custom(String::from("Only owner can burn"));
        }
        let events = self.data.burn(self.env().caller(), id)?;
        self.emit_events(events);
        Ok(())
    }
}

5. Enumerable extension

This is an optional extension that allows enumerating tokens on the chain. Enabling the extension will introduce a large gas overhead.

Can be implemented by enabling enumerable feature enabled while compiling the contents of the repository. To access its messages simply implement the PSP34Enumerable trait for your token:

#[ink(storage)]
pub struct Token {
    data: PSP34Data,
}

//...

impl PSP34Enumerable for Token {
    #[ink(message)]
    fn owners_token_by_index(&self, owner: AccountId, index: u128) -> Result<Id, PSP34Error> {
        self.data.owners_token_by_index(owner, index)
    }

    #[ink(message)]
    fn token_by_index(&self, index: u128) -> Result<Id, PSP34Error> {
        self.data.token_by_index(index)
    }
}

6. Metadata extension

Within the crate's metadata::Data there is also a set_attribute() method. It is generally used in conjunction with mint() from the PSP34Mintable. Note that the set_attribute() method will emit the AttributeSet event.

7. Unit testing

This crate comes with a suite of unit tests for PSP34 tokens. It can be easily added to your contract's unit tests with a helper macro tests!. For the macro to work you need to implement PSP34Burnable and PSP34Mintable traits. The macro should be invoked inside the main contract's module (the one annotated with #[ink::contract]):

#[ink::contract]
mod mycontract {
    ...
    #[ink(storage)]
    pub struct MyContract { ... }
    ...
    #[cfg(test)]
    mod tests { 
        crate::tests!(Token, Token::new);
    }
}

As you can see in the code snippet above, the tests! macro takes two arguments. The first one should be a name of a struct which implements PSP34 trait (usually your contract storage struct). The second argument should be a token constructor for the contract. In other words, the second argument should be a name of a function that returns the PSP34 struct.

Implementation-Specific Details

In certain scenarios, the PSP34 standard does not strictly define the behavior, and this section outlines the non-specified behavior in the current implementation. The methods discussed here can be found in data.rs.

1. Id type

The type does not have a custom equals method implemented. Consequently Id::U8(1) is not equal to Id::U16(1), for example.

2. Approval

The approve() method follows a "fall-through" approval logic for a single token. If an approved user calls this method, they will subsequently issue an approval for the owner's token to a third-party operator.

This behavior does not extend to "blanket" approvals. Approving for all tokens only grants approval for the caller's owned tokens. Additionally, for enhanced security, approve() does not allow revoking approval for a single token when the operator is approved for all tokens using

approve(caller, operator, None::<Id>, true)

3. Metadata

The set_attribute() method recommended implementation is included into the metadata.rs It is a good practice to use the method together with mint() method.

4. Balance of

Return type of the balance_of() method is u32, while the total_supply value is u128, be wary of possible overflows.

Releases

No releases published

Packages

No packages published

Languages

  • Rust 100.0%