TrustVC is a comprehensive wrapper library designed to simplify the signing and verification processes for TrustVC W3C Verifiable Credentials (VC) and OpenAttestation Verifiable Documents (VD), including OpenCert Verifiable Documents, adhering to the W3C VC Data Model v2.0 (W3C Standard). It ensures compatibility and interoperability for Verifiable Credentials while supporting OpenAttestation Verifiable Documents (VD) v6.9.5. TrustVC seamlessly integrates functionalities for handling W3C Verifiable Credentials and OpenAttestation Verifiable Documents, leveraging existing TradeTrust libraries and smart contracts for Token Registry (V4 and V5). Additionally, it includes essential utility functions for strings, networks, and chains, making it a versatile tool for developers working with decentralized identity and verifiable data solutions.
- TrustVC
Prerequisites:
- Node.js >= 20.0.0
npm install
npm run build
npm run testThis module provides utility functions for wrapping OpenAttestation documents of version 2 (v2) and version 3 (v3). These functions validate the document version and apply the appropriate wrapping logic using the OpenAttestation library. Note that wrapping is not required for W3C-compliant documents, as they follow a different format and standard.
Wraps a single OpenAttestation document asynchronously, supporting both v2 and v3 documents.
document: OpenAttestationDocument The OpenAttestation document to be wrapped.
Promise A promise that resolves to the wrapped document.
Error If the document version is unsupported or if an error occurs during wrapping.
import { wrapOADocument } from '@trustvc/trustvc';
const document = {
/* OpenAttestation document (v2 or v3) */
};
const wrappedDocument = await wrapOADocument(document);
console.log(wrappedDocument);Wraps multiple OpenAttestation documents asynchronously, supporting both v2 and v3 documents.
documents: OpenAttestationDocument[] An array of OpenAttestation documents to be wrapped.
Promise<WrappedDocument[]> A promise that resolves to the array of wrapped documents.
Error If the documents include unsupported versions or if an error occurs during wrapping.
import { wrapOADocuments } from '@trustvc/trustvc';
const documents = [
{
/* doc1 */
},
{
/* doc2 */
},
];
const wrappedDocuments = await wrapOADocuments(documents);
console.log(wrappedDocuments);The TrustVC Signing feature simplifies the signing process for OA documents and W3C-compliant verifiable credentials using ECDSA signature. This feature allows you to easily sign W3C Verifiable Credentials (VCs) and ensure they comply with the latest standards.
The signing functionality is split into two methods:
- signOA: Designed specifically for signing OpenAttestation documents.
- signW3C: Tailored for signing W3C-compliant verifiable credentials.
import { wrapOA, signOA } from '@trustvc/trustvc';
const rawDocument = {
'@context': [
'https://www.w3.org/ns/credentials/v2',
'https://schemata.openattestation.com/com/openattestation/4.0/context.json',
],
type: ['VerifiableCredential', 'OpenAttestationCredential'],
credentialSubject: {
id: '0x1234567890123456789012345678901234567890',
name: 'John Doe',
country: 'SG',
},
issuer: {
id: 'did:ethr:0xB26B4941941C51a4885E5B7D3A1B861E54405f90',
type: 'OpenAttestationIssuer',
name: 'Government Technology Agency of Singapore (GovTech)',
identityProof: { identityProofType: 'DNS-DID', identifier: 'example.openattestation.com' },
},
};
const wrappedDocument = await wrapOA(rawDocument);
const signedWrappedDocument = await signOA(wrappedDocument, {
public: 'did:ethr:0xB26B4941941C51a4885E5B7D3A1B861E54405f90#controller',
private: '<privateKey>',
});The signW3C function signs W3C Verifiable Credentials using the provided cryptographic suite and key pair. By default, it uses the ecdsa-sd-2023 crypto suite unless otherwise specified. It also supports bbs-2023 for modern BBS signatures.
import { signW3C, VerificationType } from '@trustvc/trustvc';
const rawDocument = {
'@context': [
'https://www.w3.org/ns/credentials/v2',
'https://w3id.org/security/data-integrity/v2',
'https://w3id.org/vc/status-list/2021/v1',
'https://w3c-ccg.github.io/citizenship-vocab/contexts/citizenship-v2.jsonld',
],
credentialStatus: {
id: 'https://trustvc.github.io/did/credentials/statuslist/1#1',
type: 'BitstringStatusListEntry',
statusPurpose: 'revocation',
statusListIndex: '10',
statusListCredential: 'https://trustvc.github.io/did/credentials/statuslist/1',
},
credentialSubject: {
type: ['Person']
givenName: 'TrustVC',
birthDate: '2024-04-01T12:19:52Z',
},
issuer: 'did:web:trustvc.github.io:did:1',
type: ['VerifiableCredential'],
validFrom: '2024-04-01T12:19:52Z',
validUntil: '2029-12-03T12:19:52Z'
};
// Using default ecdsa-sd-2023 crypto suite
const signingResult = await signW3C(rawDocument, {
'@context': 'https://w3id.org/security/multikey/v1',
id: 'did:web:trustvc.github.io:did:1#multikey-1',
type: VerificationType.Multikey,
controller: 'did:web:trustvc.github.io:did:1',
publicKeyMultibase: 'zDnaemDNwi4G5eTzGfRooFFu5Kns3be6yfyVNtiaMhWkZbwtc',
secretKeyMultibase: '<secretKeyMultibase>'
});
// You can also specify mandatory pointers for selective disclosure with ecdsa-sd-2023 / bbs-2023
const signingResultWithPointers = await signW3C(
rawDocument,
{
'@context': 'https://w3id.org/security/multikey/v1',
id: 'did:web:trustvc.github.io:did:1#multikey-1',
type: VerificationType.Multikey,
controller: 'did:web:trustvc.github.io:did:1',
publicKeyMultibase: 'zDnaemDNwi4G5eTzGfRooFFu5Kns3be6yfyVNtiaMhWkZbwtc',
secretKeyMultibase: '<secretKeyMultibase>'
},
'ecdsa-sd-2023',
{
mandatoryPointers: ['/credentialStatus']
}
);
// Using BBS-2023 cryptosuite
const signingResultWithBbs2023 = await signW3C(
rawDocument,
{
'@context': 'https://w3id.org/security/multikey/v1',
id: 'did:web:trustvc.github.io:did:1#multikey-2',
type: VerificationType.Multikey,
controller: 'did:web:trustvc.github.io:did:1',
publicKeyMultibase: 'zUC75kRac7BdtjawFUxowfgD6mzqnRHFxAfMDaBynebdYgakviQkPS1KNJEw7uGWqj91H3hSE4pTERb3EZKLgKXjpqHWrN8dyE8SKyPBE3k7kUGjBNAqJoNGgUzqUW3DSaWrcNr',
secretKeyMultibase: '<secretKeyMultibase>',
},
'bbs-2023'
);
// ⚠️ DEPRECATED: BbsBlsSignature2020 is no longer supported
// Use 'ecdsa-sd-2023 or bbs-2023' cryptosuite instead as shown above
const signingResultWithBbs = await signW3C(
rawDocument,
{
id: 'did:web:trustvc.github.io:did:1#keys-1',
controller: 'did:web:trustvc.github.io:did:1',
type: VerificationType.Bls12381G2Key2020,
publicKeyBase58: 'oRfEeWFresvhRtXCkihZbxyoi2JER7gHTJ5psXhHsdCoU1MttRMi3Yp9b9fpjmKh7bMgfWKLESiK2YovRd8KGzJsGuamoAXfqDDVhckxuc9nmsJ84skCSTijKeU4pfAcxeJ',
privateKeyBase58: '<privateKeyBase58>',
},
'BbsBlsSignature2020' // This will return an error
);When using ECDSA-SD-2023 or BBS-2023 crypto suites, we can derive a new credential with selective disclosure. This means you can choose which parts of the credential to reveal while keeping others hidden.
import { deriveW3C } from '@trustvc/trustvc';
// This is a signed document using ecdsa-sd-2023
const signedDocument = {
'@context': [
'https://www.w3.org/ns/credentials/v2',
'https://w3id.org/security/data-integrity/v2',
'https://w3c-ccg.github.io/citizenship-vocab/contexts/citizenship-v2.jsonld'
],
credentialStatus: {
id: 'https://trustvc.github.io/did/credentials/statuslist/1#1',
type: 'BitstringStatusListEntry',
statusPurpose: 'revocation',
statusListIndex: '10',
statusListCredential: 'https://trustvc.github.io/did/credentials/statuslist/1'
},
credentialSubject: {
type: ['Person'],
givenName: 'TrustVC',
birthDate: '2024-04-01T12:19:52Z'
},
issuer: 'did:web:trustvc.github.io:did:1',
type: ['VerifiableCredential'],
validFrom: '2024-04-01T12:19:52Z',
validUntil: '2029-12-03T12:19:52Z',
id: 'urn:uuid:0198e4a3-b601-7117-9d02-8c9a9a54ab5d',
proof: {
type: 'DataIntegrityProof',
created: '2025-08-18T14:38:51Z',
verificationMethod: 'did:web:trustvc.github.io:did:1#multikey-1',
cryptosuite: 'ecdsa-sd-2023',
proofPurpose: 'assertionMethod',
proofValue: 'u2V0AhVhAWvyp4W7vt4DBhJy2JjKdbDjNSjh3mFsIfPv68Xk2uc4PSFf1iiAeq19rvnHou1LW_Ff0MrRxzcmuTsBO54q3vVgjgCQDz9CT1s28B8Wsk-i8hgzexvcOZgInRbK9VpG6pMwSfbNYIA0xoaqSwjMxAISQ2l2uRmBFlIdL3XFduNUlo93wj5EMilhA24fPUQHaYlpN2hezHkI2QbUpUzVdIoRFA9KdzA1JNWM9GuCKWF0A62W91QmN82237JIiF1d2aLq3lnCpgR_Y-VhAdhqKN1MXPH5BNYAmM1rSZLHGF92dYt2k3XLb84UsgBYNx0f5VKOKFKNY-ZNho59RdsSTRNbsUzU-zzH1CLkc-lhAKgI6LHZPLePwB-Vsad2jOO-_PGHoHas5-uNJDDSp-xTO2auFGmpI6OGx-U_xwcKYX3su3qwtYCJ3nf2-l-t5SFhAfNLg1QbwjJBStUFCcVZWzu1wDh1d9owiox2nNm9EDun4DU40ThWLoWJEEGtqJYE0XFeMxCNkGJGvBQkXJxKZYlhAXBhzKu4D8oXuUHymh5rXvp-a4cUHI0Mh0H0eEifx41FqPc_hNNhCEZKAl_lB6mxIAA-5rqDkUH8zj-gH0TDgq1hA8GZCjLF6wE5feS14DscTe_oVIAfe_2YYTdDLwtklycGXiIGjMs3XmX002URnASJU2RcX1hROupc2tpXFGOQZmlhAPwgkCD6aSL2gusl56goodXi7lg5GDJyh3iYSSA2qL0HkBs7q3FsbijIvscH3-bIEWZHUX127ZC3f1UL85WPR01hAQi-48VLrcfPC1aFuwuUQm_UEwkZ4LZsEvvPrPtrC1WjtGq7-NDAfNkz6cO9MgsUwjAncXliJW-tTNX3ujDfEA1hAARmh7uujgnsv7CoQt4suDhtVJKZA5UdKahJkUvqXZKRFfhRmJHPwJKnM04IV_AcQd8RH--v2ZUzD6IUGYXCUIVhABjkqmiaLL9PY20li9JBOd0VR7udnu0eM8JMGnnHm_gEIKM3eHWPqyfJyw9AfFymBwm0fgBqRxf0LIo9uDkLlwYJnL2lzc3VlcmovdmFsaWRGcm9t'
}
};
// Derive a new credential with only specific fields disclosed
const derivationResult = await deriveW3C(signedDocument, {
// Only reveal the credential type and givenName, hide birthDate
selectivePointers: ['/type', '/credentialSubject/givenName']
});TrustVC simplifies the verification process with a single function that supports W3C Verifiable Credentials (VCs) and OpenAttestation Verifiable Documents (VDs), including OpenCert Verifiable Documents. Whether you're working with W3C standards or OpenAttestation standards, TrustVC handles the verification seamlessly. For ECDSA-SD-2023 and BBS-2023 signed documents, which normally require derivation before verification, TrustVC automatically handles this process internally - if a document is not derived, the
verifyDocumentfunction will automatically derive and verify the document in a single step.
import { verifyDocument } from '@trustvc/trustvc';
const signedDocument = {
'@context': [
'https://www.w3.org/ns/credentials/v2',
'https://w3id.org/security/data-integrity/v2',
'https://w3c-ccg.github.io/citizenship-vocab/contexts/citizenship-v2.jsonld'
],
credentialStatus: {
id: 'https://trustvc.github.io/did/credentials/statuslist/1#1',
type: 'BitstringStatusListEntry',
statusPurpose: 'revocation',
statusListIndex: '10',
statusListCredential: 'https://trustvc.github.io/did/credentials/statuslist/1'
},
credentialSubject: {
type: ['Person'],
givenName: 'TrustVC',
birthDate: '2024-04-01T12:19:52Z'
},
issuer: 'did:web:trustvc.github.io:did:1',
type: ['VerifiableCredential'],
validFrom: '2024-04-01T12:19:52Z',
validUntil: '2029-12-03T12:19:52Z',
id: 'urn:uuid:0198e4a3-b601-7117-9d02-8c9a9a54ab5d',
proof: {
type: 'DataIntegrityProof',
created: '2025-08-18T14:38:51Z',
verificationMethod: 'did:web:trustvc.github.io:did:1#multikey-1',
cryptosuite: 'ecdsa-sd-2023',
proofPurpose: 'assertionMethod',
proofValue: 'u2V0AhVhAWvyp4W7vt4DBhJy2JjKdbDjNSjh3mFsIfPv68Xk2uc4PSFf1iiAeq19rvnHou1LW_Ff0MrRxzcmuTsBO54q3vVgjgCQDz9CT1s28B8Wsk-i8hgzexvcOZgInRbK9VpG6pMwSfbNYIA0xoaqSwjMxAISQ2l2uRmBFlIdL3XFduNUlo93wj5EMilhA24fPUQHaYlpN2hezHkI2QbUpUzVdIoRFA9KdzA1JNWM9GuCKWF0A62W91QmN82237JIiF1d2aLq3lnCpgR_Y-VhAdhqKN1MXPH5BNYAmM1rSZLHGF92dYt2k3XLb84UsgBYNx0f5VKOKFKNY-ZNho59RdsSTRNbsUzU-zzH1CLkc-lhAKgI6LHZPLePwB-Vsad2jOO-_PGHoHas5-uNJDDSp-xTO2auFGmpI6OGx-U_xwcKYX3su3qwtYCJ3nf2-l-t5SFhAfNLg1QbwjJBStUFCcVZWzu1wDh1d9owiox2nNm9EDun4DU40ThWLoWJEEGtqJYE0XFeMxCNkGJGvBQkXJxKZYlhAXBhzKu4D8oXuUHymh5rXvp-a4cUHI0Mh0H0eEifx41FqPc_hNNhCEZKAl_lB6mxIAA-5rqDkUH8zj-gH0TDgq1hA8GZCjLF6wE5feS14DscTe_oVIAfe_2YYTdDLwtklycGXiIGjMs3XmX002URnASJU2RcX1hROupc2tpXFGOQZmlhAPwgkCD6aSL2gusl56goodXi7lg5GDJyh3iYSSA2qL0HkBs7q3FsbijIvscH3-bIEWZHUX127ZC3f1UL85WPR01hAQi-48VLrcfPC1aFuwuUQm_UEwkZ4LZsEvvPrPtrC1WjtGq7-NDAfNkz6cO9MgsUwjAncXliJW-tTNX3ujDfEA1hAARmh7uujgnsv7CoQt4suDhtVJKZA5UdKahJkUvqXZKRFfhRmJHPwJKnM04IV_AcQd8RH--v2ZUzD6IUGYXCUIVhABjkqmiaLL9PY20li9JBOd0VR7udnu0eM8JMGnnHm_gEIKM3eHWPqyfJyw9AfFymBwm0fgBqRxf0LIo9uDkLlwYJnL2lzc3VlcmovdmFsaWRGcm9t'
}
};
const resultFragments = await verifyDocument(signedDocument);The
encryptfunction encrypts plaintext messages using the ChaCha20 encryption algorithm, ensuring the security and integrity of the input data. It supports custom keys and nonces, returning the encrypted message in hexadecimal format.
function encrypt(message: string, key: string, nonce?: string): string;
The encrypt function is a utility for encrypting text messages using ChaCha20, a stream cipher known for its speed and security. This function ensures that the key meets the 32-byte requirement and that a valid 12-byte nonce is either supplied or generated.
The output is a hexadecimal string representing the encrypted data.
message(string): The plaintext message to encrypt.key(string): The encryption key, which will be transformed into a 32-byte key.nonce(string, optional): A 12-byte nonce for encryption. If omitted, a new nonce will be generated automatically.
string: The encrypted message encoded in hexadecimal format.
- Runtime errors: Issues during key transformation, nonce generation, or encryption.
import { encrypt } from '@trustvc/trustvc';
const message = 'Hello, ChaCha20!';
const key = 'my-secret-key';
const encryptedMessage = encrypt(message, key);
console.log(`Encrypted Message: ${encryptedMessage}`);import { encrypt } from '@trustvc/trustvc';
const message = 'Secure this message.';
const key = 'another-secret-key';
const nonce = '123456789012'; // Custom 12-byte nonce
const encryptedMessage = encrypt(message, key, nonce);
console.log(`Encrypted Message with Nonce: ${encryptedMessage}`);The function uses the following utilities:
stringToUint8Array: Converts strings toUint8Array.generate32ByteKey: Ensures the key is exactly 32 bytes.generate12ByteNonce: Produces a valid 12-byte nonce if none is provided.
It also relies on the ts-chacha20 library for encryption operations.
- The encrypted message is returned as a hexadecimal string.
- Always ensure the key and nonce are securely stored and not reused.
- ChaCha20 requires a unique nonce for each encryption to maintain security.
- Hexadecimal encoding is used by default for simplicity and readability.
The
decryptfunction decrypts messages encrypted with the ChaCha20 algorithm. It converts the input from a hexadecimal format back into plaintext using the provided key and nonce.
function decrypt(encryptedMessage: string, key: string, nonce?: string): string;The decrypt function is a utility for decrypting hexadecimal-encoded messages that were encrypted using the ChaCha20 stream cipher. It ensures the key meets the 32-byte requirement and validates or generates a 12-byte nonce if not supplied.
The function returns the original plaintext message in UTF-8 format.
encryptedMessage(string): The encrypted message, in hexadecimal format.key(string): The decryption key, which will be transformed into a 32-byte key. Defaults toDEFAULT_KEYif an empty key is provided.nonce(string, optional): A 12-byte nonce used during encryption. If omitted, one will be generated.
string: The decrypted plaintext message in UTF-8 format.
The function throws an error if:
- The key is invalid or transformation fails.
- The decryption process encounters unexpected issues.
import { decrypt } from '@trustvc/trustvc';
const encryptedMessage = 'e8b7c7e9...';
const key = 'my-secret-key';
const decryptedMessage = decrypt(encryptedMessage, key);
console.log(`Decrypted Message: ${decryptedMessage}`);import { decrypt } from '@trustvc/trustvc';
const encryptedMessage = 'f3a7e9b2...';
const key = 'another-secret-key';
const nonce = '123456789012'; // Custom 12-byte nonce
const decryptedMessage = decrypt(encryptedMessage, key, nonce);
console.log(`Decrypted Message with Nonce: ${decryptedMessage}`);The function uses the following utilities:
stringToUint8Array: Converts strings toUint8Array.generate32ByteKey: Ensures the key is exactly 32 bytes.generate12ByteNonce: Produces a valid 12-byte nonce if none is provided.
It also relies on the ts-chacha20 library for decryption operations.
- The function accepts the encrypted message in hexadecimal format and returns the decrypted message in UTF-8 format.
- Always use the same key and nonce pair that were used during encryption for successful decryption.
- If a custom nonce is not provided, the function will generate a new one, which may not match the original encryption nonce and will result in decryption failure.
- The default key,
DEFAULT_KEY, should only be used for fallback scenarios and not in production environments. - Suggestion: If available, consider using the value of the key Id inside the document as the encryption key. This can simplify key management and enhance the security of your encryption process.
The Electronic Bill of Lading (eBL) is a digital document that can be used to prove the ownership of goods. It is a standardized document that is accepted by all major shipping lines and customs authorities. The Token Registry repository contains both the smart contract (v4 and v5) code for token registry (in
/contracts) as well as the node package for using this library (in/src). The TrustVC library not only simplifies signing and verification but also imports and integrates existing TradeTrust libraries and smart contracts for token registry (V4 and V5), making it a versatile tool for decentralized identity and trust solutions.
To use the package, you will need to provide your own Web3 provider or signer (if you are writing to the blockchain). This package exposes the Typechain(Ethers) bindings for the contracts.
The
TradeTrustTokenis a Soulbound Token (SBT) tied to the Title Escrow. The SBT implementation is loosely based on OpenZeppelin's implementation of the ERC721 standard. An SBT is used in this case because the token, while can be transferred to the registry, is largely restricted to its designated Title Escrow contracts. See issue #108 for more details.
import { v4Contracts } from '@trustvc/trustvc';
const v4connectedRegistry = v4Contracts.TradeTrustToken__factory.connect(
tokenRegistryAddress,
signer,
);await v4connectedRegistry.mint(beneficiaryAddress, holderAddress, tokenId);await v4connectedRegistry.restore(tokenId);await v4connectedRegistry.burn(tokenId);For more information on Token Registry and Title Escrow contracts version v4, please visit the readme of TradeTrust Token Registry V4.
Token Registry v5 is the newest version. It allows you to manage token-based credentials and ownership transfers through smart contracts. The Tradetrust Token Registry now supports encrypted remarks for enhanced security when executing contract functions. This guide explains how to use the updated title-escrow command with encrypted remarks and highlights the changes introduced in this version. A new rejection function feature has been introduced, allowing a new holder or owner of a document to reject the transfer of the document. This provides an additional layer of control and flexibility for holders and owners to refuse ownership or custodianship if required.
Important
This new version uses:
- Ethers v6
- OpenZeppelin v5
- Contracts are upgraded to v 0.8.20
- Runs on Compiler v 0.8.22
The
remarkfield is optional and can be left empty by providing an empty string"0x". Please note that any value in theremarkfield is limited to 120 characters, and encryption is recommended.
In Token Registry v5, the way you connect to a registry hasn’t changed much, but it's important to ensure you're using the updated contract and factory from Token Registry v5.
In TrustVC, you will use the token-registry-v5 module to access the Token Registry v5 contracts.
import { v5Contracts } from '@trustvc/trustvc';
const connectedRegistry = v5Contracts.TradeTrustToken__factory.connect(
tokenRegistryAddress,
signer,
);In Token Registry v5, there is a slight change when you mint tokens. You will now need to pass remarks as an optional argument. If no remarks are provided, ensure you pass 0x to avoid errors.
await connectedRegistry.mint(beneficiaryAddress, holderAddress, tokenId, remarks);If no remarks are passed, the method expects '0x' as the value for remarks:
await connectedRegistry.mint(beneficiaryAddress, holderAddress, tokenId, '0x');The restore method remains mostly the same, but you'll now also have the option to include remarks.
await connectedRegistry.restore(tokenId, remarks);If no remarks are passed, use '0x':
await connectedRegistry.restore(tokenId, '0x');You can burn or accept a document in Token Registry v5 by passing remarks as an optional argument.
await connectedRegistry.burn(tokenId, remarks);If no remarks are passed, use '0x':
await connectedRegistry.burn(tokenId, '0x');When connecting to Title Escrow, the process is similar. You will use the updated contract from Token Registry v5 or TrustVC depending on your installation choice.
Important
A new remark field has been introduced for all contract operations.
The remark field is optional and can be left empty by providing an empty string "0x".
Please note that any value in the remark field is limited to 120 characters, and encryption is recommended.
import { v5Contracts } from '@trustvc/trustvc';
const connectedEscrow = v5Contracts.TitleEscrow__factory.connect(
existingTitleEscrowAddress,
signer,
);In Token Registry v4, the method to return the title to the issuer was surrender(). With Token Registry v5, this has been updated to returnToIssuer().
await connectedEscrow.returnToIssuer(remarks);If no remarks are provided, you must pass '0x' as the argument:
await connectedEscrow.returnToIssuer('0x');Token Registry v5 introduces additional methods for rejecting transfers, if necessary, for wrongful transactions:
Important
Rejection must occur as the very next action after being appointed as beneficiary and/or holder. If any transactions occur by the new appointee, it will be considered as an implicit acceptance of appointment.
There are separate methods to reject a beneficiary (rejectTransferBeneficiary) and a holder (rejectTransferHolder). However, if you are both, you must use rejectTransferOwners, as the other two methods will not work in this case.
Reject Transfer of Ownership:
Prevents a transfer of ownership to an incorrect or unauthorized party.
function rejectTransferOwner(bytes calldata _remark) external;Reject Transfer of Holding:
Prevents a transfer of holding to an incorrect or unauthorized party.
function rejectTransferHolder(bytes calldata _remark) external;Reject Both Roles (Ownership & Holding):
Prevents both ownership and holding transfers, effectively rejecting the entire transfer process.
function rejectTransferOwners(bytes calldata _remark) external;For more information on Token Registry and Title Escrow contracts version v5, please visit the readme of TradeTrust Token Registry V5
The
DocumentBuilderclass helps build and manage W3C Verifiable Credentials (VCs) with credential status features, implementing the W3C VC Data Model 2.0 specification. It supports creating documents with two types of credential statuses:transferableRecordsandverifiableDocument. It can sign the document using modern cryptographic signature schemes including ECDSA-SD-2023 (default) and BBS-2023, verify its signature, and serialize the document to a JSON format. Additionally, it allows for configuration of document rendering methods and expiration dates.
To create a new document, instantiate the DocumentBuilder with the base document (Verifiable Credential) that you want to build.
To learn more about defining custom contexts, check out the Credential Subject - Custom Contexts guide.
// Adds a custom vocabulary used to define terms in the `credentialSubject`.
// Users can define their own context if they have domain-specific fields or custom data structures.
const builder = new DocumentBuilder({
'@context': 'https://w3c-ccg.github.io/citizenship-vocab/contexts/citizenship-v2.jsonld'
});Set the subject of the Verifiable Credential, which typically contains information about the entity the credential is issued to.
builder.credentialSubject({
type: ['Person'],
givenName: 'TrustVC',
});You can configure the credential status as either transferableRecords or verifiableDocument.
Transferable Records
builder.credentialStatus({
// Refers to the supported network.
// See: https://docs.tradetrust.io/docs/introduction/key-components-of-tradetrust/blockchain/supported-network
chain: 'Ethereum',
chainId: 1,
tokenRegistry: '0x1234567890abcdef...',
rpcProviderUrl: 'https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID',
});
⚠️ Disclaimer:
This builder does not mint documents on-chain. If you're usingtransferableRecords, you'll need to mint the document.
See the minting guide here
Verifiable Document
builder.credentialStatus({
url: 'https://example.com/status-list',
// `index: <placeholder>` refers to the bit position in the status list that will be set for revocation.
// Note: A document with the specific index must be marked as not revoked in the status list.
index: <placeholder>,
purpose: 'revocation',
});You can set a valid until date (expiration) for the document.
builder.expirationDate('2026-01-01T00:00:00Z');Set the rendering method to be used for the document.
builder.renderMethod({
id: 'https://example.com/rendering-method',
type: 'EMBEDDED_RENDERER',
templateName: 'BILL_OF_LADING',
});Set the qrcode method to be used for the document.
builder.qrCode({
uri: 'https://example.com/qrcode',
type: 'TrustVCQRCode',
});To sign the document, provide a PrivateKeyPair from @trustvc/trustvc. The builder supports both ECDSA-SD-2023 (default) and BBS-2023 cryptographic signature schemes.
ECDSA-SD-2023 Signing (Default)
const ecdsaKeyPair: PrivateKeyPair = {
'@context': 'https://w3id.org/security/multikey/v1',
id: 'did:web:example.com#multikey-1',
type: VerificationType.Multikey,
controller: 'did:web:example.com',
publicKeyMultibase: 'your-ecdsa-public-key-multibase',
secretKeyMultibase: 'your-ecdsa-secret-key-multibase',
}
// Sign with default ECDSA-SD-2023 cryptosuite
const signedDocument = await builder.sign(ecdsaKeyPair);
console.log(signedDocument);BBS-2023 Signing
import { CryptoSuite } from '@trustvc/trustvc';
const bbs2023KeyPair: PrivateKeyPair = {
'@context': 'https://w3id.org/security/multikey/v1',
id: 'did:web:example.com#multikey-2',
type: VerificationType.Multikey,
controller: 'did:web:example.com',
publicKeyMultibase: 'your-bbs-public-key-multibase',
secretKeyMultibase: 'your-bbs-secret-key-multibase',
}
// Sign with BBS-2023 cryptosuite by passing CryptoSuite.Bbs2023
const signedDocument = await builder.sign(bbs2023KeyPair, CryptoSuite.Bbs2023);
console.log(signedDocument);Example Output After Signing (ECDSA-SD-2023)
{
"@context": [
"https://www.w3.org/ns/credentials/v2",
"https://w3c-ccg.github.io/citizenship-vocab/contexts/citizenship-v2.jsonld",
"https://trustvc.io/context/render-method-context-v2.json",
"https://trustvc.io/context/qrcode-context.json",
"https://w3id.org/security/data-integrity/v2"
],
"type": ["VerifiableCredential"],
"credentialSubject": {
"type": ["Person"],
"givenName": "TrustVC",
},
"validUntil": "2026-01-01T00:00:00Z",
"renderMethod": [
{
"id": "https://example.com/rendering-method",
"type": "EMBEDDED_RENDERER",
"templateName": "BILL_OF_LADING"
}
],
"qrCode": {
"uri": "https://example.com/qrcode",
"type": "TrustVCQRCode"
},
"credentialStatus": {
"id": "https://example.com/status-list#<placeholder>",
"type": "BitstringStatusListEntry",
"statusPurpose": "revocation",
"statusListIndex": "<placeholder>",
"statusListCredential": "https://example.com/status-list"
},
"issuer": "did:web:example.com",
"validFrom": "2025-01-01T00:00:00Z",
"id": "urn:bnid:_:0195fec2-4ae1-7cca-9182-03fd7da5142b",
"proof": {
"type": "DataIntegrityProof",
"created": "2025-01-01T00:00:01Z",
"verificationMethod": "did:web:example.com#multikey-1",
"cryptosuite": "ecdsa-sd-2023",
"proofPurpose": "assertionMethod",
"proofValue": "u2V0AhVhAh1oLoiuV2AwmSa2ZspbmrG2gCDbpZW.......",
}
}Provide the attributes to reveal to the derive method.
const derivedDocument = await builder.derive(['/credentialSubject/givenName']);
console.log(derivedDocument);To verify the signature of the signed document, ensure the document is derived first and then call the verify method.
const isVerified = await builder.verify();
console.log(isVerified); // true or falseTo get the current state of the document as a JSON string:
const documentJson = builder.toString();
console.log(documentJson);TrustVC provides comprehensive Document Store functionality for managing blockchain-based document storage and verification. The Document Store module supports both standard DocumentStore and TransferableDocumentStore contracts, enabling secure document issuance, revocation, and role management on various blockchain networks.
- Dual Contract Support: Works with both DocumentStore and TransferableDocumentStore contracts
- Automatic Contract Detection: Uses ERC-165 interface checking to automatically identify contract types
- Ethers Compatibility: Full support for both ethers v5 and v6
- Type Safety: Full TypeScript support with comprehensive type definitions
Deploys a new DocumentStore contract to the blockchain.
Parameters:
storeName(string): The name of the document storeowner(string): The owner address of the document storesigner(Signer): Ethers v5 or v6 signer instanceoptions(DeployOptions, optional): Deployment configuration
DeployOptions:
chainId(CHAIN_ID, optional): Target blockchain networkmaxFeePerGas(GasValue, optional): Maximum fee per gasmaxPriorityFeePerGas(GasValue, optional): Maximum priority fee per gasisTransferable(boolean, optional): Whether to deploy TransferableDocumentStore
Returns: Promise<TransactionReceipt> - The deployment transaction receipt
Example:
import { deployDocumentStore } from '@trustvc/trustvc';
const receipt = await deployDocumentStore(
'My Document Store',
'0x1234567890123456789012345678901234567890',
signer,
{
chainId: CHAIN_ID.sepolia,
isTransferable: true,
}
);
console.log('Contract deployed at:', receipt.contractAddress);Issues a document to the Document Store.
Parameters:
documentStoreAddress(string): Address of the Document Store contractdocumentHash(string): Hash of the document to issuesigner(Signer): Ethers v5 or v6 signer instanceoptions(IssueOptions, optional): Issuance configuration
IssueOptions:
chainId(CHAIN_ID, optional): Target blockchain networkmaxFeePerGas(GasValue, optional): Maximum fee per gasmaxPriorityFeePerGas(GasValue, optional): Maximum priority fee per gasisTransferable(boolean, optional): Whether the contract is TransferableDocumentStore
Returns: Promise<string> - Transaction hash of the issuance
Example:
import { documentStoreIssue } from '@trustvc/trustvc';
const txHash = await documentStoreIssue(
'0x1234567890123456789012345678901234567890',
'0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890',
signer,
{
chainId: CHAIN_ID.sepolia,
isTransferable: false,
}
);
console.log('Document issued, transaction:', txHash);Revokes a document from the Document Store.
Parameters:
documentStoreAddress(string): Address of the Document Store contractdocumentHash(string): Hash of the document to revokesigner(Signer): Ethers v5 or v6 signer instanceoptions(RevokeOptions, optional): Revocation configuration
RevokeOptions:
chainId(CHAIN_ID, optional): Target blockchain networkmaxFeePerGas(GasValue, optional): Maximum fee per gasmaxPriorityFeePerGas(GasValue, optional): Maximum priority fee per gasisTransferable(boolean, optional): Whether the contract is TransferableDocumentStore
Returns: Promise<string> - Transaction hash of the revocation
Example:
import { documentStoreRevoke } from '@trustvc/trustvc';
const txHash = await documentStoreRevoke(
'0x1234567890123456789012345678901234567890',
'0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890',
signer,
{
chainId: CHAIN_ID.sepolia,
isTransferable: false,
}
);
console.log('Document revoked, transaction:', txHash);- Basic document store functionality
- Supports document issuance and revocation
- ERC-165 interface:
0x01ffc9a7(IDocumentStore)
- Extended document store with transfer capabilities
- All DocumentStore functionality plus transfer features
- ERC-165 interface:
0x8c5a6b8a(ITransferableDocumentStore)
All functions include comprehensive error handling:
- Validation Errors: Invalid addresses, missing parameters, provider issues
- Contract Errors: Pre-check failures, insufficient permissions, contract reverts
- Network Errors: Connection issues, transaction failures
- Interface Detection: Automatic fallback when ERC-165 interfaces are not supported
The Document Store functions support gas optimization through configurable transaction options:
const options = {
maxFeePerGas: '50000000000', // 50 gwei
maxPriorityFeePerGas: '2000000000', // 2 gwei
chainId: CHAIN_ID.mainnet,
};import { deployDocumentStore, documentStoreIssue, documentStoreRevoke } from '@trustvc/trustvc';
// Deploy a new document store
const receipt = await deployDocumentStore('My Store', ownerAddress, signer);
// Issue a document
await documentStoreIssue(receipt.contractAddress, documentHash, signer);
// Revoke if needed
await documentStoreRevoke(receipt.contractAddress, documentHash, signer);import { CHAIN_ID } from '@trustvc/trustvc';
// Deploy with specific network and gas settings
const receipt = await deployDocumentStore(
'Production Store',
ownerAddress,
signer,
{
chainId: CHAIN_ID.mainnet,
maxFeePerGas: '100000000000', // 100 gwei
maxPriorityFeePerGas: '5000000000', // 5 gwei
isTransferable: true,
}
);
// Issue with explicit contract type detection
await documentStoreIssue(
receipt.contractAddress,
documentHash,
signer,
{
chainId: CHAIN_ID.mainnet,
isTransferable: true, // Explicit type detection
}
);// Issue multiple documents
const documentHashes = [
'0xhash1...',
'0xhash2...',
'0xhash3...',
];
for (const hash of documentHashes) {
await documentStoreIssue(storeAddress, hash, signer);
}TrustVC provides a utility to cancel a pending Ethereum transaction by replacing it with a 0-value transaction to the same address, using the same nonce and a higher gas price (replace-by-fee). This works with both ethers v5 and v6 signers.
Reference: How to cancel Ethereum pending transactions
Cancels a pending transaction by sending a 0-value transaction to the signer’s address with the same nonce and a higher gas price. You can specify the pending transaction either by transaction hash (nonce and gas price are fetched; gas price is doubled) or by nonce and gas price explicitly. Transactions that use EIP-1559 (no legacy gasPrice) must be cancelled using nonce and gas price.
- signer – Signer with a connected provider; type
CancelTransactionSigner(compatible with ethers v5 and v6 signers). - options –
CancelTransactionOptions:- transactionHash (optional): Pending transaction hash (
0x...). If provided, nonce and gas price are read from the chain and gas price is increased by 100%. - nonce (optional): Pending transaction nonce. Must be used together with
gasPrice. - gasPrice (optional): Gas price in wei for the replacement transaction. Must be used together with
nonce.
- transactionHash (optional): Pending transaction hash (
Either (nonce, gasPrice) or transactionHash must be provided.
Promise<string> – The replacement transaction hash.
- If the signer has no provider.
- If neither
(nonce, gasPrice)nortransactionHashis provided. - If
transactionHashis given but the transaction is not found. - If the transaction uses EIP-1559 (no
gasPrice); in that case use nonce and gas price explicitly.
import { cancelTransaction } from '@trustvc/trustvc';
// Cancel by transaction hash (gas price is fetched and doubled)
const replacementHash = await cancelTransaction(signer, {
transactionHash: '0x...',
});
console.log('Replacement tx:', replacementHash);
// Or cancel by nonce and gas price (e.g. for EIP-1559 txs)
const replacementHash2 = await cancelTransaction(signer, {
nonce: '5',
gasPrice: '25000000000', // 25 gwei in wei
});