Scaffolded TypeScript NFT Project for ERC-721

Blockchain App Builder takes the input from your NFT specification file and generates a fully-functional scaffolded chaincode project.

The project automatically generates NFT lifecycle classes and functions, including CRUD and non-CRUD methods, as well as a tokenization SDK. Validation of arguments, marshalling/unmarshalling, and transparent persistence capability are all supported automatically.

For information on the scaffolded project and methods that are not directly related to NFTs, see Scaffolded TypeScript Chaincode Project.

Model

Every tokenized model class extends the OchainModel class. Transparent Persistence Capability, or simplified ORM, is captured in the OchainModel class.

import * as yup from 'yup';
import { Id, Mandatory, Validate, Default, Embedded, Derived, ReadOnly } from '../../lib/decorators';
import { OchainModel } from '../../lib/ochain-model';
import { STRATEGY } from '../../lib/utils';
import { EmbeddedModel } from '../../lib/ochain-embedded-model';

export class ArtCollectionMetadata extends EmbeddedModel<ArtCollectionMetadata> {
    @Validate(yup.string())
    public painting_name: string;

    @Validate(yup.string())
    public description: string;

    @Validate(yup.string())
    public image: string;

    @Validate(yup.string())
    public painter_name: string;

}
    
@Id('tokenId')       
export class ArtCollection extends OchainModel<ArtCollection> {

    public readonly assetType = 'otoken';
        
    @Mandatory()
    @Validate(yup.string().required().matches(/^[A-Za-z0-9][A-Za-z0-9_-]*$/).max(16))
    public tokenId: string;

    @ReadOnly('artcollection')
    public tokenName: string;

    @Validate(yup.string().trim().max(256))
    public tokenDesc: string;

    @ReadOnly('ART')
    public symbol: string;

    @ReadOnly('erc721+')
    public tokenStandard: string;

    @ReadOnly('nonfungible')
    public tokenType: string;

    @ReadOnly('whole')
    public tokenUnit: string;

      @ReadOnly(["indivisible","singleton","mintable","transferable","burnable","roles"])
    public behaviors: string[];

    @ReadOnly({minter_role_name: "minter"})
    public roles: object;

    @ReadOnly({max_mint_quantity: 20000})
    public mintable: object;

    @Validate(yup.string())
    public owner: string;

    @Validate(yup.string())
    public createdBy: string;

    @Validate(yup.string())
    public transferredBy: string;

    @Validate(yup.string())
    public creationDate: string;

    @Validate(yup.string())
    public transferredDate: string;

    @Validate(yup.bool())
    public isBurned: boolean;

    @Validate(yup.string())
    public burnedBy: string;

    @Validate(yup.string())
    public burnedDate: string;

    @Validate(yup.string().max(2000))
    public tokenUri: string;
    
    @Embedded(ArtCollectionMetadata)
    public metadata: ArtCollectionMetadata;

    @Validate(yup.number())
    public price: number;

    @Validate(yup.boolean())
    public on_sale_flag: boolean;

}

Controller

The main controller class extends the OchainController class. There is only one main controller.

export class DigiCurrCCController extends OchainController{

You can create any number of classes, functions, or files, but only those methods that are defined within the main controller class are invokable. The other methods are hidden.

You can use the token SDK methods to write custom methods for your business application.

Automatically Generated NFT Methods

Blockchain App Builder automatically generates methods to support NFTs and NFT life cycles. You can use these methods to initialize NFTs, manage roles and accounts, and complete other NFT lifecycle tasks without any additional coding. Controller methods must have a @Validator(...params) decorator to be invokable.

Methods for Access Control Management

addTokenAdmin
This method adds a user as a Token Admin of the chaincode. This method can be called only by a Token Admin of the chaincode.
@Validator(yup.string(), yup.string())
public async addTokenAdmin(orgId: string, userId: string) {
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721ADMIN.addAdmin', 'TOKEN');
    return await this.Ctx.ERC721Admin.addAdmin(orgId, userId);
}
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • On success, a message that includes details of the user who was added as a Token Admin of the chaincode.
Return Value Example:
{"msg":"Successfully added Admin (orgId: Org1MSP, userId: User1)"}
removeTokenAdmin
This method removes a user as a Token Admin of the chaincode. This method can be called only by a Token Admin of the chaincode.
@Validator(yup.string(), yup.string())
public async removeTokenAdmin(orgId: string, userId: string) {
   await this.Ctx.ERC721Auth.checkAuthorization('ERC721ADMIN.removeAdmin', 'TOKEN');
   return await this.Ctx.ERC721Admin.removeAdmin(orgId, userId);
}
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • On success, a message that includes details of the user who was removed as a Token Admin of the chaincode.
Return Value Example:
{"msg": "Successfully removed Admin (orgId: Org1MSP, userId: User1)"}
isTokenAdmin
This method returns the Boolean value true if the caller of the function is a Token Admin, otherwise it returns false. A Token Admin can call this function on any other user in the blockchain network. Other users can call this method only on their own accounts.
@GetMethod()
@Validator(yup.string(), yup.string())
public async isTokenAdmin(orgId: string, userId: string) {
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721ADMIN.isUserTokenAdmin', 'TOKEN');
    return await this.Ctx.ERC721Auth.isUserTokenAdmin(orgId, userId);
}
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • The method returns true if the caller is a Token Admin, otherwise it returns false.
Return Value Example:
{"result": true}
getAllTokenAdmins
This method returns a list of all users who are a Token Admin of the chaincode. This method can be called only by the Token Admin of the chaincode.
@GetMethod()
@Validator()
public async getAllTokenAdmins() {
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721ADMIN.getAllAdmins', 'TOKEN');
    return await this.Ctx.ERC721Admin.getAllAdmins();
}
Parameters:
  • none
Returns:
  • On success, an admins array in JSON format that contains orgId and userId objects.
Return Value Example:
{"admins":[{"orgId":"Org1MSP","userId":"admin"}]}

Methods for Token Configuration Management

init
This method is called when the chaincode is instantiated. Every Token Admin is identified by the userId and orgId information in the adminList parameter. The userId is the user name or email ID of the instance owner or the user who is logged in to the instance. The orgId is the membership service provider (MSP) ID of the user in the current network organization. The adminList parameter is mandatory the first time you deploy the chaincode. If you are upgrading the chaincode, pass an empty list ([]). Any other information in the adminList parameter is ignored during upgrades.
@Validator(yup.array().of(yup.object()).nullable())
public async init(adminList: ERC721TokenAdminAsset[]) {
   await this.Ctx.ERC721Admin.initAdmin(adminList);
   await this.Ctx.ERC721Token.saveClassInfo(<NFT_NAME>);
   await this.Ctx.ERC721Token.saveDeleteTransactionInfo();
   return;
}
Parameters:
  • adminList array – An array of {orgId, userId} information that specifies the list of token admins. The adminList array is a mandatory parameter.
getAllTokens
This method returns all of the token assets that are saved in the state database. This method can be called only by a Token Admin of the chaincode. This method uses Berkeley DB SQL rich queries and can only be called when connected to the remote Oracle Blockchain Platform network.
@GetMethod()
@Validator()
public async getAllTokens() {
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721TOKEN.getAllTokens', 'TOKEN');
    return await this.Ctx.ERC721Token.getAllTokens();
}
Parameters:
  • none
Returns:
  • A list of all token assets in JSON format.
Return Value Example:
[
    {
        "key": "monalisa",
        "valueJson": {
            "metadata": {
                "PaintingName": "Mona_Lisa",
                "Description": "Mona Lisa Painting",
                "Image": "monalisa.jpeg",
                "PainterName": "Leonardo_da_Vinci"
            },
            "assetType": "otoken",
            "tokenId": "monalisa",
            "tokenName": "ravinft",
            "tokenDesc": "token Description",
            "symbol": "PNT",
            "tokenStandard": "erc721+",
            "tokenType": "nonfungible",
            "tokenUnit": "whole",
            "behaviors": [
                "indivisible",
                "singleton",
                "mintable",
                "transferable",
                "burnable",
                "roles"
            ],
            "roles": {
                "minter_role_name": "minter",
                "burner_role_name": "burner"
            },
            "mintable": {
                "max_mint_quantity": 20000
            },
            "owner": "oaccount~543c2258e351c3e7a40ea59b81e62154d38fbfc9d1b5b79f30ac5e08e7d0dfd1",
            "createdBy": "oaccount~543c2258e351c3e7a40ea59b81e62154d38fbfc9d1b5b79f30ac5e08e7d0dfd1",
            "creationDate": "2022-04-07T21:17:48.000Z",
            "isBurned": false,
            "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
            "NftBasePrice": 100
        }
    },
    {
        "key": "monalisa1",
        "valueJson": {
            "metadata": {
                "PaintingName": "Mona_Lisa",
                "Description": "Mona Lisa Painting",
                "Image": "monalisa.jpeg",
                "PainterName": "Leonardo_da_Vinci"
            },
            "assetType": "otoken",
            "tokenId": "monalisa1",
            "tokenName": "ravinft",
            "tokenDesc": "token Description",
            "symbol": "PNT",
            "tokenStandard": "erc721+",
            "tokenType": "nonfungible",
            "tokenUnit": "whole",
            "behaviors": [
                "indivisible",
                "singleton",
                "mintable",
                "transferable",
                "burnable",
                "roles"
            ],
            "roles": {
                "minter_role_name": "minter",
                "burner_role_name": "burner"
            },
            "mintable": {
                "max_mint_quantity": 20000
            },
            "owner": "oaccount~543c2258e351c3e7a40ea59b81e62154d38fbfc9d1b5b79f30ac5e08e7d0dfd1",
            "createdBy": "oaccount~543c2258e351c3e7a40ea59b81e62154d38fbfc9d1b5b79f30ac5e08e7d0dfd1",
            "creationDate": "2022-04-07T21:17:59.000Z",
            "isBurned": false,
            "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
            "NftBasePrice": 100
        }
    }
]
getAllTokensByUser
This method returns all of the token assets that are owned by a specified user. This method uses Berkeley DB SQL rich queries and can only be called when connected to the remote Oracle Blockchain Platform network. This method can be called only by a Token Admin of the chaincode or by the account owner.
@GetMethod()
@Validator(yup.string(), yup.string())
public async getAllTokensByUser(orgId: string, userId: string) {
    const accountId = await this.Ctx.ERC721Account.generateAccountId(orgId, userId);
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721TOKEN.getAllTokensByUser', 'TOKEN', { accountId });
    return await this.Ctx.ERC721Token.getAllTokensByUser(accountId);
}
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • A list of token assets in JSON format.
Return Value Example:
[
    {
        "key": "monalisa",
        "valueJson": {
            "metadata": {
                "PaintingName": "Mona_Lisa",
                "Description": "Mona Lisa Painting",
                "Image": "monalisa.jpeg",
                "PainterName": "Leonardo_da_Vinci"
            },
            "assetType": "otoken",
            "tokenId": "monalisa",
            "tokenName": "ravinft",
            "tokenDesc": "token Description",
            "symbol": "PNT",
            "tokenStandard": "erc721+",
            "tokenType": "nonfungible",
            "tokenUnit": "whole",
            "behaviors": [
                "indivisible",
                "singleton",
                "mintable",
                "transferable",
                "burnable",
                "roles"
            ],
            "roles": {
                "minter_role_name": "minter",
                "burner_role_name": "burner"
            },
            "mintable": {
                "max_mint_quantity": 20000
            },
            "owner": "oaccount~543c2258e351c3e7a40ea59b81e62154d38fbfc9d1b5b79f30ac5e08e7d0dfd1",
            "createdBy": "oaccount~543c2258e351c3e7a40ea59b81e62154d38fbfc9d1b5b79f30ac5e08e7d0dfd1",
            "creationDate": "2022-04-07T21:17:48.000Z",
            "isBurned": false,
            "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
            "NftBasePrice": 100
        }
    },
    {
        "key": "monalisa1",
        "valueJson": {
            "metadata": {
                "PaintingName": "Mona_Lisa",
                "Description": "Mona Lisa Painting",
                "Image": "monalisa.jpeg",
                "PainterName": "Leonardo_da_Vinci"
            },
            "assetType": "otoken",
            "tokenId": "monalisa1",
            "tokenName": "ravinft",
            "tokenDesc": "token Description",
            "symbol": "PNT",
            "tokenStandard": "erc721+",
            "tokenType": "nonfungible",
            "tokenUnit": "whole",
            "behaviors": [
                "indivisible",
                "singleton",
                "mintable",
                "transferable",
                "burnable",
                "roles"
            ],
            "roles": {
                "minter_role_name": "minter",
                "burner_role_name": "burner"
            },
            "mintable": {
                "max_mint_quantity": 20000
            },
            "owner": "oaccount~543c2258e351c3e7a40ea59b81e62154d38fbfc9d1b5b79f30ac5e08e7d0dfd1",
            "createdBy": "oaccount~543c2258e351c3e7a40ea59b81e62154d38fbfc9d1b5b79f30ac5e08e7d0dfd1",
            "creationDate": "2022-04-07T21:17:59.000Z",
            "isBurned": false,
            "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
            "NftBasePrice": 100
        }
    }
]
getTokenById
This method returns a token object if the token is present in the state database. This method can be called only by a Token Admin of the chaincode or the token owner.
@GetMethod()
@Validator(yup.string())
public async getTokenById(tokenId: string) {
   await this.Ctx.ERC721Auth.checkAuthorization('ERC721TOKEN.get', 'TOKEN', { tokenId });
   let token = await this.getTokenObject(tokenId);
   return token;
}
Parameters:
  • tokenId: string – The ID of the token to get.
Returns:
  • The token asset in JSON format.
Return Value Example:
{
    "metadata": {
        "painting_name": "Mona_Lisa",
        "description": "Mona Lisa Painting",
        "image": "monalisa.jpeg",
        "painter_name": "Leonardo_da_Vinci"
    },
    "assetType": "otoken",
    "tokenId": "monalisa",
    "tokenName": "artcollection",
    "tokenDesc": "token description",
    "symbol": "ART",
    "tokenStandard": "erc721+",
    "tokenType": "nonfungible",
    "tokenUnit": "whole",
    "behaviors": [
        "indivisible",
        "singleton",
        "mintable",
        "transferable",
        "burnable",
        "roles"
    ],
    "roles": {
        "minter_role_name": "minter"
    },
    "mintable": {
        "max_mint_quantity": 20000
    },
    "owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "transferredBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "creationDate": "2022-04-05T08:30:42.000Z",
    "transferredDate": "2022-04-05T09:28:30.000Z",
    "isBurned": false,
    "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
    "price": 100,
    "on_sale_flag": true
}
getTokenHistory
This method returns the history for a specified token ID. This is an asynchronous method. This method can only be called when connected to the remote Oracle Blockchain Platform network. Anyone can call this method.
@GetMethod()
@Validator(yup.string())
public async getTokenHistory(tokenId: string) {
   // await this.Ctx.ERC721Auth.checkAuthorization('ERC721TOKEN.history', 'TOKEN');
   return await this.Ctx.ERC721Token.history(tokenId);
}
Parameters:
  • tokenId: string – The ID of the token.
Return Value Example:
[
    {
        "trxId": "ca4c07bf04240345de918cbf1f4f3da4b4d0ab044c5b8bea94343e427d9ed4e7",
        "timeStamp": 1649150910,
        "value": {
            "metadata": {
                "painting_name": "Mona_Lisa",
                "description": "Mona Lisa Painting",
                "image": "monalisa.jpeg",
                "painter_name": "Leonardo_da_Vinci"
            },
            "assetType": "otoken",
            "tokenId": "monalisa",
            "tokenName": "artcollection",
            "tokenDesc": "token description",
            "symbol": "ART",
            "tokenStandard": "erc721+",
            "tokenType": "nonfungible",
            "tokenUnit": "whole",
            "behaviors": [
                "indivisible",
                "singleton",
                "mintable",
                "transferable",
                "burnable",
                "roles"
            ],
            "roles": {
                "minter_role_name": "minter"
            },
            "mintable": {
                "max_mint_quantity": 20000
            },
            "owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "transferredBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "creationDate": "2022-04-05T08:30:42.000Z",
            "transferredDate": "2022-04-05T09:28:30.000Z",
            "isBurned": false,
            "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
            "price": 100,
            "on_sale_flag": true
        }
    },
    {
        "trxId": "cfb52ffc8c34c7fd86210fcf8c5f53d9f92a056c45ed3a33671d638020c1f9cb",
        "timeStamp": 1649149545,
        "value": {
            "metadata": {
                "painting_name": "Mona_Lisa",
                "description": "Mona Lisa Painting",
                "image": "monalisa.jpeg",
                "painter_name": "Leonardo_da_Vinci"
            },
            "assetType": "otoken",
            "tokenId": "monalisa",
            "tokenName": "artcollection",
            "tokenDesc": "token description",
            "symbol": "ART",
            "tokenStandard": "erc721+",
            "tokenType": "nonfungible",
            "tokenUnit": "whole",
            "behaviors": [
                "indivisible",
                "singleton",
                "mintable",
                "transferable",
                "burnable",
                "roles"
            ],
            "roles": {
                "minter_role_name": "minter"
            },
            "mintable": {
                "max_mint_quantity": 20000
            },
            "owner": "oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba",
            "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "transferredBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "creationDate": "2022-04-05T08:30:42.000Z",
            "transferredDate": "2022-04-05T09:05:45.000Z",
            "isBurned": false,
            "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
            "price": 100,
            "on_sale_flag": true
        }
    },
    {
        "trxId": "702e61cc8d6d2982521023d0d5f3195900f35e146d6a90ef66daae551e6075d2",
        "timeStamp": 1649147729,
        "value": {
            "metadata": {
                "painting_name": "Mona_Lisa",
                "description": "Mona Lisa Painting",
                "image": "monalisa.jpeg",
                "painter_name": "Leonardo_da_Vinci"
            },
            "assetType": "otoken",
            "tokenId": "monalisa",
            "tokenName": "artcollection",
            "tokenDesc": "token description",
            "symbol": "ART",
            "tokenStandard": "erc721+",
            "tokenType": "nonfungible",
            "tokenUnit": "whole",
            "behaviors": [
                "indivisible",
                "singleton",
                "mintable",
                "transferable",
                "burnable",
                "roles"
            ],
            "roles": {
                "minter_role_name": "minter"
            },
            "mintable": {
                "max_mint_quantity": 20000
            },
            "owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "creationDate": "2022-04-05T08:30:42.000Z",
            "isBurned": false,
            "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
            "price": 100,
            "on_sale_flag": true
        }
    },
    {
        "trxId": "e7747b3001a170f88688620956320e9402e1dd8edad8afb4818a08a34647337c",
        "timeStamp": 1649147442,
        "value": {
            "metadata": {
                "painting_name": "Mona_Lisa",
                "description": "Mona Lisa Painting",
                "image": "monalisa.jpeg",
                "painter_name": "Leonardo_da_Vinci"
            },
            "assetType": "otoken",
            "tokenId": "monalisa",
            "tokenName": "artcollection",
            "tokenDesc": "token description",
            "symbol": "ART",
            "tokenStandard": "erc721+",
            "tokenType": "nonfungible",
            "tokenUnit": "whole",
            "behaviors": [
                "indivisible",
                "singleton",
                "mintable",
                "transferable",
                "burnable",
                "roles"
            ],
            "roles": {
                "minter_role_name": "minter"
            },
            "mintable": {
                "max_mint_quantity": 20000
            },
            "owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "creationDate": "2022-04-05T08:30:42.000Z",
            "isBurned": false,
            "tokenUri": "\"https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg\"",
            "price": 100,
            "on_sale_flag": false
        }
    }
]
getTokenObject
This is a utility method that returns an instance of the token for a specified token ID. This method is used by many of the automatically generated methods to fetch token objects. You can call this method as needed from your custom methods. When you create a tokenized asset or class, update the switch case with the corresponding Token class to return the correct token object. The ochain sync command in Blockchain App Builder automatically creates a switch case when a tokenized asset is created in the specification file. This method has no @Validator() method decorator, which means this method is not directly invokable and can only be called from other methods.
public async getTokenObject<T extends OchainModel<any>>(tokenId: string): Promise<T> {
   if (!tokenId) {
        throw Error('TokenID cannot be null/empty.');
    }
    const token = await this.Ctx.ERC721Token.get(tokenId);
    if (token.tokenName && token.assetType && token.assetType === 'otoken') {
        let tokenAsset;
        switch (token.tokenName) {
           case '<NFT_NAME in lowercase>':
               tokenAsset = new <NFT_NAME>(token, false, true);
               return tokenAsset;
           default:
               throw new Error(`No token exists with ID [${tokenId}]`);
        }
    } else {
        throw new Error(`No token exists with ID [${tokenId}]`);
    }
}
Parameters:
  • tokenId: string – The ID of the token.
ownerOf
This method returns the account ID of the owner of the specified token ID. Anyone can call this method.
@GetMethod()
@Validator(yup.string())
public async ownerOf(tokenId: string) {
   return await this.Ctx.ERC721Token.ownerOf(tokenId);
}
Parameters:
  • tokenId: string – The ID of the token.
Returns:
  • A JSON object of the owner's account ID.
Return Value Example:
{"owner": "oaccount~d6d22c3167e3c6ab9ee5653e1a008c37c20cc47ebb0229ca0aedfafe64c675b8"}
name
This method returns the name of the token class. Anyone can call this method.
@GetMethod()
@Validator()
public async name() {
   return await this.Ctx.ERC721Token.name();
}
Parameters:
  • none
Returns:
  • A JSON object of the token name.
Return Value Example:
{"tokenName": "artcollection"}
symbol
This method returns the symbol of the token class. Anyone can call this method.
@GetMethod()
@Validator()
public async symbol() {
   return await this.Ctx.ERC721Token.symbol();
}
Parameters:
  • none
Returns:
  • A JSON object of the token symbol.
Return Value Example:
{"symbol": "PNT"}
tokenURI
This method returns the URI of a specified token. Anyone can call this method.
@GetMethod()
@Validator(yup.string())
public async tokenURI(tokenId: string) {
   return await this.Ctx.ERC721Token.tokenURI(tokenId);
}
Parameters:
  • tokenId: string – The ID of the token.
Returns:
  • On success, a JSON object of the token URI.
Return Value Example:
{"tokenURI": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\
.ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg"}
totalSupply
This method returns the total number of minted tokens. This method can be called only by a Token Admin of the chaincode.
@GetMethod()
@Validator()
public async totalSupply() {
  await this.Ctx.ERC721Auth.checkAuthorization('ERC721TOKEN.totalSupply', 'TOKEN');
  return await this.Ctx.ERC721Token.totalSupply();
}
Parameters:
  • none
Returns:
  • On success, a JSON object of the token count.
Return Value Example:
{"totalSupply": 3}
totalNetSupply
This method returns the total number of minted tokens minus the number of burned tokens. This method can be called only by a Token Admin of the chaincode.
@GetMethod()
@Validator()
public async totalNetSupply() {
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721TOKEN.totalNetSupply', 'TOKEN');
    return await this.Ctx.ERC721Token.getTotalMintedTokens();
}
Parameters:
  • none
Returns:
  • On success, a JSON object of the token count.
Return Value Example:
{"totalNetSupply": 1}

Methods for Account Management

createAccount
This method creates an account for a specified user and token. An account must be created for any user who will have tokens at any point. Accounts track the number of NFTs a user has. Users must have accounts in the network to complete token-related operations. You can create only one NFT account per user.

An account ID is an alphanumeric set of characters, prefixed with oaccount~ and followed by an SHA-256 hash of the membership service provider ID (orgId) of the user in the current network organization, the user name or email ID (userId) of the instance owner or the user who is logged in to the instance, and the constant string nft. This method can be called only by the Token Admin of the chaincode.

@Validator(yup.string(), yup.string(), yup.string())
public async createAccount(org_id: string, user_id: string, token_type: string) {
  await this.Ctx.Auth.checkAuthorization("ACCOUNT.createAccount", "TOKEN", { org_id });
  return await this.Ctx.Account.createAccount(org_id, user_id, token_type);
}
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
  • tokenType: string – The only supported token type is nonfungible.
Returns:
  • On success, a JSON object of the account that was created. The bapAccountVersion parameter is defined in the account object for internal use.
Return Value Example:
{
    "assetType": "oaccount",
    "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "bapAccountVersion": 0,
    "userId": "admin",
    "orgId": "Org1MSP",
    "tokenType": "nonfungible",
    "noOfNfts": 0
}
balanceOf
This method returns the total number of NFTs that a specified user holds. This method can be called only by a Token Admin of the chaincode or by the account owner.
@GetMethod()
@Validator(yup.string(), yup.string())
 public async balanceOf(orgId: string, userId: string) {
     await this.Ctx.ERC721Auth.checkAuthorization('ERC721ACCOUNT.balanceOf', 'TOKEN', { orgId, userId });
     const accountId = await this.Ctx.ERC721Account.generateAccountId(orgId, userId);
     return await this.Ctx.ERC721Account.balanceOf(accountId);
 }
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • A JSON object of the current NFT count.
Return Value Example:
{"totalNfts": 0}
getAllAccounts
This method returns a list of all accounts. This method can be called only by a Token Admin of the chaincode. This method uses Berkeley DB SQL rich queries and can only be called when connected to the remote Oracle Blockchain Platform network.
@GetMethod()
@Validator()
public async getAllAccounts() {
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721ACCOUNT.getAllAccounts', 'TOKEN');
    return await this.Ctx.ERC721Account.getAllAccounts();
}
Parameters:
  • none
Returns:
  • On success, a JSON array of all accounts.
Return Value Example:
[
    {
        "key": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "valueJson": {
            "assetType": "oaccount",
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 1
        }    
    }
]
getAccountByUser
This method returns account details for a specified user. This method can be called only by a Token Admin of the chaincode or the Account Owner of the account.
@GetMethod()
@Validator(yup.string(), yup.string())
public async getAccountByUser(orgId: string, userId: string) {
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721ACCOUNT.getAccountByUser', 'TOKEN', { orgId, userId });
    return await this.Ctx.ERC721Account.getAccountWithStatusByUser(orgId, userId);
}
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • On success, a JSON account object that includes the following properties:
  • bapAccountVersion – An account object parameter for internal use.
  • status – The current status of the user account.
  • accountId – The ID of the user account.
  • userId – The user name or email ID of the user.
  • orgId – The membership service provider (MSP) ID of the user in the current organization.
  • tokenType – The type of token that the account holds.
  • noOfNfts – The total number of NFTs held by the account.
Return Value Example:
{
  "bapAccountVersion": 0,
  "assetType": "oaccount",
  "status": "active",
  "accountId": "oaccount~cc301bee057f14236a97d434909ec1084970921b008f6baab09c2a0f5f419a9a",
  "userId": "idcqa",
  "orgId": "appdev",
  "tokenType": "nonfungible",
  "noOfNfts": 0
}
getUserByAccountId
This method returns the user details of a specified account. This method can be called by any user.
@GetMethod()
@Validator(yup.string())
public async getUserByAccountId(accountId: string) {
    return await this.Ctx.ERC721Account.getUserByAccountId(accountId);
}
Parameters:
  • accountId: string – The ID of the account.
Returns:
  • On success, a JSON object of the user details (orgId and userId).
Return Value Example:
{
  "userId": "admin",
  "orgId": "Org1MSP"
}
getAccountHistory
This method returns account history for a specified user. This is an asynchronous method. This method can be called only by the Token Admin of the chaincode or by the account owner.
@GetMethod()
@Validator(yup.string(), yup.string())
public async getAccountHistory(orgId: string, userId: string) {
    const accountId = await this.Ctx.ERC721Account.generateAccountId(orgId, userId);
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721ACCOUNT.history', 'TOKEN', { accountId });
    return await this.Ctx.ERC721Account.history(accountId);
}
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • On success, a JSON object of the account history. The bapAccountVersion parameter is defined in the account object for internal use.
Return Value Example:
[
    {
        "trxId": "6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
        "timeStamp": 1649151044,
        "value": {
            "assetType": "oaccount",
            "bapAccountVersion" : 5,
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 1
        }
    },
    {
        "trxId": "a605f1fa62e511c2945fce5437f983a5e70ec814b82520d3ecd2d81e3ecf53a3",
        "timeStamp": 1649151022,
        "value": {
            "assetType": "oaccount",
            "bapAccountVersion" : 4,
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 2
        }
    },
    {
        "trxId": "ca4c07bf04240345de918cbf1f4f3da4b4d0ab044c5b8bea94343e427d9ed4e7",
        "timeStamp": 1649150910,
        "value": {
            "assetType": "oaccount",
            "bapAccountVersion" : 3,
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 1
        }
    },
    {
        "trxId": "cfb52ffc8c34c7fd86210fcf8c5f53d9f92a056c45ed3a33671d638020c1f9cb",
        "timeStamp": 1649149545,
        "value": {
            "assetType": "oaccount",
            "bapAccountVersion" : 2,
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 0
        }
    },
    {
        "trxId": "e7747b3001a170f88688620956320e9402e1dd8edad8afb4818a08a34647337c",
        "timeStamp": 1649147442,
        "value": {
            "assetType": "oaccount",
            "bapAccountVersion" : 1,
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 1
        }
    },
    {
        "trxId": "d2d1f9c898707ae831e9361bc25da6369eac37b10c87dc04d18d6f3808222f08",
        "timeStamp": 1649137534,
        "value": {
            "assetType": "oaccount",
            "bapAccountVersion" : 0,
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 0
        }
    }
]

Methods for Role Management

addRole
This method adds a role to a specified user. This method can be called only by a Token Admin of the chaincode.
@Validator(yup.string(), yup.string(), yup.string())
public async addRole(role: string, orgId: string, userId: string) {
   const accountId = await this.Ctx.ERC721Account.generateAccountId(orgId, userId);
   await this.Ctx.ERC721Auth.checkAuthorization('ERC721TOKEN.addRoleMember', 'TOKEN');
   return await this.Ctx.ERC721Token.addRoleMember(role, accountId);
}
Parameters:
  • role: string – The name of the role to add to the specified user. The mintable and burnable behaviors correspond to the minter_role_name and burner_role_name properties of the specification file.
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • On success, a message with account details.
Return Value Example:
{"msg": "Successfully added role 'minter' to Account Id: oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d (Org-Id: Org1MSP, User-Id: admin)"}
removeRole
This method removes a role from a specified user. This method can be called only by a Token Admin of the chaincode.
@Validator(yup.string(), yup.string(), yup.string())
public async removeRole(role: string, orgId: string, userId: string) {
    const accountId = await this.Ctx.ERC721Account.generateAccountId(orgId, userId);
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721TOKEN.removeRoleMember', 'TOKEN');
    return await this.Ctx.ERC721Token.removeRoleMember(role, accountId);
}
Parameters:
  • role: string – The name of the role to remove from the specified user. The mintable and burnable behaviors correspond to the minter_role_name and burner_role_name properties of the specification file.
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • On success, a message with account details.
Return Value Example:
{"msg": "Successfully removed role 'minter' from Account Id: oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba (Org-Id: Org1MSP, User-Id: user1)"}
getAccountsByRole
This method returns a list of all account IDs for a specified role. This method can be called only by a Token Admin of the chaincode.
@GetMethod()
@Validator(yup.string())
public async getAccountsByRole(role: string) {
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721ROLE.getAccountsByRole', 'TOKEN');
    return await this.Ctx.ERC721Role.getAccountsByRole(role);
}
Parameters:
  • role: string – The name of the role to search for.
Returns:
  • On success, a JSON array of account IDs.
Return Value Example:
{
    "accounts": [
        "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d"
    ]
}
getUsersByRole
This method returns a list of all users for a specified role. This method can be called only by a Token Admin of the chaincode.
@GetMethod()
@Validator(yup.string())
public async getUsersByRole(role: string) {
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721ROLE.getUsersByRole', 'TOKEN');
    return await this.Ctx.ERC721Role.getUsersByRole(role);
}
Parameters:
  • role: string – The name of the role to search for.
Returns:
  • On success, a JSON array of the user objects (orgId and userId).
Return Value Example:
{
    "users": [
        {
            "userId": "admin",
            "orgId": "Org1MSP"
        }
    ]
}
isInRole
This method returns a Boolean value to indicate if a user has a specified role. This method can be called only by a Token Admin of the chaincode or the Account Owner of the account.
@GetMethod()
@Validator(yup.string(), yup.string(), yup.string())
public async isInRole(orgId: string, userId: string, role: string) {
    const accountId = await this.Ctx.ERC721Account.generateAccountId(orgId, userId);
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721TOKEN.isInRole', 'TOKEN',{ accountId });
    return { result: await this.Ctx.ERC721Token.isInRole(role, accountId) };
}
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
  • role: string – The name of the role to search for.
Returns:
  • On success, a JSON string of the Boolean result.
Return Value Example:
{"result":"true"}

Methods for Transaction History Management

getAccountTransactionHistory
This method returns account transaction history for a specified user. This is an asynchronous method. This method can be called only by the Token Admin of the chaincode or by the account owner.
@GetMethod()
@Validator(yup.string(), yup.string())
public async getAccountTransactionHistory(orgId: string, userId: string) {
    const accountId = await this.Ctx.ERC721Account.generateAccountId(orgId, userId);
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721ACCOUNT.getAccountTransactionHistory', 'TOKEN', { accountId });
    return await this.Ctx.ERC721Account.getAccountTransactionHistory(accountId)
}
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Return Value Example:
[
    {
        "transactionId": "otransaction~6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
        "timestamp": "2022-04-05T09:30:44.000Z",
        "tokenId": "monalisa1",
        "noOfNfts": 1,
        "transactedAccount": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "transactionType": "BURN"
    },
    {
        "transactionId": "otransaction~a605f1fa62e511c2945fce5437f983a5e70ec814b82520d3ecd2d81e3ecf53a3",
        "timestamp": "2022-04-05T09:30:22.000Z",
        "tokenId": "monalisa1",
        "transactedAccount": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "transactionType": "MINT"
    },
    {
        "transactionId": "otransaction~ca4c07bf04240345de918cbf1f4f3da4b4d0ab044c5b8bea94343e427d9ed4e7",
        "timestamp": "2022-04-05T09:28:30.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba",
        "transactionType": "CREDIT"
    },
    {
        "transactionId": "otransaction~cfb52ffc8c34c7fd86210fcf8c5f53d9f92a056c45ed3a33671d638020c1f9cb",
        "timestamp": "2022-04-05T09:05:45.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba",
        "transactionType": "DEBIT"
    },
    {
        "transactionId": "otransaction~e7747b3001a170f88688620956320e9402e1dd8edad8afb4818a08a34647337c",
        "timestamp": "2022-04-05T08:30:42.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "transactionType": "MINT"
    }
]
getAccountTransactionHistoryWithFilters
This method returns account transaction history for a specified user, filtered by PageSize, Bookmark, startTime and endTime. This is an asynchronous method. This method can only be called when connected to the remote Oracle Blockchain Platform network. This method can be called only by the Token Admin of the chaincode or by the account owner.
@GetMethod()
@Validator(yup.string(), yup.string(), yup.object().nullable())
public async getAccountTransactionHistoryWithFilters(orgId: string, userId: string, filters ?: Filters) {
    const accountId = await this.Ctx.ERC721Account.generateAccountId(orgId, userId);
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721ACCOUNT.getAccountTransactionHistoryWithFilters', 'TOKEN', { accountId });
    return await this.Ctx.ERC721Account.getAccountTransactionHistoryWithFilters(accountId, filters)
}
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
  • filters: object – An object of the Filter class that contains four attributes: pageSize, bookmark, startTime and endTime.
Return Value Example:
[
    {
        "transactionId": "otransaction~6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
        "timestamp": "2022-04-05T09:30:44.000Z",
        "tokenId": "monalisa1",
        "transactedAccount": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "transactionType": "BURN"
    },
    {
        "transactionId": "otransaction~a605f1fa62e511c2945fce5437f983a5e70ec814b82520d3ecd2d81e3ecf53a3",
        "timestamp": "2022-04-05T09:30:22.000Z",
        "tokenId": "monalisa1",
        "transactedAccount": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "transactionType": "MINT"
    },
    {
        "transactionId": "otransaction~ca4c07bf04240345de918cbf1f4f3da4b4d0ab044c5b8bea94343e427d9ed4e7",
        "timestamp": "2022-04-05T09:28:30.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba",
        "transactionType": "CREDIT"
    },
    {
        "transactionId": "otransaction~cfb52ffc8c34c7fd86210fcf8c5f53d9f92a056c45ed3a33671d638020c1f9cb",
        "timestamp": "2022-04-05T09:05:45.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba",
        "transactionType": "DEBIT"
    },
    {
        "transactionId": "otransaction~e7747b3001a170f88688620956320e9402e1dd8edad8afb4818a08a34647337c",
        "timestamp": "2022-04-05T08:30:42.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "transactionType": "MINT"
    }
]
getTransactionById
This method returns transaction history for a specified transaction ID. This is an asynchronous method. This method can be called only by a Token Admin of the chaincode or by the account owner.
@GetMethod()
@Validator(yup.string())
public async getTransactionById(transactionId: string) {
    return await this.Ctx.ERC721Transaction.getTransactionById(transactionId);
}
Parameters:
  • transactionId: string – The id of the transaction, which is the prefix otransaction~ followed by the 64-bit hash in hexadecimal format.
Return Value Example:
{
    "transactionId": "otransaction~6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
    "history": [
        {
            "trxId": "6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
            "timeStamp": 1649151044,
            "value": {
                "assetType": "otransaction",
                "transactionId": "otransaction~6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
                "tokenId": "monalisa1",
                "fromAccountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
                "toAccountId": "",
                "triggeredByAccountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
                "transactionType": "BURN",
                "timestamp": "2022-04-05T09:30:44.000Z",
            }
        }
    ]
}
deleteHistoricalTransactions
This method deletes transactions older than a specified time stamp in the state database. This is an asynchronous method. This method can be called only by a Token Admin of the chaincode.
@Validator(yup.date())
public async deleteHistoricalTransactions(timeToExpiration: Date) {
    await this.Ctx.ERC721Auth.checkAuthorization('ERC721TRANSACTION.deleteTransactions', 'TOKEN');
    return await this.Ctx.ERC721Transaction.deleteTransactions(timeToExpiration);
}
Parameters:
  • timestamp: string – A time stamp. All transactions before the time stamp will be deleted.
Return Value Example:
{
    "msg": "Successfuly deleted transaction older than date: Thu Apr 07 2022 21:18:59 GMT+0000 (Coordinated Universal Time).",
    "transactions": [
        "otransaction~30513757d8b647fffaafac440d743635f5c1b2e41b25ebd6b70b5bbf78a2643f",
        "otransaction~ac0e908c735297941ba58bb208ee61ff4816a1e54c090d68024f82adf743892b"
    ]
}

Methods for Token Behavior Management - Mintable Behavior

create<Token Name>Token
This method creates (mints) an NFT. The asset and associated properties are saved in the state database. The caller of this transaction must have a token account. The caller of this transaction becomes the owner of the NFT. If the token specification file includes the roles section for behaviors and the minter_role_name property for roles, then the caller of the transaction must have the minter role. Otherwise, any caller can mint NFTs.
@Validator(< Token Class >)
public async create< Token Name >Token(tokenAsset: <Token Class>) {
    return await this.Ctx.ERC721Token.createToken(tokenAsset);
}
Parameters:
  • tokenAsset: <Token Class> – The token asset to mint. For more information about the properties of the token asset, see the input specification file.
Returns:
  • On success, a JSON token asset object that includes the following properties:
  • metadata – JSON information that describes the token.
  • createdBy – The account ID of the user who called the transaction to mint the token.
  • creationDate – The time stamp of the transaction.
  • isBurned – A Boolean value that indicates if the NFT identified by tokenId is burned.
  • tokenName – The name of the token.
  • tokenDesc – The description of the token.
  • symbol – The symbol of the token.
  • tokenStandard – The standard of the token.
  • tokenType – The type of token held by this account.
  • tokenUnit – The unit of the token.
  • behaviors – A description of all token behaviors.
  • mintable – A description of the properties of mintable behavior. The max_mint_quantity property specifies the maximum number of NFTs of this token class that can be created.
  • owner – The account ID of the current owner of the token. During the minting process, the caller of this method becomes the owner of the token.
  • tokenUri – The URI of the token.
Return Value Example:
{
    "metadata": {
        "painting_name": "Mona_Lisa",
        "description": "Mona Lisa Painting",
        "image": "monalisa.jpeg",
        "painter_name": "Leonardo_da_Vinci"
    },
    "assetType": "otoken",
    "tokenId": "monalisa",
    "tokenName": "artcollection",
    "tokenDesc": "token description",
    "symbol": "ART",
    "tokenStandard": "erc721+",
    "tokenType": "nonfungible",
    "tokenUnit": "whole",
    "behaviors": [
        "indivisible",
        "singleton",
        "mintable",
        "transferable",
        "burnable",
        "roles"
    ],
    "roles": {
        "minter_role_name": "minter"
    },
    "mintable": {
        "max_mint_quantity": 20000
    },
    "owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "creationDate": "2022-04-05T08:30:42.000Z",
    "isBurned": false,
    "tokenUri": "\"https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg\"",
    "price": 100,
    "on_sale_flag": false
}
update<Token Name>Token
This method updates token properties. This method can be called only by the user who is the owner or creator of the token. After a token asset is created, only the token owner can update the token custom properties. If the user is both token owner and creator of a token, they can also update the TokenDesc property. Token metadata cannot be updated. You must pass all token properties to this method, even if you want to update only certain properties.
@Validator(<Token Class>)
public async update<Token name>Token(tokenAsset: <Token Class>) {
    return await this.Ctx.ERC721Token.updateToken(tokenAsset);
}
Parameters:
  • tokenAsset: <Token Class> – The token asset to update. For more information about the properties of the token asset, see the input specification file.
Returns:
  • On success, an updated JSON token asset object
Return Value Example:
{
    "metadata": {
        "painting_name": "Mona_Lisa",
        "description": "Mona Lisa Painting",
        "image": "monalisa.jpeg",
        "painter_name": "Leonardo_da_Vinci"
    },
    "assetType": "otoken",
    "tokenId": "monalisa",
    "tokenName": "artcollection",
    "tokenDesc": "token description",
    "symbol": "ART",
    "tokenStandard": "erc721+",
    "tokenType": "nonfungible",
    "tokenUnit": "whole",
    "behaviors": [
        "indivisible",
        "singleton",
        "mintable",
        "transferable",
        "burnable",
        "roles"
    ],
    "roles": {
        "minter_role_name": "minter"
    },
    "mintable": {
        "max_mint_quantity": 20000
    },
    "owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "creationDate": "2022-04-05T08:30:42.000Z",
    "isBurned": false,
    "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
    "price": 100,
    "on_sale_flag": true
}

Methods for Token Behavior Management - Transferable Behavior

safeTransferFrom
This is an asynchronous function. This method transfers ownership of the specified NFT from the caller to another account. This method includes the following validations:
  • The token exists and is not burned.
  • The sender account and receiver account exist and are not the same account.
  • The sender account owns the token.
  • The caller of the function is the sender.
@Validator(yup.string(), yup.string(), yup.string(), yup.string(), yup.string(), yup.string().max(2000))
public async safeTransferFrom(fromOrgId: string, fromUserId: string, toOrgId: string, toUserId: string, tokenId: string, data?: string) {
    const tokenAsset = await this.getTokenObject(tokenId);
    const fromAccountId = await this.Ctx.ERC721Account.generateAccountId(fromOrgId, fromUserId);
    const toAccountId = await this.Ctx.ERC721Account.generateAccountId(toOrgId, toUserId);
    return await this.Ctx.ERC721Token.safeTransferFrom(fromAccountId, toAccountId, tokenAsset, data);
}
Parameters:
  • fromOrgId: string – The membership service provider (MSP) ID of the sender and token owner in the current organization.
  • fromUserId: string – The user name or email ID of the sender and token owner.
  • toOrgId: string – The membership service provider (MSP) ID of the receiver in the current organization.
  • toUserId: string – The user name or email ID of the receiver.
  • tokenId: string – The ID of the token to transfer.
  • data: string – Optional additional information to store in the transaction record.
Returns:
  • On success, a message with the sender and receiver account details.
Return Value Example:
{"msg": "Successfully transferred NFT token: 'monalisa' from Account-Id: oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d (Org-Id: Org1MSP, User-Id: admin) to Account-Id: oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba (Org-Id: Org1MSP, User-Id: user1)"}
transferFrom
This is an asynchronous function. This method transfers ownership of the specified NFT from a sender account to a receiver account. It is the responsibility of the caller to pass the correct parameters. This method can be called by any user, not only the token owner. This method includes the following validations:
  • The token exists and is not burned.
  • The sender account and receiver account exist and are not the same account.
  • The sender account owns the token.
@Validator(yup.string(), yup.string(), yup.string(), yup.string(), yup.string())
public async transferFrom(fromOrgId: string, fromUserId: string, toOrgId: string, toUserId: string, tokenId: string) {
    const tokenAsset = await this.getTokenObject(tokenId);
    const fromAccountId = await this.Ctx.ERC721Account.generateAccountId(fromOrgId, fromUserId);
    const toAccountId = await this.Ctx.ERC721Account.generateAccountId(toOrgId, toUserId);
    return await this.Ctx.ERC721Token.transferFrom(fromAccountId, toAccountId, tokenAsset);
}
Parameters:
  • fromOrgId: string – The membership service provider (MSP) ID of the sender in the current organization.
  • fromUserId: string – The user name or email ID of the sender.
  • toOrgId: string – The membership service provider (MSP) ID of the receiver in the current organization.
  • toUserId: string – The user name or email ID of the receiver.
  • tokenId: string – The ID of the token to transfer.
Returns:
  • On success, a message with the sender and receiver account details.
Return Value Example:
{"msg": "Successfully transferred NFT token: 'monalisa' from Account-Id: oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba (Org-Id: Org1MSP, User-Id: user1) to Account-Id: oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d (Org-Id: Org1MSP, User-Id: admin)"}

Methods for Token Behavior Management - Burnable Behavior

burn
This method deactivates, or burns, the specified NFT from the caller's account. The caller of this method must have an account. A token cannot be burned unless the token specification file includes the burnable behavior. If no burner_role_name property is specified in the roles section of the specification file, then the owner of the token can burn the token. If a burner_role_name property is specified in the roles section, then the user assigned the burner role who is also the minter (creator) or owner of the token can burn the token.
@Validator(yup.string())
public async burn(tokenId: string) {
    const tokenAsset = await this.getTokenObject(tokenId);
    return await this.Ctx.ERC721Token.burn(tokenAsset);
}
Parameters:
  • tokenId: string – The ID of the token to burn.
Returns:
  • On success, a message with the account details.
Return Value Example:
{"msg": "Successfully burned NFT token: 'monalisa1' from Account-Id: oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d (Org-Id: Org1MSP, User-Id: admin)"}
burnNFT
This method deactivates, or burns, the specified NFT from the caller's account, and returns a token object and token history. The caller of this method must have an account. A token cannot be burned unless the token specification file includes the burnable behavior. If no burner_role_name property is specified in the roles section of the specification file, then the owner of the token can burn the token. If a burner_role_name property is specified in the roles section, then the user assigned the burner role who is also the minter (creator) or owner of the token can burn the token.
@Validator(yup.string())
public async burnNFT(tokenId: string) {
    const token = await this.Ctx.ERC721Token.get(tokenId)
    if (token.isBurned === true) {
      throw new Error(`token with tokenId ${tokenId} is already burned`);
    }
    const tokenHistory = await this.Ctx.ERC721Token.history(tokenId);
    await this.burn(tokenId);
    token.tokenId = parseInt(token.tokenId);
    if(Number.isNaN(token.tokenId)) {
      throw new Error(`tokenId is expected to be integer but found ${tokenId}`)
    }
    token.isBurned = true;
    return {...token, tokenHistory: JSON.stringify(tokenHistory)};
}
Parameters:
  • tokenId: string – The ID of the token to burn.
Returns:
  • On success, a token object that includes token history information.
Return Value Example:
{
    "assetType": "otoken",
    "tokenId": 1,
    "tokenName": "artcollection",
    "symbol": "ART",
    "tokenStandard": "erc721+",
    "tokenType": "nonfungible",
    "tokenUnit": "whole",
    "behaviors": [
        "indivisible",
        "singleton",
        "mintable",
        "transferable",
        "burnable",
        "roles"
    ],
    "roles": {
        "minter_role_name": "minter"
    },
    "mintable": {
        "max_mint_quantity": 20000
    },
    "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "creationDate": "2023-08-22T07:36:50.000Z",
    "owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "isBurned": true,
    "tokenUri": "example.com",
    "price": 120,
    "on_sale_flag": false,
    "tokenHistory": "[{\"trxId\":\"732438a85b5e8fc76c5254e54602b29d583543b103fafb5a28c0df384428bb50\",\"timeStamp\":\"2023-08-22T07:36:50.000Z\",\"value\":{\"assetType\":\"otoken\",\"tokenId\":\"1\",\"tokenName\":\"artcollection\",\"symbol\":\"ART\",\"tokenStandard\":\"erc721+\",\"tokenType\":\"nonfungible\",\"tokenUnit\":\"whole\",\"behaviors\":[\"indivisible\",\"singleton\",\"mintable\",\"transferable\",\"burnable\",\"roles\"],\"roles\":{\"minter_role_name\":\"minter\"},\"mintable\":{\"max_mint_quantity\":20000},\"createdBy\":\"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d\",\"creationDate\":\"2023-08-22T07:36:50.000Z\",\"owner\":\"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d\",\"isBurned\":false,\"tokenUri\":\"example.com\",\"price\":120,\"on_sale_flag\":false}}]"
}

Custom Methods

You can use the token SDK methods to write custom methods for your business application.

The following example shows how to use token SDK methods in custom methods. When the sell method is called, it posts a token for sale for a specified price.

@Validator(yup.string(), yup.number())
public async sell(token_id: string, selling_price: number) {
    try { 
        const token = await this.Ctx.ERC721Token.get(token_id);
        const t = new ArtCollection(token)
 /**  * price is a custom asset
      attribute to set the price of a non-fungible token in the
      marketplace  */
        t.price =  selling_price;
 /**  * on_sale_flag is a
      custom asset attribute that maintains non-fungible token selling status in the
      marketplace  */
        t.on_sale_flag = true;
        await this.Ctx.ERC721Token.updateToken(t);
        let msg = `Token ID : '${token_id}' has been posted for selling in the marketplace'`;
        return {msg}
        } catch(error) {
            throw new Error(error.message);
    }
}

NFT SDK Methods

Methods for Access Control Management

The NFT SDK provides an access control function. Some methods can be called only by a Token Admin or Account Owner of the token. You can use this feature to ensure that operations are carried out only by the intended users. Any unauthorized access results in an error. To use the access control function, import the Authorization class from the ../lib/erc721-auth module.
import { ERC721Authorization } from '../lib/erc721-auth';
checkAuthorization
Use this method to add an access control check to an operation. This is an asynchronous function. Most automatically generated methods include access control. Certain token methods can be run only by the ERC721Admin or Account Owner of the token or by the MultipleAccountOwner for users with multiple accounts. The checkAuthorization method is part of the Authorization class, which you access via the Ctx object. The access control mapping is described in the ../lib/constant.ts file, as shown in the following text. You can modify access control by editing the ../lib/constant.ts file. To use your own access control or to disable access control, remove the access control code from the automatically generated controller methods and custom methods.
export const TOKENACCESS = {
  ADMIN: {
    isUserTokenAdmin: ['Admin', 'MultipleAccountOwner'],
    addAdmin: ['Admin'],
    removeAdmin: ['Admin'],
    getAllAdmins: ['Admin'],
  },
  TOKEN: {
    save: ['Admin'],
    getAllTokens: ['Admin'],
    get: ['Admin'],
    update: ['Admin'],
    getDecimals: ['Admin'],
    getTokensByName: ['Admin'],
    addRoleMember: ['Admin'],
    removeRoleMember: ['Admin'],
    isInRole: ['Admin', 'AccountOwner'],
    getTotalMintedTokens: ['Admin'],
    getNetTokens: ['Admin'],
  },
  ROLE: {
    getAccountsByRole: ['Admin'],
    getUsersByRole: ['Admin'],
  },
  TRANSACTION: {
    deleteTransactions: ['Admin'],
  },
  ACCOUNT: {
    createAccount: ['Admin'],
    getAllAccounts: ['Admin'],
    getAccountsByUser: ['Admin', 'MultipleAccountOwner'],
    getAccount: ['Admin', 'AccountOwner'],
    history: ['Admin', 'AccountOwner'],
    getAccountTransactionHistory: ['Admin', 'AccountOwner'],
    getAccountBalance: ['Admin', 'AccountOwner'],
    getAccountOnHoldBalance: ['Admin', 'AccountOwner'],
    getOnHoldIds: ['Admin', 'AccountOwner'],
  },
  ERC721ADMIN: {
    isUserTokenAdmin: ['Admin'],
    addAdmin: ['Admin'],
    removeAdmin: ['Admin'],
    getAllAdmins: ['Admin'],
  }, 
  ERC721TOKEN: {
    getAllTokens: ['Admin'],
    getAllTokensByUser: ['Admin', 'AccountOwner'],
    get: ['Admin', TOKEN_OWNER],
    getTokensByName: ['Admin'],
    addRoleMember: ['Admin'],
    removeRoleMember: ['Admin'],
    isInRole: ['Admin', 'AccountOwner'],
    totalSupply: ['Admin'],
    totalNetSupply: ['Admin'],
    history: ['Admin'],
  },
  ERC721ROLE: {
    getAccountsByRole: ['Admin'],
    getUsersByRole: ['Admin'],
  },
  ERC721TRANSACTION: {
    deleteTransactions: ['Admin'],
  },
  ERC721ACCOUNT: {
    createAccount: ['Admin'],
    getAllAccounts: ['Admin'],
    getAccountsByUser: ['Admin', 'MultipleAccountOwner'],
    history: ['Admin', 'AccountOwner'],
    getAccountTransactionHistory: ['Admin', 'AccountOwner'],
    getAccountTransactionHistoryWithFilters: ['Admin', 'AccountOwner'],
    balanceOf: ['Admin', 'MultipleAccountOwner'],
  }
}
Ctx.ERC721Auth.checkAuthorization(classFuncName: string, ...args)
Parameters:
  • classFuncName: string – The map value between the class and methods as described in the ../lib/constant.ts file.
  • ...args – A variable argument where args[0] takes the constant 'TOKEN' and args[1] takes the accountId parameter to add an access control check for an AccountOwner. To add an access control check for a MultipleAccountOwner, args[1] takes the orgId parameter and args[2] takes the userId parameter.
Returns:
  • On success, a promise. On error, a rejection with an error message.
Examples:

Admin access

await this.Ctx.ERC721Auth.checkAuthorization('ADMIN.addAdmin', 'TOKEN');

AccountOwner access

await this.Ctx.ERC721Auth.checkAuthorization('ACCOUNT.getAccountBalance', 'TOKEN', accountId);

MultipleAccountOwner access

await this.Ctx.ERC721Auth.checkAuthorization('ADMIN.isUserTokenAdmin', 'TOKEN', orgId, userId);
isUserTokenAdmin
This method returns the Boolean value true if the caller of the function is a Token Admin. Otherwise the method returns false. This is an asynchronous static function.
Ctx.ERC721Auth.isUserTokenAdmin(orgId: string, userId: string)
Parameters:
  • orgId – The membership service provider (MSP) ID of the user in the current network organization.
  • userId – The user name or email ID of the user.
Returns:
  • A Boolean response and an error message if an error is encountered.
Example:

await this.Ctx.Auth.isUserTokenAdmin('Org1MSP', 'user1');

{"result":false}
addAdmin
This method adds a user as a Token Admin of the token chaincode.
Ctx.ERC721Admin.addAdmin(orgId: string, userId: string)
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • On success, a message that lists details for the user added as a Token Admin of the token chaincode. On error, a non-nil error object that contains an error message.
Example:

await this.Ctx.ERC721Admin.addAdmin(orgId, userId)

{"msg": "Successfully added Admin (orgId: Org1MSP, userId: user1)"}
removeAdmin
This method removes a user as a Token Admin of the token chaincode.
Ctx.ERC721Admin.removeAdmin(orgId: string, userId: string)
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • On success, a message that lists details for the user removed as a Token Admin of the token chaincode. On error, a non-nil error object that contains an error message.
Example:

await this.Ctx.ERC721Admin.RemoveAdmin(orgId, userId)

{"msg": "Successfully removed Admin (orgId: Org1MSP, userId: user1)"}
getAllAdmins
This method returns a list of all Token Admin users.
Ctx.ERC721Admin.getAllAdmins()
Parameters:
  • none
Returns:
  • On success, a list of all Token Admin users. On error, a non-nil error object that contains an error message.
Example:

await this.Ctx.ERC721Admin.getAllAdmins()

{
    "admins": [
        {
            "orgId": "Org1MSP",
            "userId": "admin"
        }
    ]
}

Methods for Token Configuration Management

The token configuration management methods are based on the ERC-721 standard. To use the token configuration management methods, import the Token class from the ../lib/erc721-token module.

totalSupply
This method returns the total number of minted NFTs. This is an asynchronous function.
Ctx.ERC721Token.totalSupply()
Parameters:
  • none
Returns:
  • On success, the total net tokens, in the number data type. On error, it returns with an error message.
Example:

await this.Ctx.ERC721Token.totalSupply(tokenAsset);

2000
get
This method returns the specified token object if it is present in the state database. This is an asynchronous static function.
Ctx.ERC721Token.get(tokenId: string)
Parameters:
  • tokenId: string – The ID of the token.
Returns:
  • On success, a promise that includes a JSON object of the token asset. On error, a rejection with an error message
Example:

await this.Ctx.ERC721Token.get(tokenId);

{
    "metadata": {
        "painting_name": "Mona_Lisa",
        "description": "Mona Lisa Painting",
        "image": "monalisa.jpeg",
        "painter_name": "Leonardo_da_Vinci"
    },
    "assetType": "otoken",
    "tokenId": "monalisa",
    "tokenName": "artcollection",
    "tokenDesc": "token description",
    "symbol": "ART",
    "tokenStandard": "erc721+",
    "tokenType": "nonfungible",
    "tokenUnit": "whole",
    "behaviors": [
        "indivisible",
        "singleton",
        "mintable",
        "transferable",
        "burnable",
        "roles"
    ],
    "roles": {
        "minter_role_name": "minter"
    },
    "mintable": {
        "max_mint_quantity": 20000
    },
    "owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "transferredBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "creationDate": "2022-04-05T08:30:42.000Z",
    "transferredDate": "2022-04-05T09:28:30.000Z",
    "isBurned": false,
    "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
    "price": 100,
    "on_sale_flag": true
}
isTokenType
This method indicates whether a token asset exists with the specified ID. This is an asynchronous static function.
Ctx.ERC721Token.isTokenType(tokenId: string)
Parameters:
  • tokenId: string – The ID of the token.
Returns:
  • On success, a promise with true if a token asset exists with the specified ID. On error, a rejection with an error message.
Example:

await this.Ctx.ERC721Token.isTokenType(tokenId);

true
createToken
This method creates a token and saves its properties in the state database. This method can be called only by users with the minter role. This is an asynchronous function.
Ctx.ERC721Token.createToken(token: <Instance of Token Class>)
Parameters:
  • token: <Instance of Token Class> – The token asset to create.
Returns:
  • On success, a promise message with token details. On error, a rejection with an error message.
Example:

await this.Ctx.ERC721Token.createToken(tokenAsset);

{
    "metadata": {
        "painting_name": "Mona_Lisa",
        "description": "Mona Lisa Painting",
        "image": "monalisa.jpeg",
        "painter_name": "Leonardo_da_Vinci"
    },
    "assetType": "otoken",
    "tokenId": "monalisa",
    "tokenName": "artcollection",
    "tokenDesc": "token description",
    "symbol": "ART",
    "tokenStandard": "erc721+",
    "tokenType": "nonfungible",
    "tokenUnit": "whole",
    "behaviors": [
        "indivisible",
        "singleton",
        "mintable",
        "transferable",
        "burnable",
        "roles"
    ],
    "roles": {
        "minter_role_name": "minter"
    },
    "mintable": {
        "max_mint_quantity": 20000
    },
    "owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "creationDate": "2022-04-05T08:30:42.000Z",
    "isBurned": false,
    "tokenUri": "\"https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg\"",
    "price": 100,
    "on_sale_flag": false
}
updateToken
This method updates token properties. This method can be called only by the owner or creator of the token. After a token asset is created, only the token owner can update the token custom properties. If the user is both token owner and creator of a token, they can also update the TokenDesc property. Token metadata cannot be updated. You must pass all token properties to this method, even if you want to update only certain properties. This is an asynchronous function.
Ctx.ERC721Token.updateToken(token: <Instance of Token Class>)
Parameters:
  • token: <Instance of Token Class> – The token asset to update.
Returns:
  • On success, a promise message with token details. On error, a rejection with an error message.
Example:

await this.Ctx.ERC721Token.updateToken(tokenAsset)

{
    "metadata": {
        "painting_name": "Mona_Lisa",
        "description": "Mona Lisa Painting",
        "image": "monalisa.jpeg",
        "painter_name": "Leonardo_da_Vinci"
    },
    "assetType": "otoken",
    "tokenId": "monalisa",
    "tokenName": "artcollection",
    "tokenDesc": "token description",
    "symbol": "ART",
    "tokenStandard": "erc721+",
    "tokenType": "nonfungible",
    "tokenUnit": "whole",
    "behaviors": [
        "indivisible",
        "singleton",
        "mintable",
        "transferable",
        "burnable",
        "roles"
    ],
    "roles": {
        "minter_role_name": "minter"
    },
    "mintable": {
        "max_mint_quantity": 20000
    },
    "owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "createdBy": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "creationDate": "2022-04-05T08:30:42.000Z",
    "isBurned": false,
    "tokenUri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
    "price": 100,
    "on_sale_flag": true
}
getByRange
This method calls the fabric getStateByRange method internally. Even though any asset with the given ID is returned from the ledger, this method casts the asset into the caller Asset type. This is an asynchronous static function.
@validator(yup.string(), yup.string())
public async getDigiCurrGetByRange(startId: string, endId: string) {
   return await this.Ctx.ERC721TOken.getByRange(startId, endId, PaintingNft);
}
Ctx.ERC721Token.getByRange(startId: string, endId: string, tokenClassReference?: <Instance of Token Class> )
Parameters:
  • startId: string – The starting key of the range. This key is included in the range.
  • endId: string – The end key of the range. This key is excluded from the range.
  • tokenClassReference: <Instance of Token Class> – The token asset to operate on.
Returns:
  • On success, a promise with an array of <Token Class>. On error, a rejection with an error message.
Return Value Example:
[
  {
      "metadata":{
         "painting_name":"Mona_Lisa",
         "description":"Mona Lisa Painting",
         "image":"monalisa.jpeg",
         "painter_name":"Leonardo_da_Vinci"
      },
      "assetType":"otoken",
      "tokenId":"monalisa",
      "tokenName":"artcollection",
      "tokenDesc":"token description",
      "symbol":"ART",
      "tokenStandard":"erc721+",
      "tokenType":"nonfungible",
      "tokenUnit":"whole",
      "behaviors":[
         "indivisible",
         "singleton",
         "mintable",
         "transferable",
         "burnable",
         "roles"
      ],
      "roles":{
         "minter_role_name":"minter"
      },
      "mintable":{
         "max_mint_quantity":20000
      },
      "owner":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
      "createdBy":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
      "transferredBy":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
      "creationDate":"2022-04-05T08:30:42.000Z",
      "transferredDate":"2022-04-05T09:28:30.000Z",
      "isBurned":false,
      "tokenUri":"https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
      "price":100,
      "on_sale_flag":true
   }
]
history
This method returns history for the specified token. This is an asynchronous static function.
Ctx.ERC721Token.history(tokenId: string)
Parameters:
  • tokenId: string – The ID of the token.
Returns:
  • On success, a promise history query iterator for the specified token. On error, a rejection with an error message.
Return Value Example:
[
   {
      "trxId":"e17a3154d5271be0492cbc7c12390b3480fec5a792d1cb1083e5335de56ebbd9",
      "timeStamp":1622614032,
      "isDelete":false,
      "value":{
         "metadata":{
            "painting_name":"Mona_Lisa",
            "description":"Mona Lisa Painting",
            "image":"monalisa.jpeg",
            "painter_name":"Leonardo_da_Vinci"
         },
         "assetType":"otoken",
         "tokenId":"monalisa",
         "tokenName":"artcollection",
         "tokenDesc":"token description",
         "symbol":"ART",
         "tokenStandard":"erc721+",
         "tokenType":"nonfungible",
         "tokenUnit":"whole",
         "behaviors":[
            "indivisible",
            "singleton",
            "mintable",
            "transferable",
            "burnable",
            "roles"
         ],
         "roles":{
            "minter_role_name":"minter"
         },
         "mintable":{
            "max_mint_quantity":20000
         },
         "owner":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
         "createdBy":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
         "creationDate":"2022-04-05T08:30:42.000Z",
         "isBurned":false,
         "tokenUri":"https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
         "price":100,
         "on_sale_flag":"true"
      }
   },
   {
      "trxId":"dbcc4da410ad4d4a80996f090b313240f3f3d08aa2b5086afa8d0921f7b4c1e5",
      "timeStamp":1622643853,
      "isDelete":false,
      "value":{
         "metadata":{
            "painting_name":"Mona_Lisa",
            "description":"Mona Lisa Painting",
            "image":"monalisa.jpeg",
            "painter_name":"Leonardo_da_Vinci"
         },
         "assetType":"otoken",
         "tokenId":"monalisa",
         "tokenName":"artcollection",
         "tokenDesc":"token description",
         "symbol":"ART",
         "tokenStandard":"erc721+",
         "tokenType":"nonfungible",
         "tokenUnit":"whole",
         "behaviors":[
            "indivisible",
            "singleton",
            "mintable",
            "transferable",
            "burnable",
            "roles"
         ],
         "roles":{
            "minter_role_name":"minter"
         },
         "mintable":{
            "max_mint_quantity":20000
         },
         "owner":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
         "createdBy":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
         "transferredBy":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
         "creationDate":"2022-04-05T08:30:42.000Z",
         "transferredDate":"2022-04-05T09:28:30.000Z",
         "isBurned":false,
         "tokenUri":"https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg",
         "price":100,
         "on_sale_flag":true
      }
   }
]
getAllTokens
This method returns all of the token assets that are saved in the state database. This method uses Berkeley DB SQL rich queries and can only be called when connected to the remote Oracle Blockchain Platform network. This is an asynchronous static function.
Ctx.ERC721Token.getAllTokens()
Parameters:
  • none
Returns:
  • On success, a promise with all of the token assets. On error, a rejection with an error message.
Example:

await this.Ctx.ERC721Token.getAllTokens();

{
   "returnCode":"Success",
   "error":"",
   "result":{
      "txid":"98e0a0a115803d25b843d630e6b23c435a192a03eb0a301fc9375f05da49a8b2",
      "payload":[
         "           "{
            "metadata":{
               "painting_name":"Mona_Lisa",
               "description":"Mona Lisa Painting",
               "image":"monalisa.jpeg",
               "painter_name":"Leonardo_da_Vinci"
            },
            "assetType":"otoken",
            "tokenId":"monalisa",
            "tokenName":"artcollection",
            "tokenDesc":"token description",
            "symbol":"ART",
            "tokenStandard":"erc721+",
            "tokenType":"nonfungible",
            "tokenUnit":"whole",
            "behaviors":[
               "indivisible",
               "singleton",
               "mintable",
               "transferable",
               "burnable",
               "roles"
            ],
            "roles":{
               "minter_role_name":"minter"
            },
            "mintable":{
               "max_mint_quantity":20000
            },
            "owner":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "createdBy":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "creationDate":"2022-04-05T08:30:42.000Z",
            "isBurned":false,
            "tokenUri":"\"https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg\"",
            "price":100,
            "on_sale_flag":false
         }"       "
      ],
      "encode":"JSON"
   }
}
getAllTokensByUser
This method returns all tokens that are owned by a specified account ID. This is an asynchronous static function.
Ctx.ERC721Token.getAllTokensByUser(accountId: string)
Parameters:
  • accountId: string – The ID of the account.
Returns:
  • On success, a promise history query iterator for the specified account. On error, a rejection with an error message.
Return Value Example:
{
   "returnCode":"Success",
   "error":"",
   "result":{
      "txid":"98e0a0a115803d25b843d630e6b23c435a192a03eb0a301fc9375f05da49a8b2",
      "payload":[
         "           "{
            "metadata":{
               "painting_name":"Mona_Lisa",
               "description":"Mona Lisa Painting",
               "image":"monalisa.jpeg",
               "painter_name":"Leonardo_da_Vinci"
            },
            "assetType":"otoken",
            "tokenId":"monalisa",
            "tokenName":"artcollection",
            "tokenDesc":"token description",
            "symbol":"ART",
            "tokenStandard":"erc721+",
            "tokenType":"nonfungible",
            "tokenUnit":"whole",
            "behaviors":[
               "indivisible",
               "singleton",
               "mintable",
               "transferable",
               "burnable",
               "roles"
            ],
            "roles":{
               "minter_role_name":"minter"
            },
            "mintable":{
               "max_mint_quantity":20000
            },
            "owner":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "createdBy":"oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "creationDate":"2022-04-05T08:30:42.000Z",
            "isBurned":false,
            "tokenUri":"\"https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg\"",
            "price":100,
            "on_sale_flag":false
         }"       "
      ],
      "encode":"JSON"
   }
ownerOf
This method returns the account ID of the owner of a specified token. This is an asynchronous static function.
Ctx.ERC721Token.ownerOf(tokenId: string)
Parameters:
  • tokenId: string – The ID of the token.
Returns:
  • On success, it returns a promise history query iterator for the specified token ID. On error, it rejects with an error message
Return Value Example:
{"owner": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d"}
tokenUri
This method returns the URI for a specified token. This is an asynchronous static function.
Ctx.ERC721Token.tokenUri(tokenId: string)
Parameters:
  • tokenId: string – The ID of the token.
Returns:
  • On success, it returns a promise history query iterator for the specified token ID. On error, it rejects with an error message
Return Value Example:
{"uri": "https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg"}
getTokenUri
This method returns the URI for a specified token. This is an asynchronous static function.
Ctx.ERC721Token.getTokenUri(tokenId: string)
Parameters:
  • tokenId: string – The ID of the token.
Returns:
  • On success, it returns a promise history query iterator for the specified token ID. On error, it rejects with an error message
Return Value Example:
{"tokenUri": https://bafybeid6pmpp62bongoip5iy2skosvyxh3gr7r2e35x3ctvawjco6ddmsq\\ .ipfs.infura-ipfs.io/?filename=MonaLisa.jpeg"}
symbol
This method returns the symbol of the token class.
Ctx.ERC721Token.symbol()
Parameters:
  • none
Returns:
  • On success, a JSON object with the token symbol.
Return Value Example:
{"symbol": "PNT"}

Methods for Account Management

generateAccountId
This method returns an account ID, which is formed by concatenating the membership service provider ID (orgId) and the user name or email ID (userId) and then creating a SHA-256 hash.
Ctx.ERC721Account.generateAccountId(orgId: string, userId: string)
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
Returns:
  • On success, a promise with the generated account ID. On error, a rejection with an error message.
Example:

await this.Ctx.ERC721Account.generateAccountId(orgId, userId)

oaccount~a0a60d54ba9e2ff349737d292ea10ebd9cc8f1991c11443c19d20aea299a9507
createAccount
This method creates an account for a specified user and token. An account must be created for any user who will have tokens at any point. Accounts track the number of NFTs a user has. Users must have accounts in the network to complete token-related operations. You can create only one NFT account per user.

An account ID is an alphanumeric set of characters, prefixed with oaccount~ and followed by an SHA-256 hash of the membership service provider ID (orgId) of the user in the current network organization, the user name or email ID (userId) of the instance owner or the user who is logged in to the instance, and the constant string nft. This method can be called only by the Token Admin of the chaincode.

Ctx.ERC721Account.createAccount(orgId: string, userId: string, tokenType: string)
Parameters:
  • orgId: string – The membership service provider (MSP) ID of the user in the current organization.
  • userId: string – The user name or email ID of the user.
  • tokenType: string – The only supported token type is nonfungible.
Returns:
  • On success, a promise with the new account object. On error, a rejection with an error message
Example:

await this.Ctx.ERC721Account.CreateAccount(orgId, userId, tokenType)

{
    "assetType": "oaccount",
    "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "userId": "admin",
    "orgId": "Org1MSP",
    "tokenType": "nonfungible",
    "noOfNfts": 0
}
getAllAccounts
This method returns a list of all accounts. This method uses Berkeley DB SQL rich queries and can only be called when connected to the remote Oracle Blockchain Platform network.
Ctx.ERC721Account.getAllAccounts()
Parameters:
  • none
Returns:
  • On success, a promise with a JSON object that lists all accounts. On error, a rejection with an error message.
Return Value Example:
[
    {
        "key": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "valueJson": {
            "assetType": "oaccount",
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 1
        }   
    }
]
history
This method returns an array of the account history details for a specified account.
Ctx.ERC721Account.history(accountId: string)
Parameters:
  • accountId: string – The ID of the account.
Returns:
  • On success, a map[string]interface{} array that contains the account history details for the specified account. The account data is shown under the value key in the map. On error, a non-nil error object containing an error message.
Example:

await this.Ctx.ERC721Account.history(accountId)

[
    {
        "trxId": "6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
        "timeStamp": 1649151044,
        "value": {
            "assetType": "oaccount",
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 1
        }
    },
    {
        "trxId": "a605f1fa62e511c2945fce5437f983a5e70ec814b82520d3ecd2d81e3ecf53a3",
        "timeStamp": 1649151022,
        "value": {
            "assetType": "oaccount",
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 2
        }
    },
    {
        "trxId": "ca4c07bf04240345de918cbf1f4f3da4b4d0ab044c5b8bea94343e427d9ed4e7",
        "timeStamp": 1649150910,
        "value": {
            "assetType": "oaccount",
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 1
        }
    },
    {
        "trxId": "cfb52ffc8c34c7fd86210fcf8c5f53d9f92a056c45ed3a33671d638020c1f9cb",
        "timeStamp": 1649149545,
        "value": {
            "assetType": "oaccount",
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 0
        }
    },
    {
        "trxId": "e7747b3001a170f88688620956320e9402e1dd8edad8afb4818a08a34647337c",
        "timeStamp": 1649147442,
        "value": {
            "assetType": "oaccount",
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 1
        }
    },
    {
        "trxId": "d2d1f9c898707ae831e9361bc25da6369eac37b10c87dc04d18d6f3808222f08",
        "timeStamp": 1649137534,
        "value": {
            "assetType": "oaccount",
            "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
            "userId": "admin",
            "orgId": "Org1MSP",
            "tokenType": "nonfungible",
            "noOfNfts": 0
        }
    }
]
getUserByAccountId
This method returns the user details for a specified account.
Ctx.ERC721Account.getUserByAccountId(accountId: string)
Parameters:
  • accountId: string – The ID of the account.
Returns:
  • On success, a JSON object that includes user details in the following properties:
    • orgId – The membership service provider (MSP) ID of the user in the current network organization.
    • userId – The user name or email ID of the user.
  • On error, a rejection with an error message.
Example:

await this.Ctx.ERC721Account.getUserByAccountById(accountId)

{
  "userId": "admin",
  "orgId": "Org1MSP"
}
getAccountWithStatusByUser
This method returns user details for a specified account, including account status. This method can be called only by a Token Admin of the chaincode or the Account Owner of the account.
Ctx.ERC721Account.getAccountWithStatusByUser(orgId, userId)
Parameters:
  • orgId – The membership service provider (MSP) ID of the user in the current organization.
  • userId – The user name or email ID of the user.
Returns:
  • On success, a JSON account object that includes the following properties:
  • accountId – The ID of the user account.
  • userId – The user name or email ID of the user.
  • orgId – The membership service provider (MSP) ID of the user in the current organization.
  • tokenType – The type of token that the account holds.
  • noOfNfts – The total number of NFTs held by the account.
  • bapAccountVersion – An account object parameter for internal use.
  • status – The current status of the user account.
  • On error, a non-nil object that contains an error message.
Example:

await this.Ctx.ERC721Account.getAccountWithStatusByUser(orgId, userId)

{
  "bapAccountVersion": 0,
  "assetType": "oaccount",
  "status": "active",
  "accountId": "oaccount~cc301bee057f14236a97d434909ec1084970921b008f6baab09c2a0f5f419a9a",
  "userId": "idcqa",
  "orgId": "appdev",
  "tokenType": "nonfungible",
  "noOfNfts": 0
}
getAccountByUser
This method returns user details for a specified account. This method can be called only by a Token Admin of the chaincode or the Account Owner of the account.
Ctx.ERC721Account.getAccountByUser(orgId, userId)
Parameters:
  • orgId – The membership service provider (MSP) ID of the user in the current organization.
  • userId – The user name or email ID of the user.
Returns:
  • On success, a JSON account object that includes the following properties:
  • accountId – The ID of the user account.
  • userId – The user name or email ID of the user.
  • orgId – The membership service provider (MSP) ID of the user in the current organization.
  • tokenType – The type of token that the account holds.
  • noOfNfts – The total number of NFTs held by the account.
  • On error, a non-nil object that contains an error message.
Example:

await this.Ctx.ERC721Account.getUserByAccountById(orgId, userId)

{
    "assetType": "oaccount",
    "accountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
    "userId": "admin",
    "orgId": "Org1MSP",
    "tokenType": "nonfungible",
    "noOfNfts": 0
}
balanceOf
This method returns the total number of NFTs the specified user holds.
Ctx.ERC721Account.balanceOf(accountId: string)
Parameters:
  • accountId: string – The account ID of the user.
Returns:
  • On success, a JSON object of the current NFT count. On error, a non-nil error object that contains an error message.
Example:

await this.Ctx.ERC721Account.balanceOf(accountId)

{"totalNfts": 0}

Methods for Role Management

addRoleMember
This method adds a role to a specified user and token. An account ID is formed by creating an SHA-256 hash of the concatenated membership service provider ID (orgId) and the user name or email ID (userId). This is an asynchronous function.
Ctx.ERC721Token.addRoleMember(role: string, accountId: string)
Parameters:
  • role: string – The name of the role to add to the specified user. The mintable and burnable behaviors correspond to the minter_role_name and burner_role_name properties of the specification file.
  • accountId: string – The account ID to operate on.
Returns:
  • On success, a promise with a message including the added role and account ID. On error, a rejection with an error message
Example:

await this.Ctx.ERC721Token.addRoleMember(role, accountId);

{"msg": "Successfully added role 'minter' to Account Id: oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d (Org-Id: Org1MSP, User-Id: admin)"}
removeRoleMember
This method removes a role from a specified user and token. An account ID is formed by creating an SHA-256 hash of the concatenated membership service provider ID (orgId) and the user name or email ID (userId). This is an asynchronous function.
Ctx.ERC721Token.removeRoleMember(role: string, accountId: string)
Parameters:
  • role: string – The name of the role to remove from the specified user. The mintable and burnable behaviors correspond to the minter_role_name and burner_role_name properties of the specification file.
  • accountId: string – The account ID to operate on.
Returns:
  • On success, a promise with a message including the removed role and account ID. On error, a rejection with an error message
Example:

await this.Ctx.ERC721Token.removeRoleMember(role, accountId);

{"msg": "Successfully removed role 'minter' from Account Id: oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba (Org-Id: Org1MSP, User-Id: user1)"}
isInRole
This method returns a Boolean value to indicate if a user and token has a specified role. An account ID is formed by creating an SHA-256 hash of the concatenated membership service provider ID (orgId) and the user name or email ID (userId). This is an asynchronous function.
Ctx.ERC721Token.isInRole(role: string, accountId: string)
Parameters:
  • role: string – The name of the role to check for the specified user. The mintable and burnable behaviors correspond to the minter_role_name and burner_role_name properties of the specification file.
  • accountId: string – The account ID to operate on.
Returns:
  • On success, a promise that is true if the role is present for the specified account ID, otherwise false. On error, a rejection with an error message
Example:

await this.Ctx.ERC721Token.isInRole(role, accountId, tokenAsset)

{"result": "true"}
getAccountsByRole
This method returns a list of all account IDs for a specified role.
Ctx.ERC721Role.getAccountsByRole(roleName: string)
Parameters:
  • roleName: string – The name of the role to search for.
Returns:
  • On success, a JSON array of account IDs. On error, a non-nil error object that contains an error message.
Example:

await this.Ctx.ERC721Role.getAccountsByRole(userRole)

{
    "accounts": [
        "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d"
    ]
}
getUsersByRole
This method returns a list of all users for a specified role.
Ctx.ERC721Role.getUsersByRole(userRole: string)
Parameters:
  • role: string – The name of the role to search for.
Returns:
  • On success, a JSON array of user objects. Each object contains the user ID and organization ID. On error, a non-nil error object that contains an error message.
Example:

await this.Ctx.ERC721Role.getUsersByRole(userRole)

{
    "users": [
        {
            "userId": "admin",
            "orgId": "Org1MSP"
        }
    ]
}

Methods for Transaction History Management

getAccountTransactionHistory
This method returns an array of the transaction history details for a specified account.
Ctx.ERC721Account.getAccountTransactionHistory(accountId: string)
Parameters:
  • accountId: string – The ID of the account.
Returns:
  • On success, an array of account transaction objects in JSON format:
    • transactionId – The ID of the transaction.
    • transactedAccount – The account with which the transaction took place.
    • transactionType – The type of transaction.
    • timestamp – The time of the transaction.
    • noOfNfts – The balance of the caller account.
    • On error, a non-nil error object that contains an error message.
Example:

await this.Ctx.ERC721Account.GetAccountTransactionHistory(accountId)

[
    {
        "transactionId": "otransaction~6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
        "timestamp": "2022-04-05T09:30:44.000Z",
        "tokenId": "monalisa1",
        "transactedAccount": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "transactionType": "BURN"
    },
    {
        "transactionId": "otransaction~a605f1fa62e511c2945fce5437f983a5e70ec814b82520d3ecd2d81e3ecf53a3",
        "timestamp": "2022-04-05T09:30:22.000Z",
        "tokenId": "monalisa1",
        "transactedAccount": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "transactionType": "MINT"
    },
    {
        "transactionId": "otransaction~ca4c07bf04240345de918cbf1f4f3da4b4d0ab044c5b8bea94343e427d9ed4e7",
        "timestamp": "2022-04-05T09:28:30.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba",
        "transactionType": "CREDIT"
    },
    {
        "transactionId": "otransaction~cfb52ffc8c34c7fd86210fcf8c5f53d9f92a056c45ed3a33671d638020c1f9cb",
        "timestamp": "2022-04-05T09:05:45.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba",
        "transactionType": "DEBIT"
    },
    {
        "transactionId": "otransaction~e7747b3001a170f88688620956320e9402e1dd8edad8afb4818a08a34647337c",
        "timestamp": "2022-04-05T08:30:42.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "transactionType": "MINT"
    }
]
getAccountTransactionHistoryWithFilters
This method returns account transaction history for a specified user, filtered by PageSize, Bookmark, startTime and endTime. This method can only be called when connected to the remote Oracle Blockchain Platform network.
async getAccountTransactionHistoryWithFilters(orgId: string, userId: string, filters?: Filters)
Parameters:
  • accountId: string – The ID of the account.
  • filters: object – An object of the Filter class that contains four attributes: pageSize, bookmark, startTime and endTime. If empty, all records are returned. The PageSize property determines the number of records to return. If PageSize is 0, the default page size is 20. The Bookmark property determines the starting index of the records to return. For more information, see the Hyperledger Fabric documentation. The StartTime and EndTime properties must be specified in RFC-3339 format.
Returns:
  • On success, an array of account transaction objects in JSON format:
    • transactionId – The ID of the transaction.
    • transactedAccount – The account with which the transaction took place.
    • transactionType – The type of transaction.
    • timestamp – The time of the transaction.
    • noOfNfts – The balance of the caller account.
    • On error, a non-nil error object that contains an error message.
Example:

await this.Ctx.ERC721Account.getAccountTransactionHistoryWithFilters(accountId, filters)

[
    {
        "transactionId": "otransaction~ca4c07bf04240345de918cbf1f4f3da4b4d0ab044c5b8bea94343e427d9ed4e7",
        "timestamp": "2022-04-05T09:28:30.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba",
        "transactionType": "CREDIT"
    },
    {
        "transactionId": "otransaction~cfb52ffc8c34c7fd86210fcf8c5f53d9f92a056c45ed3a33671d638020c1f9cb",
        "timestamp": "2022-04-05T09:05:45.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba",
        "transactionType": "DEBIT"
    },
    {
        "transactionId": "otransaction~e7747b3001a170f88688620956320e9402e1dd8edad8afb4818a08a34647337c",
        "timestamp": "2022-04-05T08:30:42.000Z",
        "tokenId": "monalisa",
        "transactedAccount": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
        "transactionType": "MINT"
    }
]
getTransactionById
This method returns the history of a Transaction asset.
Ctx.ERC721Transaction.getTransactionById(transactionId: string)
Parameters:
  • transactionId: string – The ID of the transaction asset.
Example:

await this.Ctx.ERC721Transaction.getTransactionById(transactionId)

{
    "transactionId": "otransaction~6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
    "history": [
        {
            "trxId": "6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
            "timeStamp": 1649151044,
            "value": {
                "assetType": "otransaction",
                "transactionId": "otransaction~6ffd0d94f234c12444a5d5aa559563b59dff4d2280b573fea956dc632bdaf5d4",
                "tokenId": "monalisa1",
                "fromAccountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
                "toAccountId": "",
                "triggeredByAccountId": "oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d",
                "transactionType": "BURN",
                "timestamp": "2022-04-05T09:30:44.000Z",
            }
        }
    ]
}
deleteHistoricalTransactions
This method deletes transactions that are older than a specified date from the state database.
Ctx.ERC721Transaction.deleteTransactions(timeToExpiration: Date)
Parameters:
  • timeToExpiration: Date – The date and time. Transactions older than the specified time will be deleted.
Example:

await this.Ctx.ERC721Transaction.deleteTransactions(timeToExpiration)

{
    "returnCode": "Success",
    "error": "",
    "result": {
        "txid": "62ad6753cf2bfa54816b4c2f0ea325478b1cb1b84f8e13e6742c00f277310081",
        "payload": {
            "msg": "Successfuly deleted transaction older than date: Fri Apr 08 2022 00:00:00 GMT+0000 (Coordinated Universal Time).",
            "transactions": [
                "otransaction~e687531b71d943da2fb129638784fb93a96e7698013dfc51c8c6bf4f5f797059",
                "otransaction~18446adf59b669e12990a1cf3ea0a7a15764f967fa694cf263aee0cd5a21d952",
                "otransaction~5560d4b5e0b0d0b9a6e97dcd7f81241a5daf56497a7b6819c6a55cebacc106f2",
                "otransaction~f0a0a64ec1a0c92ac732706dd75ffbd3feecd9c48fc79e42c551485edf0542cb"
            ]
        },
        "encode": "JSON"
    }
}

Token Behavior Management - Mintable Behavior

getMaxMintQuantity
This method returns the maximum mintable quantity of a token. If the max_mint_quantity behavior is not configured in the specification file, then the default value is 0 and an infinite number of tokens can be minted.
Ctx.ERC721Token.getMaxMintQuantity(token: <Instance of Token Class>)
Parameters:
  • token: <Instance of Token Class> – The token asset to operate on.
Returns:
  • On success, the maximum mintable quantity of the token, in the number data type. On error, it returns with an error message.
Example:

await this.Ctx.ERC721Token.getMaxMintQuantity(tokenAsset);

20000
getTotalMintedTokens
This method returns the total minted number of tokens available in the system for the specified token. The net number of tokens available is the total number of minted tokens minus the number of burned tokens. This is an asynchronous function.
Ctx.ERC721Token.getTotalMintedTokens()
Parameters:
  • token: <Instance of Token Class> – The token asset to operate on.
Returns:
  • On success, the total minted tokens, in the number data type. On error, it returns with an error message.
Example:

await this.Ctx.ERC721Token.getTotalMintedTokens(tokenAsset);

4000

Token Behavior Management - Transferable Behavior

safeTransferFrom
This is an asynchronous function. This method transfers ownership of the specified NFT from the caller to another account. This method includes the following validations:
  • The token exists and is not burned.
  • The sender account and receiver account exist and are not the same account.
  • The sender account owns the token.
  • The caller of the function is the sender.
Ctx.ERC721Token.safeTransferFrom(fromAccountId: string, toAccountId: string, token: <Instance of Token Class>, data?: string)
Parameters:
  • fromAccountId: string – The account ID of the sender in the current organization.
  • toAccountId: string – The account ID of the receiver in the current organization.
  • token: <Instance of Token Class> – The token asset to transfer.
  • data: string – Optional additional information to store in the transaction.
Returns:
  • On success, a promise with a success message that includes account details. Account IDs have the prefix oaccount~. On error, a rejection with an error message.
Example:

await this.Ctx.ERC721Token.safeTransferFrom(fromAccountId, toAccountId, tokenAsset, data);

{"msg": "Successfully transferred NFT token: 'monalisa' from Account-Id: oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d (Org-Id: Org1MSP, User-Id: admin) to Account-Id: oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba (Org-Id: Org1MSP, User-Id: user1)"}
transferFrom
This is an asynchronous function. This method transfers ownership of the specified NFT from a sender account to a receiver account. It is the responsibility of the caller to pass the correct parameters. This method can be called by any user, not only the token owner. This method includes the following validations:
  • The token exists and is not burned.
  • The sender account and receiver account exist and are not the same account.
  • The sender account owns the token.
Ctx.ERC721Token.transferFrom(fromAccountId: string, toAccountId: string, token: <Instance of Token Class>)
Parameters:
  • fromAccountId: string – The account ID of the sender in the current organization.
  • toAccountId: string – The account ID of the receiver in the current organization.
  • token: <Instance of Token Class> – The token asset to transfer.
Returns:
  • On success, a promise with a success message that includes account details. Account IDs have the prefix oaccount~. On error, a rejection with an error message.
\Example:

await this.Ctx.ERC721Token.transferFrom(fromAccountId, toAccountId, tokeAsset, data);

{"msg": "Successfully transferred NFT token: 'monalisa' from Account-Id: oaccount~ec32cff8635a056f3dda3da70b1d6090d61f66c6a170c4a95fd008181f729dba (Org-Id: Org1MSP, User-Id: user1) to Account-Id: oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d (Org-Id: Org1MSP, User-Id: admin)"}

Token Behavior Management - Burnable Behavior

burn
This method deactivates, or burns, the specified NFT from the caller's account. The caller of this method must have an account. A token cannot be burned unless the token specification file includes the burnable behavior. If no burner_role_name property is specified in the roles section of the specification file, then the owner of the token can burn the token. If a burner_role_name property is specified in the roles section, then the user assigned the burner role who is also the minter (creator) of the token can burn the token. This is an asynchronous function.
Ctx.ERC721Token.burn(token: <Instance of Token Class>)
Parameters:
  • token: <Instance of Token Class> – The token asset to burn.
Returns:
  • On success, a promise with a success message that includes account details. On error, a rejection with an error message.
Example:

await this.Ctx.ERC721Token.burn(tokenAsset);

{msg": "Successfully burned NFT token: 'monalisa1' from Account-Id: oaccount~42e89f4c72dfde9502814876423c6da630d466e87436dd1aae201d347ad1288d (Org-Id: Org1MSP, User-Id: admin)"}