vechain-sdk-js icon indicating copy to clipboard operation
vechain-sdk-js copied to clipboard

💡 [REQUEST] - Improve serverless (especially CloudFlare) support

Open ifavo opened this issue 9 months ago • 0 comments

Summary

My personal setup involves CloudFlare Workers a lot to create APIs or Vechain interaction with a very low effort. To enable transaction building with connex I have a stripped version of the thor-devkit that runs in node_compat (NodeJS compatibility) mode.

I would like to use the SDK within CloudFlare Workers in compatibility mode as well without creating a stripped version to:

  1. Build transaction objects
  2. Sign transactions
  3. Interact with the Node-APIs

Ideas to create the compatibility are:

  1. Use global fetch or allow injection of fetch function
  2. Dynamically import modules, like events on demand instead

Basic Example

  1. Create a new CloudFlare Worker using npx wrangler generate sdk-cf
  2. Add @vechain/sdk-network to it using npm install --save @vechain/sdk-network @vechain/sdk-core
  3. Create a thor client in the worker using ThorClient.fromUrl('https://testnet.vechain.org')
  4. Test the Worker by using wrangler dev or if you have a CloudFlare account use wrangler deploy
    • It will fail to start.
    • Optimal Results would be a CloudFlare Worker that can use the SDK instantly without enable Node Compatibility in the next step.
  5. Add node_compat = true to the wrangler.toml to enable NodeJS compatibility
  6. Test the Worker by using wrangler dev or if you have a CloudFlare account use wrangler deploy

Using this simplified index.ts:

import { ThorClient } from "@vechain/sdk-network";
export default {
	async fetch(
	): Promise<Response> {
		const thor = ThorClient.fromUrl('https://testnet.vechain.org')
		const block = await thor.blocks.getBestBlockRef()
		return new Response(block);
	},
};

ifavo avatar Apr 29 '24 07:04 ifavo