UNPKG

@gotake/gotake-sdk

Version:

SDK for interacting with GoTake blockchain contracts

65 lines (64 loc) 2.25 kB
import { ethers } from 'ethers'; import { JsonRpcProvider } from '@ethersproject/providers'; import { hasEnvironmentVariables, getEnvironmentVariable } from './environment.js'; // Async dotenv loading for Node.js environments only let dotenvLoaded = false; async function loadDotenvIfNeeded() { if (dotenvLoaded || !hasEnvironmentVariables()) { return; } try { // Dynamic import to avoid bundler issues const dotenv = await import('dotenv'); dotenv.config(); dotenvLoaded = true; } catch (error) { // Dotenv not available, continue without it } } /** * Get environment variable value * @param key Environment variable name * @param defaultValue Default value (if environment variable doesn't exist) * @returns Environment variable value */ export async function getEnv(key, defaultValue) { await loadDotenvIfNeeded(); const value = getEnvironmentVariable(key, defaultValue); if (value === undefined) { if (!hasEnvironmentVariables()) { throw new Error(`Environment variables not available in browser environment. Please provide ${key} directly.`); } throw new Error(`Environment variable ${key} not set`); } return value; } /** * Get private key from environment variable * @param keyName Private key environment variable name, default is 'PRIVATE_KEY' * @returns Private key string */ export async function getPrivateKey(keyName = 'PRIVATE_KEY') { return await getEnv(keyName); } /** * Create Signer from environment variable * @param provider Ethereum Provider * @param keyName Private key environment variable name * @returns Ethereum wallet instance */ export async function createSignerFromEnv(provider, keyName = 'PRIVATE_KEY') { const privateKey = await getPrivateKey(keyName); return new ethers.Wallet(privateKey, provider); } /** * Create Provider from environment variable or parameter * @param rpcUrl RPC URL (optional) * @returns JsonRpcProvider instance */ export async function createProvider(rpcUrl) { // If RPC URL is provided, use it; otherwise, get it from environment variable const url = rpcUrl || await getEnv('RPC_URL'); return new JsonRpcProvider(url); }