vechain / vechain-sdk-js

The official JavaScript SDK for VeChain.
23 stars 9 forks source link

💡 [REQUEST] - Support transaction signing on CloudFlare workers #1095

Closed ifavo closed 1 month ago

ifavo commented 1 month ago

Summary

This isuse is related to https://github.com/vechain/vechain-sdk-js/issues/830

Summary

Interaction with Vechain in CloudFlare Workers to read blockchain data is now possible with the latest updates.

I would like to use the SDK within CloudFlare Workers also to build and sign transactions.

Right now this fails with an error:

crypto.getRandomValues must be defined

Being able to sign in CloudFlare workers empowers developers to quickly leverage CloudFlares serverless infrastructure.

Basic Example

Example worker using the docs example signing snippet:

import { clauseBuilder, TransactionUtils, networkInfo, secp256k1, TransactionHandler } from "@vechain/sdk-core";

export interface Env {}

export default {
    async fetch(
        request: Request,
        env: Env,
        ctx: ExecutionContext
    ): Promise<Response> {
        const clauses = [
            clauseBuilder.transferVET(
                '0x7567d83b7b8d80addcb281a71d54fc7b3364ffed', 0
            )
        ];

        // 2 - Calculate intrinsic gas of clauses
        const gas = TransactionUtils.intrinsicGas(clauses);

        // 3 - Body of transaction
        const body = {
            chainTag: networkInfo.mainnet.chainTag,
            blockRef: '0x0000000000000000',
            expiration: 0,
            clauses,
            gasPriceCoef: 128,
            gas,
            dependsOn: null,
            nonce: 12345678
        };

        // Create private key
        const privateKey = secp256k1.generatePrivateKey();

        // 4 - Sign transaction
        const signedTransaction = TransactionHandler.sign(
            body,
            Buffer.from(privateKey)
        );

        // 5 - Encode transaction
        const encodedRaw = signedTransaction.encoded;

        // 6 - Decode transaction
        const decodedTx = TransactionHandler.decode(encodedRaw, true);
        return new Response(JSON.stringify(decodedTx))
    },
};
victhorbi commented 1 month ago

Blocked by #1092

ifavo commented 1 month ago

I just tried with the latest release, and it worked! Thanks a lot, I will try some things with the SDK in workers now! :)