@gotake/gotake-sdk
Version:
SDK for interacting with GoTake blockchain contracts
106 lines (105 loc) • 3.22 kB
JavaScript
import { getContractAddress } from 'gotake-contracts';
import { NetworkId } from '../utils/index.js';
/**
* Base class for all contract wrappers, providing common functionality
*/
export class BaseWrapper {
/**
* Create wrapper instance
* @param provider Provider instance
* @param signer Signer instance
*/
constructor(provider, signer) {
this._initialized = false;
this._provider = provider;
this._signer = signer;
}
/**
* Initialize network ID from signer
* Must be called before using methods that depend on networkId
*/
async init() {
if (this._initialized && this._networkId !== undefined) {
// If previously initialized with a signer, return
if (this._signer)
return;
}
if (!this._signer) {
console.warn("Attempted to init BaseWrapper without a signer. NetworkId will be undefined.");
this._initialized = true; // Mark as attempted initialization
return;
}
try {
const chainId = await this._signer.getChainId();
this._networkId = chainId;
this._initialized = true;
}
catch (error) {
console.error("Failed to initialize networkId from signer:", error);
this._initialized = false; // Allow retry
throw error;
}
}
/**
* Get contract address
* @param contractName Contract name
* @returns Contract address
*/
getContractAddress(contractName) {
if (this._networkId === undefined) {
throw new Error("NetworkId not initialized. Call init() first.");
}
// Map NetworkId to network key
const networkKey = this.getNetworkKey(this._networkId);
return getContractAddress(networkKey, contractName);
}
/**
* Convert NetworkId to network key string
* @param networkId Network ID
* @returns Network key
*/
getNetworkKey(networkId) {
const networkMap = {
[NetworkId.ETHEREUM_MAINNET]: 'ethereum_mainnet',
[NetworkId.ETHEREUM_GOERLI]: 'ethereum_goerli',
[NetworkId.ETHEREUM_SEPOLIA]: 'ethereum_sepolia',
[NetworkId.BASE_MAINNET]: 'base_mainnet',
[NetworkId.BASE_GOERLI]: 'base_goerli',
[NetworkId.BASE_SEPOLIA]: 'base_sepolia',
};
const key = networkMap[networkId];
if (!key) {
throw new Error(`Network ID ${networkId} not supported`);
}
return key;
}
/**
* Update Provider and Signer (when network changes)
* @param provider New Provider
* @param signer New Signer
*/
updateConnection(provider, signer) {
this._provider = provider;
this._signer = signer;
this._initialized = false;
this._networkId = undefined;
}
/**
* Get current Provider
*/
get provider() {
return this._provider;
}
/**
* Get current Signer
*/
get signer() {
return this._signer;
}
/**
* Get current network ID
*/
get networkId() {
return this._networkId;
}
}