Skip to content

Commit

Permalink
pre-released garden.js
Browse files Browse the repository at this point in the history
  • Loading branch information
ManiReddyt committed Oct 10, 2024
1 parent aba8d6f commit 35338b5
Show file tree
Hide file tree
Showing 63 changed files with 4,577 additions and 3,661 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@
"license": "MIT",
"scripts": {
"echo": "yarn workspaces foreach --include \"packages/*\" run echo",
"build": "yarn workspaces foreach -Atp --include \"packages/*\" run build",
"build": "yarn workspaces foreach -Atp --include \"packages/*\" --exclude \"packages/test\" run build",
"test": "vitest run",
"dev": "yarn workspaces foreach -Api -j unlimited --include \"packages/*\" run dev ",
"patch:affected": "yarn workspaces foreach -p --topological --include \"packages/*\" --since=$0 run patch",
"publish:affected": "yarn workspaces foreach -p --include \"packages/*\" --since=main npm publish"
"publish:affected": "yarn workspaces foreach -p --include \"packages/*\" --since=main --no-private npm publish --tag beta"
},
"workspaces": [
"packages/*"
],
"devDependencies": {
"@eslint/js": "^9.6.0",
"@types/chrome": "^0.0.268",
"@types/node": "^20.11.30",
"@types/node": "^22.7.4",
"eslint": "9.x",
"globals": "^15.8.0",
"ts-node": "^10.9.2",
Expand Down
9 changes: 2 additions & 7 deletions packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@gardenfi/core",
"version": "0.2.0",
"version": "0.2.0-beta.3",
"type": "module",
"files": [
"dist"
Expand Down Expand Up @@ -30,20 +30,15 @@
"@catalogfi/wallets": "^0.2.49",
"@gardenfi/orderbook": "workspace:^",
"bitcoinjs-lib": "^6.1.6",
"crypto": "^1.0.1",
"ethers": "6.8.0",
"tiny-secp256k1": "^2.2.3",
"varuint-bitcoin": "^1.1.2",
"viem": "^2.21.15",
"vite-plugin-node-polyfills": "^0.22.0"
"viem": "^2.21.15"
},
"devDependencies": {
"dotenv": "^16.3.1",
"typescript": "^5.2.2",
"vite": "^5.1.6",
"vite-plugin-dts": "^3.7.3",
"vite-plugin-top-level-await": "^1.4.1",
"vite-plugin-wasm": "^3.3.0",
"vitest": "^1.6.0"
},
"sideEffects": false
Expand Down
12 changes: 8 additions & 4 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
export { Garden } from './lib/garden/garden';
export type { IGardenJS } from './lib/garden/garden.types';
export type {
IGardenJS,
SwapParams,
TimeLocks,
} from './lib/garden/garden.types';

export { EvmRelay } from './lib/evmRelay/evmRelay';
export type { IEVMRelay } from './lib/evmRelay/evmRelay.types';

export { Order } from './lib/orderExecutor/order';
export { OrderExecutor } from './lib/orderExecutor/orderExecutor';
export type {
IOrder,
IOrderExecutor,
OrderStatus,
SwapStatus,
OrderActions,
} from './lib/orderExecutor/order.types';
} from './lib/orderExecutor/orderExecutor.types';
export {
fetchBitcoinBlockNumber,
fetchL1BlockNumber,
Expand Down
5 changes: 1 addition & 4 deletions packages/core/src/lib/evmRelay/evmRelay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from '@gardenfi/utils';
import { AtomicSwapABI } from './abi';
import { ParseSwapStatus } from '../orderExecutor/orderStatusParser';
import { SwapStatus } from '../orderExecutor/order.types';
import { SwapStatus } from '../orderExecutor/orderExecutor.types';

export class EvmRelay implements IEVMRelay {
private walletClient: WalletClient;
Expand Down Expand Up @@ -75,7 +75,6 @@ export class EvmRelay implements IEVMRelay {
this.walletClient,
);
if (approval.error) return Err(approval.error);
console.log('approval :', approval.val);

const domain = await atomicSwap.read.eip712Domain();

Expand Down Expand Up @@ -127,8 +126,6 @@ export class EvmRelay implements IEVMRelay {
}

async redeem(orderId: string, secret: string): AsyncResult<string, string> {
if (!this.walletClient.account) return Err('No account found');

try {
const auth = await this.auth.getToken();
if (auth.error) return Err(auth.error);
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/lib/garden/garden.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,6 @@ describe('garden', () => {
source: sourceWallet,
destination: destWallet,
},
secretManager,
});
console.log('execute result :', res.val);
console.log('execute error: ', res.error);
Expand Down
33 changes: 19 additions & 14 deletions packages/core/src/lib/garden/garden.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { AsyncResult, Err } from '@catalogfi/utils';
import { IGardenJS, SwapParams, TimeLocks } from './garden.types';
import { IOrderbook, isBitcoin, isEVM } from '@gardenfi/orderbook';
import { IStore, Url } from '@gardenfi/utils';
import { IOrder } from '../orderExecutor/order.types';
import { Order } from '../orderExecutor/order';
import { IOrderExecutor } from '../orderExecutor/orderExecutor.types';
import { OrderExecutor } from '../orderExecutor/orderExecutor';

export class Garden implements IGardenJS {
private secretManager: ISecretManager;
Expand Down Expand Up @@ -66,19 +66,24 @@ export class Garden implements IGardenJS {
}

async subscribeOrders(
cb: (executor: IOrder) => void,
cb: (executor: IOrderExecutor) => Promise<void>,
interval: number = 5000,
): Promise<() => void> {
return await this.orderBook.subscribeToOrders(true, interval, (order) => {
order.data.map((o) => {
const orderExecutor = new Order(
o,
this.relayURL.toString(),
this.secretManager,
this.opts,
);
cb(orderExecutor);
});
});
return await this.orderBook.subscribeToOrders(
true,
interval,
async (order) => {
for (let i = 0; i < order.data.length; i++) {
const orderExecutor = new OrderExecutor(
order.data[i],
this.relayURL.toString(),
this.secretManager,
this.opts,
);
await cb(orderExecutor);
}
},
true,
);
}
}
7 changes: 5 additions & 2 deletions packages/core/src/lib/garden/garden.types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AsyncResult } from '@catalogfi/utils';
import { Asset } from '@gardenfi/orderbook';
import { IOrder } from '../orderExecutor/order.types';
import { IOrderExecutor } from '../orderExecutor/orderExecutor.types';

export type SwapParams = {
fromAsset: Asset;
Expand Down Expand Up @@ -30,5 +30,8 @@ export interface IGardenJS {
* @param cb - Callback function to be called for each order. This callback will take orderExecutor as an argument.
* @param interval - Polling interval in milliseconds.
*/
subscribeOrders(cb: (orderExecutor: IOrder) => void, interval: number): void;
subscribeOrders(
cb: (orderExecutor: IOrderExecutor) => Promise<void>,
interval?: number,
): Promise<() => void>;
}
6 changes: 5 additions & 1 deletion packages/core/src/lib/orderExecutor/orderCache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { MatchedOrder } from '@gardenfi/orderbook';
import { IStore } from '@gardenfi/utils';
import { IOrderCache, OrderCacheAction, OrderCacheValue } from './order.types';
import {
IOrderCache,
OrderCacheAction,
OrderCacheValue,
} from './orderExecutor.types';

export class OrderCache implements IOrderCache {
private order: MatchedOrder;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { WalletClient } from 'viem';
import {
executeParams,
IOrder,
ExecuteParams,
IOrderExecutor,
IOrderCache,
OrderActions,
OrderCacheAction,
} from './order.types';
} from './orderExecutor.types';
import { IBitcoinWallet } from '@catalogfi/wallets';
import { isBitcoin, MatchedOrder } from '@gardenfi/orderbook';
import { IStore, MemoryStorage } from '@gardenfi/utils';
Expand All @@ -18,8 +18,7 @@ import { toXOnly } from '../utils';
import { ISecretManager } from '../secretManager/secretManager.types';
import { OrderCache } from './orderCache';

//orderBook will return orderExecutorInstance
export class Order implements IOrder {
export class OrderExecutor implements IOrderExecutor {
private order: MatchedOrder;
private relayURL: string;
private secretManager: ISecretManager;
Expand Down Expand Up @@ -52,6 +51,7 @@ export class Order implements IOrder {
): AsyncResult<string, string> {
const initHash = this.orderCache.get(OrderCacheAction.init);
if (initHash) return Ok(initHash.txHash);

if (isBitcoin(this.order.source_swap.chain))
return Ok('Bitcoin initiation is not automated');

Expand All @@ -68,7 +68,9 @@ export class Order implements IOrder {
secret: string,
): AsyncResult<string, string> {
const redeemHash = this.orderCache.get(OrderCacheAction.redeem);
// already redeemed
if (redeemHash) return Ok(redeemHash.txHash);

if (isBitcoin(this.order.destination_swap.chain)) {
try {
const bitcoinExecutor = await GardenHTLC.from(
Expand Down Expand Up @@ -131,11 +133,15 @@ export class Order implements IOrder {
}
}

async execute(params: executeParams) {
const { wallets } = params;

async execute(params: ExecuteParams): AsyncResult<string | void, string> {
// fetch the current block number of the source and destination chains if not provided
const { wallets } = params;
let { blockNumbers } = params;
if (!blockNumbers && !wallets)
return Err(
'Provide wallets or blockNumbers to calculate the order status.',
);

if (!blockNumbers) {
const currentBlockNumber = await this.fetchCurrentBlockNumber(wallets);
if (currentBlockNumber.error) {
Expand All @@ -152,15 +158,6 @@ export class Order implements IOrder {
);

switch (action) {
case OrderActions.Initiate:
if (isBitcoin(this.order.source_swap.chain))
return Ok('Bitcoin initiation is not automated');

return await this.init(
wallets.source as WalletClient,
blockNumbers.source,
);

case OrderActions.Redeem: {
const secret = this.secretManager.generateSecret(
Number(this.order.create_order.nonce),
Expand All @@ -169,6 +166,7 @@ export class Order implements IOrder {

return await this.redeem(wallets.destination, secret.val.secret);
}

case OrderActions.Refund:
if (!isBitcoin(this.order.source_swap.chain))
return Ok('EVM refund is automatically done by relayer service');
Expand All @@ -178,7 +176,11 @@ export class Order implements IOrder {
return Ok(Void);
}
}
private async fetchCurrentBlockNumber(wallets: executeParams['wallets']) {

private async fetchCurrentBlockNumber(wallets: ExecuteParams['wallets']) {
if (!wallets || !wallets.source || !wallets.destination)
return Err('Provide wallets to fetch the current block number');

const sourceBlockNumber = isBitcoin(this.order.source_swap.chain)
? await fetchBitcoinBlockNumber(
await (wallets.source as IBitcoinWallet).getProvider(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { AsyncResult } from '@catalogfi/utils';
import { IBitcoinWallet } from '@catalogfi/wallets';
import { WalletClient } from 'viem';
import { ISecretManager } from '../secretManager/secretManager.types';
import { MatchedOrder } from '@gardenfi/orderbook';

/**
Expand Down Expand Up @@ -141,12 +140,11 @@ export enum OrderActions {
Refund = 'Refund',
}

export type executeParams = {
export type ExecuteParams = {
wallets: {
source: IBitcoinWallet | WalletClient;
destination: IBitcoinWallet | WalletClient;
};
secretManager: ISecretManager;
blockNumbers?: {
source: number;
destination: number;
Expand All @@ -156,20 +154,13 @@ export type executeParams = {
/**
* This is a generic interface for Order. Use this interface to perform operations on the order (init, redeem, refund, execute).
*/
export interface IOrder {
export interface IOrderExecutor {
/**
* Get the order details.
* @returns MatchedOrder
*/
getOrder(): MatchedOrder;
/**
* Initialize the order.
* Deposit funds into the atomic swap contract.
*/
init(
walletClient: WalletClient,
currentBlockNumber: number,
): AsyncResult<string, string>;

/**
* Redeem the funds from the atomic swap contract.
*/
Expand All @@ -182,13 +173,12 @@ export interface IOrder {
*/
refund(wallet: IBitcoinWallet): AsyncResult<string, string>;
/**
* This will take care of order execution according to its current status, i.e., init, redeem, refund.
* This will take care of order execution according to its current status, i.e., redeem or refund.
*
* Initiate:- BTC should be done manually, EVM will be automated.
* Redeem:- Automated for both BTC and EVM.
* Refund:- Automated for BTC, EVM will be done by the relayer service automatically after expiry.
* Redeem:- Both EVM and BTC redeems are done by executor, and only BTC refund is done by executor.
* EVM refund is done automatically by the relayer service.
*/
execute(params: executeParams): AsyncResult<string | void, string>;
execute(params: ExecuteParams): AsyncResult<string | void, string>;
}

export enum OrderCacheAction {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/lib/orderExecutor/orderStatusParser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MatchedOrder } from '@gardenfi/orderbook';
import { OrderActions, OrderStatus, SwapStatus } from './order.types';
import { OrderActions, OrderStatus, SwapStatus } from './orderExecutor.types';
import { Swap } from '@gardenfi/orderbook';

/**
Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/lib/secretManager/secretManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Err, Ok, trim0x } from '@catalogfi/utils';
import { sha256, WalletClient } from 'viem';
import { ECPairFactory } from 'ecpair';
import * as ecc from 'tiny-secp256k1';
import { createHash } from 'crypto';
import { with0x } from '@gardenfi/utils';
import { ISecretManager } from './secretManager.types';

Expand Down Expand Up @@ -68,14 +67,14 @@ export class SecretManager implements ISecretManager {

const signMessage = 'Garden.fi' + nonce.toString();
const signMessageBuffer = Buffer.from(signMessage, 'utf8');
const hash = createHash('sha256').update(signMessageBuffer).digest();
const hash = sha256(signMessageBuffer);

const privKeyBuf = Buffer.from(trim0x(this.privKey), 'hex');
if (privKeyBuf.length !== 32) {
throw new Error('Invalid private key length. Expected 32 bytes.');
}
const keyPair = ECPair.fromPrivateKey(privKeyBuf);
const signature = keyPair.sign(hash);
const signature = keyPair.sign(Buffer.from(trim0x(hash), 'hex'));
return signature.toString('hex');
}
}
Loading

0 comments on commit 35338b5

Please sign in to comment.