Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: eliminate read only ethereum handler, export ethereum functions #21

Merged
merged 3 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"type": "module",
"name": "dlc-btc-lib",
"version": "2.0.0",
"version": "2.1.0",
"description": "This library provides a comprehensive set of interfaces and functions for minting dlcBTC tokens on supported blockchains.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
22 changes: 22 additions & 0 deletions src/constants/ethereum-constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,23 @@ export const ethereumArbitrum: EthereumNetwork = {
defaultNodeURL: 'https://arb1.arbitrum.io/rpc',
};

const ethereumHardhat: EthereumNetwork = {
name: 'Hardhat',
displayName: 'Hardhat',
id: EthereumNetworkID.Hardhat,
defaultNodeURL: 'http://localhost:8545',
};

export const supportedEthereumNetworks: EthereumNetwork[] = [
ethereumArbitrumSepolia,
ethereumArbitrum,
ethereumHardhat,
];

export const hexChainIDs: { [key in EthereumNetworkID]: string } = {
[EthereumNetworkID.ArbitrumSepolia]: '0x66eee',
[EthereumNetworkID.Arbitrum]: '0xa4b1',
[EthereumNetworkID.Hardhat]: '0x7a69',
};

export const addNetworkParams = {
Expand Down Expand Up @@ -55,6 +64,19 @@ export const addNetworkParams = {
blockExplorerUrls: ['https://arbiscan.io/'],
},
],
[EthereumNetworkID.Hardhat]: [
{
chainId: '31337',
rpcUrls: ['http://localhost:8545'],
chainName: 'Hardhat',
nativeCurrency: {
name: 'ETH',
symbol: 'ETH',
decimals: 18,
},
blockExplorerUrls: [],
},
],
};

export const GITHUB_SOLIDITY_URL = 'https://raw.githubusercontent.com/DLC-link/dlc-solidity';
Expand Down
180 changes: 157 additions & 23 deletions src/functions/ethereum/ethereum-functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from '../../constants/ethereum-constants.js';
import { EthereumError } from '../../models/errors.js';
import {
DLCEthereumContractName,
DLCEthereumContracts,
DLCSolidityBranchName,
EthereumDeploymentPlan,
Expand Down Expand Up @@ -88,10 +89,14 @@ export function getProvider(
}
}

export function getEthereumontract(
export function getEthereumContract(
ethereumDeploymentPlans: EthereumDeploymentPlan[],
contractName: string,
signerOrProvider: Wallet | providers.JsonRpcSigner | providers.JsonRpcProvider
signerOrProvider:
| Wallet
| providers.JsonRpcSigner
| providers.JsonRpcProvider
| providers.WebSocketProvider
): Contract {
try {
const contractDeploymentPlan = ethereumDeploymentPlans.find(
Expand All @@ -118,31 +123,12 @@ export function getEthereumContracts(
ethereumDeploymentPlans: EthereumDeploymentPlan[],
signer: Wallet | providers.JsonRpcSigner
): DLCEthereumContracts {
const dlcManagerContract = getEthereumontract(ethereumDeploymentPlans, 'DLCManager', signer);
const dlcBTCContract = getEthereumontract(ethereumDeploymentPlans, 'DLCBTC', signer);
const dlcManagerContract = getEthereumContract(ethereumDeploymentPlans, 'DLCManager', signer);
const dlcBTCContract = getEthereumContract(ethereumDeploymentPlans, 'DLCBTC', signer);

return { dlcManagerContract, dlcBTCContract };
}

export function getReadOnlyEthereumContracts(
ethereumDeploymentPlans: EthereumDeploymentPlan[],
readOnlyProvider: providers.JsonRpcProvider
): { protocolContract: Contract; dlcManagerContract: Contract; dlcBTCContract: Contract } {
const protocolContract = getEthereumontract(
ethereumDeploymentPlans,
'TokenManager',
readOnlyProvider
);
const dlcManagerContract = getEthereumontract(
ethereumDeploymentPlans,
'DLCManager',
readOnlyProvider
);
const dlcBTCContract = getEthereumontract(ethereumDeploymentPlans, 'DLCBTC', readOnlyProvider);

return { protocolContract, dlcManagerContract, dlcBTCContract };
}

export async function getLockedBTCBalance(userVaults: RawVault[]): Promise<number> {
try {
const fundedVaults = userVaults.filter(vault => vault.status === VaultState.FUNDED);
Expand All @@ -155,3 +141,151 @@ export async function getLockedBTCBalance(userVaults: RawVault[]): Promise<numbe
throw new EthereumError(`Could not fetch locked BTC balance: ${error}`);
}
}

export async function getReadOnlyContract(
contractName: DLCEthereumContractName,
ethereumNetwork: EthereumNetwork,
ethereumContractBranch: DLCSolidityBranchName,
rpcEndpoint?: string
): Promise<Contract> {
try {
const dlcManagerContractDeploymentPlan = await fetchEthereumDeploymentPlan(
contractName,
ethereumNetwork,
ethereumContractBranch,
GITHUB_SOLIDITY_URL
);

const provider = getProvider(rpcEndpoint ?? ethereumNetwork.defaultNodeURL);

return new Contract(
dlcManagerContractDeploymentPlan.contract.address,
dlcManagerContractDeploymentPlan.contract.abi,
provider
);
} catch (error) {
throw new EthereumError(`Could not fetch DLCManager Contract: ${error}`);
}
}

export async function isUserWhitelisted(
dlcManagerContract: Contract,
userAddress: string
): Promise<boolean> {
try {
return await dlcManagerContract.isWhitelisted(userAddress);
} catch (error) {
throw new EthereumError(`Could not check if User is whitelisted: ${error}`);
}
}

export async function isWhitelistingEnabled(dlcManagerContract: Contract): Promise<boolean> {
return await dlcManagerContract.whitelistingEnabled();
}

export async function getAttestorGroupPublicKey(dlcManagerContract: Contract): Promise<string> {
try {
const attestorGroupPubKey = await dlcManagerContract.attestorGroupPubKey();
if (!attestorGroupPubKey)
throw new Error('Attestor Group Public key is not set on DLCManager Contract');
return attestorGroupPubKey;
} catch (error) {
throw new EthereumError(`Could not fetch Attestor Public Key: ${error}`);
}
}

export async function getContractVaults(
dlcManagerContract: Contract,
amount: number = 50
): Promise<RawVault[]> {
try {
let totalFetched = 0;
const allVaults: RawVault[] = [];

let shouldContinue = true;
while (shouldContinue) {
const fetchedVaults: RawVault[] = await dlcManagerContract.getAllDLCs(
totalFetched,
totalFetched + amount
);

allVaults.push(...fetchedVaults);

totalFetched += amount;
shouldContinue = fetchedVaults.length === amount;
}

return allVaults;
} catch (error) {
throw new EthereumError(`Could not fetch All Vaults: ${error}`);
}
}

export async function getAllAddressVaults(
dlcManagerContract: Contract,
ethereumAddress: string
): Promise<RawVault[]> {
try {
return await dlcManagerContract.getAllVaultsForAddress(ethereumAddress);
} catch (error) {
throw new EthereumError(`Could not fetch User Vaults: ${error}`);
}
}

export async function getRawVault(
dlcManagerContract: Contract,
vaultUUID: string
): Promise<RawVault> {
try {
const vault: RawVault = await dlcManagerContract.getVault(vaultUUID);
if (!vault) throw new EthereumError('Vault not found');
return vault;
} catch (error) {
throw new EthereumError(`Could not fetch Vault: ${error}`);
}
}

export async function setupVault(dlcManagerContract: Contract): Promise<any | undefined> {
try {
await dlcManagerContract.callStatic.setupVault();
const transaction = await dlcManagerContract.setupVault();
return await transaction.wait();
} catch (error) {
throw new EthereumError(`Could not Setup Vault: ${error}`);
}
}

export async function withdraw(
dlcManagerContract: Contract,
vaultUUID: string,
withdrawAmount: bigint
) {
try {
await dlcManagerContract.callStatic.withdraw(vaultUUID, withdrawAmount);
const transaction = await dlcManagerContract.withdraw(vaultUUID, withdrawAmount);
return await transaction.wait();
} catch (error) {
throw new EthereumError(`Could not Withdraw: ${error}`);
}
}

export async function getAddressDLCBTCBalance(
dlcBTCContract: Contract,
ethereumAddress: string
): Promise<number | undefined> {
try {
const ethereumAddressBalance = await dlcBTCContract.balanceOf(ethereumAddress);
return ethereumAddressBalance.toNumber();
} catch (error) {
throw new EthereumError(`Could not fetch dlcBTC balance: ${error}`);
}
}

export async function getDLCBTCTotalSupply(dlcBTCContract: Contract): Promise<number> {
try {
const totalSupply = await dlcBTCContract.totalSupply();
return totalSupply.toNumber();
} catch (error: any) {
throw new EthereumError(`Could not fetch Total Supply: ${error}`);
}
}
7 changes: 1 addition & 6 deletions src/functions/ethereum/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1 @@
import {
fetchEthereumDeploymentPlan,
fetchEthereumDeploymentPlansByNetwork,
} from '../ethereum/ethereum-functions.js';

export { fetchEthereumDeploymentPlan, fetchEthereumDeploymentPlansByNetwork };
export * from './ethereum-functions.js';
2 changes: 0 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ import { LedgerDLCHandler } from './dlc-handlers/ledger-dlc-handler.js';
import { PrivateKeyDLCHandler } from './dlc-handlers/private-key-dlc-handler.js';
import { SoftwareWalletDLCHandler } from './dlc-handlers/software-wallet-dlc-handler.js';
import { EthereumHandler } from './network-handlers/ethereum-handler.js';
import { ReadOnlyEthereumHandler } from './network-handlers/read-only-ethereum-handler.js';
import { ProofOfReserveHandler } from './proof-of-reserve-handlers/proof-of-reserve-handler.js';

export {
PrivateKeyDLCHandler,
LedgerDLCHandler,
SoftwareWalletDLCHandler,
EthereumHandler,
ReadOnlyEthereumHandler,
ProofOfReserveHandler,
};
7 changes: 7 additions & 0 deletions src/models/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ export class EthereumError extends Error {
}
}

export class EthereumHandlerError extends Error {
constructor(message: string) {
super(message);
this.name = 'EthereumHandlerError';
}
}

export class BitcoinError extends Error {
constructor(message: string) {
super(message);
Expand Down
9 changes: 9 additions & 0 deletions src/models/ethereum-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface EthereumNetwork {
export enum EthereumNetworkID {
ArbitrumSepolia = '421614',
Arbitrum = '42161',
Hardhat = '31337',
}

export enum VaultState {
Expand Down Expand Up @@ -51,6 +52,14 @@ export interface EthereumDeploymentPlan {
contract: EthereumContract;
}

export interface DetailedEvent {
from: string;
to: string;
value: number;
timestamp: number;
txHash: string;
}

export interface DLCEthereumContracts {
dlcManagerContract: Contract;
dlcBTCContract: Contract;
Expand Down
Loading
Loading