@gotake/gotake-sdk
Version:
SDK for interacting with GoTake blockchain contracts
89 lines (88 loc) • 2.53 kB
JavaScript
/**
* Base class for all API modules, providing shared functionality
*/
export class BaseApi {
/**
* Create API module 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 BaseApi 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;
}
}
/**
* Update connection information (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;
// Subclasses can handle their own updates by overriding this method
this.onConnectionUpdated();
}
/**
* Method called when connection is updated, can be overridden by subclasses
*/
async onConnectionUpdated() {
// Base implementation re-initializes networkId
await this.init();
}
/**
* Get current network ID
*/
get networkId() {
if (!this._initialized) {
console.warn("Accessing networkId before initialization. Call init() first.");
}
return this._networkId;
}
/**
* Get current Provider
*/
get provider() {
return this._provider;
}
/**
* Get current Signer
*/
get signer() {
return this._signer;
}
/**
* Get current user address
*/
async getAddress() {
return this._signer.getAddress();
}
}