Skip to content
Draft
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 .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@
"console": "integratedTerminal",
"sourceMaps": true,
"internalConsoleOptions": "openOnSessionStart"
}
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { Injectable } from '@nestjs/common';
import { ModuleEntity } from '../shared/modules/module.entity';
// import { ModuleEntity } from '../shared/modules/module.entity';
import { WorkflowInstanceEntity } from 'libs/shared/src/workflows/entities/instance.entity';
import { Step } from 'libs/shared/src/workflows/entities/step.entity';
import { DexService } from '../dex/dex.service';
// import { DividentsService } from "../dividents/services/dividents.service";
import { SnapshotBuilderService } from '../snapshots/snapshot-builder.service';
// import { SnapshotBuilderService } from '../snapshots/snapshot-builder.service';
import { SnapshotModuleEntry } from '../snapshots/snapshots.entry';
import { StakingService } from '../staking/staking.service';

@Injectable()
export class ModulesManagerService {
constructor(
private readonly dexService: DexService,
private readonly snapshotModuleEntry: SnapshotModuleEntry,
private readonly stakingService: StakingService,
) {}

async executeModule(instance: WorkflowInstanceEntity, step: Step) {
Expand All @@ -23,6 +25,12 @@ export class ModulesManagerService {
await this.dexService.swap(dexArguments, instance);
console.log(`module ${step.module} finished call ${step.method}`);
break;
case 'staking':
console.log(`using module ${step.module} for method ${step.method}`);
const stakingArguments: any = step.arguments;
await this.stakingService.stake(stakingArguments, instance);
console.log(`module ${step.module} finished call ${step.method}`);
break;
case 'dividents':
console.log(`using module ${step.module} for method ${step.method}`);
// const dividentsArguments: any = step.arguments;
Expand Down
3 changes: 2 additions & 1 deletion apps/ensemble-engine/src/modules/manager/modules.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { DividentsModule } from '../dividents/dividents.module';
import { ModulesManagerService } from './modules-manager.service';
import { DexModule } from '../dex/dex.module';
import { SnapshotsModule } from '../snapshots/snapshots.module';
import { StakingModule } from '../staking/staking.module';

@Module({
imports: [DividentsModule, DexModule, SnapshotsModule],
imports: [DividentsModule, DexModule, SnapshotsModule, StakingModule],
providers: [ModulesManagerService],
exports: [ModulesManagerService],
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export class CreateStakingDto {
avaxPublicUrl: string;
P_CHAIN_ADDRESS: string;
privateKey: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateStakingDto } from './create-staking.dto';

export class UpdateStakingDto extends PartialType(CreateStakingDto) {
id: number;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class Staking {}
11 changes: 11 additions & 0 deletions apps/ensemble-engine/src/modules/staking/staking.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { StakingService } from './staking.service';
import { WalletsModule } from 'apps/ensemble-service/src/wallets/wallets.module';

@Module({
imports: [WalletsModule],
controllers: [],
providers: [StakingService],
exports: [StakingService],
})
export class StakingModule {}
88 changes: 88 additions & 0 deletions apps/ensemble-engine/src/modules/staking/staking.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { Injectable } from '@nestjs/common';
import { CreateStakingDto } from './dto/create-staking.dto';
import { UpdateStakingDto } from './dto/update-staking.dto';
import { Staking } from './entities/staking.entity';

import { networkIDs } from '@avalabs/avalanchejs';
import { addTxSignatures } from '@avalabs/avalanchejs';
import { utils } from '@avalabs/avalanchejs';
import { Context } from '@avalabs/avalanchejs';
import { pvm } from '@avalabs/avalanchejs';
import { WorkflowInstanceEntity } from 'libs/shared/src/workflows/entities/instance.entity';
import { WalletsService } from 'libs/shared/src/wallets/wallets.service';


@Injectable()
export class StakingService {
private readonly stakings: Staking[] = [];

constructor(private readonly walletsService: WalletsService) {
console.log('StakingService created');
}
create(createStakingDto: CreateStakingDto) {
// TODO: Implement staking creation logic
return 'This action adds a new staking';
}

findAll() {
return this.stakings;
}

findOne(id: number) {
// TODO: Implement find one staking logic
return `This action returns a #${id} staking`;
}

update(id: number, updateStakingDto: UpdateStakingDto) {
// TODO: Implement update staking logic
return `This action updates a #${id} staking`;
}

remove(id: number) {
// TODO: Implement remove staking logic
return `This action removes a #${id} staking`;
}

// TODO: Implement staking with AVAX logic
async stake(createStakingDto: CreateStakingDto, instance: WorkflowInstanceEntity) {
console.log('Staking DTO:', createStakingDto);
const pChainAddress = createStakingDto.P_CHAIN_ADDRESS;
const avaxPublicUrl = "https://api.avax-test.network"
if (!pChainAddress) {
throw new Error('Missing staking parameters.');
}

const walletAddress = instance.getWalletAddress();
const walletData = await this.walletsService.findOne(walletAddress, true);
const { privateKey } = walletData;
const pvmapi = new pvm.PVMApi(avaxPublicUrl);
const { utxos } = await pvmapi.getUTXOs({ addresses: [pChainAddress] });
const context = await Context.getContextFromURI(avaxPublicUrl);
const startTime = await new pvm.PVMApi().getTimestamp();
const startDate = new Date(startTime.timestamp);
const start = BigInt(startDate.getTime() / 1000);
const endTime = new Date(startTime.timestamp);
endTime.setDate(endTime.getDate() + 2);
const end = BigInt(endTime.getTime() / 1000);
const nodeID = 'NodeID-3JPvbn4J4TxpUHwe8giH7HK1uzQnNUPYJ';

const tx = pvm.newAddPermissionlessDelegatorTx(
context,
utxos,
[utils.bech32ToBytes(pChainAddress)],
nodeID,
networkIDs.PrimaryNetworkID.toString(),
start,
end,
BigInt(1e9),
[utils.bech32ToBytes(pChainAddress)],
);

await addTxSignatures({
unsignedTx: tx,
privateKeys: [utils.hexToBuffer(privateKey)],
});

return pvmapi.issueSignedTx(tx.getSignedTx());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions apps/ensemble-engine/src/modules/trading/trading.entry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions apps/ensemble-engine/src/modules/trading/trading.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export class WorkflowProcessorService {
}
const instanceEntity = new WorkflowInstanceEntity(
instanceDoc.id,
instanceDoc.workflow.toJSON(),
instanceDoc.workflow.toObject(),
instanceDoc.status,
instanceDoc.currentStepIndex,
instanceDoc.triggerSnapshots,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

70 changes: 70 additions & 0 deletions examples/p-chain/delegate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { networkIDs } from '@avalabs/avalanchejs';
import { addTxSignatures } from '@avalabs/avalanchejs';
import { utils } from '@avalabs/avalanchejs';
import { Context } from '@avalabs/avalanchejs';
import { pvm } from '@avalabs/avalanchejs';
import { config } from 'dotenv';

config();

const pvmapi = new pvm.PVMApi(process.env.AVAX_PUBLIC_URL);
const P_CHAIN_ADDRESS = process.env.P_CHAIN_ADDRESS;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const NODE_ID = process.env.NODE_ID;
console.log(process.env.AVAX_PUBLIC_URL, P_CHAIN_ADDRESS, PRIVATE_KEY);

const main = async () => {
if (!P_CHAIN_ADDRESS || !PRIVATE_KEY) {
throw new Error('Missing environment variable(s).');
}


let { utxos } = await pvmapi.getUTXOs({ addresses: [P_CHAIN_ADDRESS] });
if (utxos.length > 0) {
utxos = utxos.slice(1);
}
const context = await Context.getContextFromURI(process.env.AVAX_PUBLIC_URL);
const startTime = await new pvm.PVMApi().getTimestamp();
const startDate = new Date(startTime.timestamp);
const start = BigInt(startDate.getTime() / 1000);
const endTime = new Date(startTime.timestamp);
endTime.setDate(endTime.getDate() + 2);
const end = BigInt(endTime.getTime() / 1000);
const nodeID = NODE_ID;
const amount = BigInt(1e17);
console.log('Arguments:');
console.log('context:', context);
console.log('utxos:', utxos);
console.log('P_CHAIN_ADDRESS:', P_CHAIN_ADDRESS);
console.log('nodeID:', nodeID);
console.log('networkID:', networkIDs.PrimaryNetworkID.toString());
console.log('start:', start);
console.log('end:', end);
console.log('stake amount:', amount);
console.log('privateKey:', PRIVATE_KEY);

// const balance = await pvmapi.getBalance(P_CHAIN_ADDRESS);
// console.log('Current balance:', balance.balance);


const tx = pvm.newAddPermissionlessDelegatorTx(
context,
utxos,
[utils.bech32ToBytes(P_CHAIN_ADDRESS)],
nodeID,
networkIDs.PrimaryNetworkID.toString(),
start,
end,
amount,
[utils.bech32ToBytes(P_CHAIN_ADDRESS)],
);

await addTxSignatures({
unsignedTx: tx,
privateKeys: [utils.hexToBuffer(PRIVATE_KEY)],
});

return pvmapi.issueSignedTx(tx.getSignedTx());
};

main().then(console.log);
3 changes: 0 additions & 3 deletions libs/shared/src/workflows/circle/circle.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ export class CircleService {
private client: ReturnType<typeof initiateDeveloperControlledWalletsClient>;

constructor() {
console.log(
`initializing circle client with api key ${process.env.CIRCLE_API_KEY} and entity secret ${process.env.CIRCLE_ENTITY_SECRET}`,
);
this.client = initiateDeveloperControlledWalletsClient({
apiKey: process.env.CIRCLE_API_KEY,
entitySecret: process.env.CIRCLE_ENTITY_SECRET,
Expand Down
2 changes: 1 addition & 1 deletion libs/shared/src/workflows/services/instances.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export class WorkflowInstancesService {
console.log(
`Instance ${instance.id} has completed all steps. Setting status to completed.`,
);
instance.status = 'completed';
// instance.status = 'completed';
instance.currentStepIndex = 0;
instance.completedAt = new Date();
}
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@
"start:engine:debug": "nest start --debug --watch ensemble-engine",
"start:service:dev": "nest start --watch",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"example": "NODE_OPTIONS='--loader ts-node/esm' ts-node examples/p-chain/delegate.ts",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./apps/ensemble-service/test/jest-e2e.json"
},
"dependencies": {
"@avalabs/avalanchejs": "^4.0.5",
"@circle-fin/developer-controlled-wallets": "^4.5.1",
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.2.3",
Expand All @@ -38,7 +40,7 @@
"@nestjs/schedule": "^4.1.0",
"@uniswap/router-sdk": "^1.11.1",
"@uniswap/sdk-core": "^5.3.1",
"@uniswap/universal-router-sdk": "^3.0.2",
"@uniswap/universal-router-sdk": "3.0.2",
"@uniswap/v2-sdk": "^4.4.1",
"@uniswap/v3-sdk": "^3.13.1",
"@uniswap/v4-sdk": "^1.0.0",
Expand Down
Loading