Skip to content

Commit

Permalink
chore: Improve doc examples (#334)
Browse files Browse the repository at this point in the history
* fix: move builddocs.ts in build-scripts folder

* fix: typo
  • Loading branch information
rodolfopietro97 authored Dec 4, 2023
1 parent 6492cfb commit 4c9fa87
Show file tree
Hide file tree
Showing 39 changed files with 585 additions and 387 deletions.
90 changes: 51 additions & 39 deletions docs/accounts.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,23 @@ Mnemonics represent a standard human-readable approach to generate private keys.
import { mnemonic } from '@vechainfoundation/vechain-sdk-core';
import { expect } from 'expect';

// Generate BIP39 mnemonic words, default to 12 words(128bit strength)
const rndMnemonic = mnemonic.generate();
// 1 - Generate BIP39 mnemonic words, default to 12 words (128bit strength)

const randomMnemonic = mnemonic.generate();

console.log('Mnemonic words', randomMnemonic);
// Mnemonic words: "w1 w2 ... w12"

// 2 - Derive private key from mnemonic words according to BIP32, using the path `m/44'/818'/0'/0`.

// Derive private key from mnemonic words according to BIP32, using the path `m/44'/818'/0'/0`.
// Defined for VET at https://github.com/satoshilabs/slips/blob/master/slip-0044.md
const privateKey = mnemonic.derivePrivateKey(rndMnemonic);
const privateKey = mnemonic.derivePrivateKey(randomMnemonic);

console.log(privateKey.toString('hex'));
// ...SOME PRIVATE KEY...

// In recovery process, validation is recommended
const ok = mnemonic.validate(rndMnemonic);
expect(ok).toBeTruthy();
expect(mnemonic.validate(randomMnemonic)).toBeTruthy();
// true

```
Expand All @@ -37,15 +42,19 @@ expect(ok).toBeTruthy();
```typescript { name=bip32, category=example }
import { mnemonic, HDNode } from '@vechainfoundation/vechain-sdk-core';

// Generate BIP39 mnemonic words, default to 12 words(128bit strength)
const rndMnemonic = mnemonic.generate();
console.log('Mnemonic words', rndMnemonic);
// 1 - Generate BIP39 mnemonic words, default to 12 words (128bit strength)

const randomMnemonic = mnemonic.generate();

console.log('Mnemonic words', randomMnemonic);
// Mnemonic words: "w1 w2 ... w12"

// Create BIP32 HD node from mnemonic words
const hdnode = HDNode.fromMnemonic(rndMnemonic);
// 2 - Create BIP32 HD node from mnemonic words

const hdnode = HDNode.fromMnemonic(randomMnemonic);

// 3 - Derive 5 child private keys

// Derive 5 child private keys
for (let i = 0; i < 5; i++) {
const child = hdnode.derive(i);
console.log(`children ${i}`, child.address);
Expand All @@ -62,22 +71,27 @@ for (let i = 0; i < 5; i++) {
```typescript { name=pubkey, category=example }
import { HDNode } from '@vechainfoundation/vechain-sdk-core';

// Create HD node from xpub
// 1 - Create HD node from xpub (extended private key) and chain code

const xpub = Buffer.from(
'04dc40b4324626eb393dbf77b6930e915dcca6297b42508adb743674a8ad5c69a046010f801a62cb945a6cb137a050cefaba0572429fc4afc57df825bfca2f219a',
'hex'
);

const chainCode = Buffer.from(
'105da5578eb3228655a8abe70bf4c317e525c7f7bb333634f5b7d1f70e111a33',
'hex'
);

// Create BIP32 HD node from xpub
// 2 - Create BIP32 HD node from xpub

const hdnode = HDNode.fromPublicKey(xpub, chainCode);

// Derive 5 child public keys
// 3 - Derive 5 child public keys

for (let i = 0; i < 5; i++) {
const child = hdnode.derive(i);

console.log(`children ${i}`, child.address);
// children 0 0x...
// children 1 0x...
Expand All @@ -97,36 +111,34 @@ Through the use of mnemonics and keystore, Vechain SDK ensures secure and user-f
import { keystore, secp256k1 } from '@vechainfoundation/vechain-sdk-core';
import { expect } from 'expect';

async function example(): Promise<void> {
// Create private key
// 1 - Create private key using Secp256k1

// BIP 39
// const words = mnemonic.generate()
// const privateKey = mnemonic.derivePrivateKey(words)
const privateKey = secp256k1.generatePrivateKey();

// Secp256k1
const privateKey = secp256k1.generatePrivateKey();
// @NOTE you can use BIP 39 too!
// const words = mnemonic.generate()
// const privateKey = mnemonic.derivePrivateKey(words)

// ...
// ...

// Encrypt/decrypt private key using Ethereum's keystore scheme
const keyStorePassword = 'your password';
const newKeyStore = await keystore.encrypt(privateKey, keyStorePassword);
// 2 - Encrypt/decrypt private key using Ethereum's keystore scheme

// Throw for wrong password
const recoveredPrivateKey = await keystore.decrypt(
newKeyStore,
keyStorePassword
);
console.log(recoveredPrivateKey.privateKey.toString());
// ...
const keyStorePassword = 'your password';
const newKeyStore = await keystore.encrypt(privateKey, keyStorePassword);

// Roughly check keystore format
const ok = keystore.isValid(newKeyStore);
expect(ok).toBeTruthy();
// Key store ok true
}
await example();
// 3 - Throw for wrong password

const recoveredPrivateKey = await keystore.decrypt(
newKeyStore,
keyStorePassword
);

console.log(recoveredPrivateKey.privateKey.toString());
// 0x...

// Roughly check keystore format
expect(keystore.isValid(newKeyStore)).toBeTruthy();
// Key store ok true

```

12 changes: 8 additions & 4 deletions docs/bloom-filter.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,23 @@ By employing bloom filters in this manner, the VechainThor blockchain significan
import { bloom } from '@vechainfoundation/vechain-sdk-core';
import { expect } from 'expect';

// Get best value of k (bits per key)
// 1 - Get best value of k (bits per key)

const k = bloom.calculateK(100);
console.log(k);

// Create a bloom filter with 14 bits
// 2 - Create a bloom filter with 14 bits

const bloomGenerator = new bloom.Generator();

// Add number from 0 to 99 to the bloom gernator
// 3 - Add number from 0 to 99 to the bloom gernator

for (let i = 0; i < 100; i++) {
bloomGenerator.add(Buffer.from(i + '', 'utf8'));
}

// Create the filter
// 4 - Create the filter

const bloomFilter = bloomGenerator.generate(100, k);

// Positive case (number from 0 to 99 must be present in the bloom filter)
Expand Down
File renamed without changes.
10 changes: 5 additions & 5 deletions docs/certificates.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,14 @@ import {
addressUtils
} from '@vechainfoundation/vechain-sdk-core';

// In this example we create a certificate and
// sign it, and then call verify to verify the signature
// 1 - Generate a private key and address for the signer

// Generate a private key and address for the signer
const privateKey = secp256k1.generatePrivateKey();
const publicKey = secp256k1.derivePublicKey(privateKey);
const signerAddress = addressUtils.fromPublicKey(publicKey);

// Create a certificate
// 2 - Create a certificate

const cert: Certificate = {
purpose: 'identification',
payload: {
Expand All @@ -62,7 +61,8 @@ const cert: Certificate = {
signer: signerAddress
};

// Sign certificate
// 3 - Sign certificate

const jsonStr = certificate.encode(cert);
const signature = secp256k1.sign(blake2b256(jsonStr), privateKey);

Expand Down
21 changes: 19 additions & 2 deletions docs/contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,17 @@ This example showcases the process of building a smart contract transaction usin
import { buildDeployContractTransaction } from '@vechainfoundation/vechain-sdk-core';
import { expect } from 'expect';

// 1 - Init contract bytecode to deploy

const contractBytecode =
'0x608060405234801561000f575f80fd5b506101438061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610034575f3560e01c806360fe47b1146100385780636d4ce63c14610054575b5f80fd5b610052600480360381019061004d91906100ba565b610072565b005b61005c61007b565b60405161006991906100f4565b60405180910390f35b805f8190555050565b5f8054905090565b5f80fd5b5f819050919050565b61009981610087565b81146100a3575f80fd5b50565b5f813590506100b481610090565b92915050565b5f602082840312156100cf576100ce610083565b5b5f6100dc848285016100a6565b91505092915050565b6100ee81610087565b82525050565b5f6020820190506101075f8301846100e5565b9291505056fea2646970667358221220427ff5682ef89b62b910bb1286c1028d32283512122854159ad59f1c71fb6d8764736f6c63430008160033';

// 2 - Create a transaction to deploy the contract

const transaction = buildDeployContractTransaction(contractBytecode);
console.log(transaction);

// The first clause of the transaction should be a deploy contract clause
expect(transaction.body.clauses[0].data).toEqual(contractBytecode);

```
Expand All @@ -37,9 +44,14 @@ This example provides a practical demonstration of utilizing the Vechain SDK to
This example demonstrates the process of building a transaction to call a function on a deployed smart contract using the Vechain SDK.

```typescript { name=contract-function-call, category=example }
import { networkInfo, buildCallContractTransaction } from '@vechainfoundation/vechain-sdk-core';
import {
networkInfo,
buildCallContractTransaction
} from '@vechainfoundation/vechain-sdk-core';
import { expect } from 'expect';

// 1 - Init a simple contract ABI

const contractABI = JSON.stringify([
{
constant: false,
Expand Down Expand Up @@ -71,17 +83,22 @@ const contractABI = JSON.stringify([
}
]);

// 2 - Create a transaction to call setValue(123)

const transaction = buildCallContractTransaction(
'0x7567d83b7b8d80addcb281a71d54fc7b3364ffed', // just a sample deployed contract address
contractABI,
'setValue',
[123]
);

// check the parameters of the transaction
// 3 - Check the parameters of the transaction

expect(transaction.body.clauses[0].to).toBe(
'0x7567d83b7b8d80addcb281a71d54fc7b3364ffed'
);

// Some checks on the transaction body
expect(transaction.body.clauses[0].value).toBe(0);
expect(transaction.body.clauses[0].data).toBeDefined();
expect(transaction.body.nonce).toBeDefined();
Expand Down
27 changes: 19 additions & 8 deletions docs/cryptography.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,15 @@ vechain sdk supports blake2b256 and keccak256 hash functions.
Blake2b256 is a specific type of hash function known for its speed and security. It takes any input data and generates a 256-bit (32-byte) hash value. The blake2b256 part refers to the specific design of the algorithm, and the 256 indicates the length of the resulting hash code. Blake2b256 is widely used in cryptographic applications, blockchain technologies, and secure data storage.

```typescript { name=blake2b256, category=example }
import { blake2b256, type HashInput } from '@vechainfoundation/vechain-sdk-core';
import {
blake2b256,
type HashInput
} from '@vechainfoundation/vechain-sdk-core';
import { expect } from 'expect';

// Input of hash function (it can be a string or a Buffer)
const toHash: HashInput = 'hello world';

const hash = blake2b256(toHash);
expect(hash.toString('hex')).toBe(
'256c83b297114d201b30179f3f0ef0cace9783622da5974326b436178aeef610'
Expand All @@ -34,7 +39,9 @@ Keccak256 is another type of hash function, and it's particularly well-known for
import { keccak256, type HashInput } from '@vechainfoundation/vechain-sdk-core';
import { expect } from 'expect';

// Input of hash function (it can be a string or a Buffer)
const toHash: HashInput = 'hello world';

const hash = keccak256(toHash);
expect(hash.toString('hex')).toBe(
'47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad'
Expand Down Expand Up @@ -63,29 +70,33 @@ import {
} from '@vechainfoundation/vechain-sdk-core';
import { expect } from 'expect';

// Generate a private key
// 1 - Generate a private key

const privateKey = secp256k1.generatePrivateKey();
console.log('Private key:', privateKey.toString('hex'));
// Private key: ...SOME_PRIVATE_KEY...

// Public key and address from private key
// 2 - Derive public key and address from private key

const publicKey = secp256k1.derivePublicKey(privateKey);
const userAddress = addressUtils.fromPublicKey(publicKey);
console.log('User address:', userAddress);
// User address: 0x...SOME_ADDRESS...

// Sign message
// 3 - Sign message

const messageToSign: HashInput = 'hello world';
const hash = keccak256(messageToSign);
console.log(`Hash: ${hash.toString()}`);

const signature = secp256k1.sign(hash, privateKey);
console.log('Signature:', signature.toString('hex'));
// Signature: ...SOME_SIGNATURE...

// Test recovery
const recoveredPubKey = secp256k1.recover(hash, signature);
const equals = publicKey.equals(recoveredPubKey);
expect(equals).toBeTruthy();
// 4 - Test recovery of public key

const recoveredPublicKey = secp256k1.recover(hash, signature);
expect(publicKey.equals(recoveredPublicKey)).toBeTruthy();
// Recovered public key is correct: true

```
Loading

1 comment on commit 4c9fa87

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test Coverage

Summary

Lines Statements Branches Functions
Coverage: 100%
100% (1244/1244) 100% (273/273) 100% (263/263)
Title Tests Skipped Failures Errors Time
core 347 0 💤 0 ❌ 0 🔥 1m 8s ⏱️
network 90 0 💤 0 ❌ 0 🔥 1m 27s ⏱️
errors 30 0 💤 0 ❌ 0 🔥 8.044s ⏱️

Please sign in to comment.