Skip to content

Commit

Permalink
feat: Add affiliates queries and transaction (#259)
Browse files Browse the repository at this point in the history
  • Loading branch information
rosepuppy authored Oct 1, 2024
1 parent 120b03f commit 781a620
Show file tree
Hide file tree
Showing 7 changed files with 990 additions and 37 deletions.
895 changes: 868 additions & 27 deletions v4-client-js/__native__/__ios__/v4-native-client.js

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions v4-client-js/src/clients/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ export const TYPE_URL_MSG_WITHDRAW_FROM_SUBACCOUNT =
'/dydxprotocol.sending.MsgWithdrawFromSubaccount';
export const TYPE_URL_MSG_DEPOSIT_TO_SUBACCOUNT = '/dydxprotocol.sending.MsgDepositToSubaccount';

// x/affiliates
export const TYPE_URL_MSG_REGISTER_AFFILIATE = '/dydxprotocol.affiliates.MsgRegisterAffiliate';

// x/vault
export const TYPE_URL_MSG_DEPOSIT_TO_MEGAVAULT = '/dydxprotocol.vault.MsgDepositToMegavault';
export const TYPE_URL_MSG_WITHDRAW_FROM_MEGAVAULT = '/dydxprotocol.vault.MsgWithdrawFromMegavault';
Expand Down
6 changes: 6 additions & 0 deletions v4-client-js/src/clients/lib/registry.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { GeneratedType, Registry } from '@cosmjs/proto-signing';
import { defaultRegistryTypes } from '@cosmjs/stargate';
import { MsgRegisterAffiliate } from '@dydxprotocol/v4-proto/src/codegen/dydxprotocol/affiliates/tx';
import {
MsgPlaceOrder,
MsgCancelOrder,
Expand Down Expand Up @@ -34,6 +35,7 @@ import {
TYPE_URL_BATCH_CANCEL,
TYPE_URL_MSG_DEPOSIT_TO_MEGAVAULT,
TYPE_URL_MSG_WITHDRAW_FROM_MEGAVAULT,
TYPE_URL_MSG_REGISTER_AFFILIATE,
} from '../constants';

export const registry: ReadonlyArray<[string, GeneratedType]> = [];
Expand All @@ -58,11 +60,15 @@ export function generateRegistry(): Registry {
// vaults
[TYPE_URL_MSG_DEPOSIT_TO_MEGAVAULT, MsgDepositToMegavault as GeneratedType],
[TYPE_URL_MSG_WITHDRAW_FROM_MEGAVAULT, MsgWithdrawFromMegavault as GeneratedType],

// sending
[TYPE_URL_MSG_CREATE_TRANSFER, MsgCreateTransfer as GeneratedType],
[TYPE_URL_MSG_WITHDRAW_FROM_SUBACCOUNT, MsgWithdrawFromSubaccount as GeneratedType],
[TYPE_URL_MSG_DEPOSIT_TO_SUBACCOUNT, MsgDepositToSubaccount as GeneratedType],

// affiliates
[TYPE_URL_MSG_REGISTER_AFFILIATE, MsgRegisterAffiliate as GeneratedType],

// default types
...defaultRegistryTypes,
]);
Expand Down
15 changes: 15 additions & 0 deletions v4-client-js/src/clients/modules/composer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
MsgDelegate,
MsgUndelegate,
} from '@dydxprotocol/v4-proto/src/codegen/cosmos/staking/v1beta1/tx';
import { MsgRegisterAffiliate } from '@dydxprotocol/v4-proto/src/codegen/dydxprotocol/affiliates/tx';
import { ClobPair_Status } from '@dydxprotocol/v4-proto/src/codegen/dydxprotocol/clob/clob_pair';
import {
MsgBatchCancel,
Expand Down Expand Up @@ -47,6 +48,7 @@ import {
TYPE_URL_MSG_UNDELEGATE,
TYPE_URL_MSG_WITHDRAW_DELEGATOR_REWARD,
TYPE_URL_BATCH_CANCEL,
TYPE_URL_MSG_REGISTER_AFFILIATE,
TYPE_URL_MSG_DEPOSIT_TO_MEGAVAULT,
TYPE_URL_MSG_WITHDRAW_FROM_MEGAVAULT,
} from '../constants';
Expand Down Expand Up @@ -536,6 +538,19 @@ export class Composer {
};
}

// ------------ x/affiliates ------------
public composeMsgRegisterAffiliate(referee: string, affiliate: string): EncodeObject {
const msg: MsgRegisterAffiliate = {
referee,
affiliate,
};

return {
typeUrl: TYPE_URL_MSG_REGISTER_AFFILIATE,
value: msg,
};
}

// ------------ util ------------
public validateGoodTilBlockAndTime(
orderFlags: number,
Expand Down
51 changes: 51 additions & 0 deletions v4-client-js/src/clients/modules/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { bigIntToBytes } from '../../lib/helpers';
import { PAGE_REQUEST } from '../constants';
import { UnexpectedClientError } from '../lib/errors';
import {
AffiliateModule,
BridgeModule,
ClobModule,
DistributionModule,
Expand Down Expand Up @@ -559,6 +560,56 @@ export class Get {
return VaultModule.QueryMegavaultWithdrawalInfoResponse.decode(data);
}

async getAffiliateInfo(address: string): Promise<AffiliateModule.AffiliateInfoResponse> {
const requestData = Uint8Array.from(
AffiliateModule.AffiliateInfoRequest.encode({
address,
}).finish(),
);

const data = await this.sendQuery('/dydxprotocol.affiliates.Query/AffiliateInfo', requestData);

return AffiliateModule.AffiliateInfoResponse.decode(data);
}

async getReferredBy(address: string): Promise<AffiliateModule.ReferredByResponse> {
const requestData = Uint8Array.from(
AffiliateModule.ReferredByRequest.encode({
address,
}).finish(),
);

const data = await this.sendQuery('/dydxprotocol.affiliates.Query/ReferredBy', requestData);

return AffiliateModule.ReferredByResponse.decode(data);
}

async getAllAffiliateTiers(): Promise<AffiliateModule.AllAffiliateTiersResponse> {
const requestData = Uint8Array.from(
AffiliateModule.AllAffiliateTiersRequest.encode({}).finish(),
);

const data = await this.sendQuery(
'/dydxprotocol.affiliates.Query/AllAffiliateTiers',
requestData,
);

return AffiliateModule.AllAffiliateTiersResponse.decode(data);
}

async getAffiliateWhitelist(): Promise<AffiliateModule.AffiliateWhitelistResponse> {
const requestData = Uint8Array.from(
AffiliateModule.AffiliateWhitelistRequest.encode({}).finish(),
);

const data = await this.sendQuery(
'/dydxprotocol.affiliates.Query/AffiliateWhitelist',
requestData,
);

return AffiliateModule.AffiliateWhitelistResponse.decode(data);
}

private async sendQuery(requestUrl: string, requestData: Uint8Array): Promise<Uint8Array> {
// eslint-disable-next-line max-len
const resp: QueryAbciResponse = await this.stargateQueryClient.queryAbci(
Expand Down
56 changes: 46 additions & 10 deletions v4-client-js/src/clients/modules/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,13 @@ export class Post {
public useTimestampNonce: boolean = false;
private accountNumberCache: Map<string, Account> = new Map();

constructor(get: Get, chainId: string, denoms: DenomConfig, defaultClientMemo?: string, useTimestampNonce?: boolean) {
constructor(
get: Get,
chainId: string,
denoms: DenomConfig,
defaultClientMemo?: string,
useTimestampNonce?: boolean,
) {
this.get = get;
this.chainId = chainId;
this.registry = generateRegistry();
Expand Down Expand Up @@ -129,13 +135,7 @@ export class Post {
sequence = msgsAndAccount[1].sequence;
}

return this.simulateTransaction(
wallet.pubKey!,
sequence,
msgs,
gasPrice,
memo,
);
return this.simulateTransaction(wallet.pubKey!, sequence, msgs, gasPrice, memo);
}

/**
Expand Down Expand Up @@ -177,6 +177,7 @@ export class Post {
memo?: string,
broadcastMode?: BroadcastMode,
account?: () => Promise<Account>,
gasAdjustment: number = GAS_MULTIPLIER,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
const msgsPromise = messaging();
const accountPromise = account ? await account() : this.account(wallet.address!);
Expand All @@ -191,6 +192,7 @@ export class Post {
gasPrice,
memo ?? this.defaultClientMemo,
broadcastMode ?? this.defaultBroadcastMode(msgs),
gasAdjustment,
);
}

Expand Down Expand Up @@ -235,6 +237,7 @@ export class Post {
zeroFee: boolean,
gasPrice: GasPrice = this.getGasPrice(),
memo?: string,
gasAdjustment: number = GAS_MULTIPLIER,
): Promise<Uint8Array> {
// protocol expects timestamp nonce in UTC milliseconds, which is the unit returned by Date.now()
const sequence = this.useTimestampNonce ? Date.now() : account.sequence;
Expand All @@ -244,7 +247,14 @@ export class Post {
amount: [],
gas: '1000000',
}
: await this.simulateTransaction(wallet.pubKey!, sequence, messages, gasPrice, memo);
: await this.simulateTransaction(
wallet.pubKey!,
sequence,
messages,
gasPrice,
memo,
gasAdjustment,
);

const txOptions: TransactionOptions = {
sequence,
Expand Down Expand Up @@ -286,6 +296,7 @@ export class Post {
gasPrice: GasPrice = this.getGasPrice(),
memo?: string,
broadcastMode?: BroadcastMode,
gasAdjustment: number = GAS_MULTIPLIER,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
const signedTransaction = await this.signTransaction(
wallet,
Expand All @@ -294,6 +305,7 @@ export class Post {
zeroFee,
gasPrice,
memo,
gasAdjustment,
);
return this.sendSignedTransaction(signedTransaction, broadcastMode);
}
Expand Down Expand Up @@ -326,6 +338,7 @@ export class Post {
messages: readonly EncodeObject[],
gasPrice: GasPrice = this.getGasPrice(),
memo?: string,
gasAdjustment: number = GAS_MULTIPLIER,
): Promise<StdFee> {
// Get simulated response.
const encodedMessages: Any[] = messages.map((message: EncodeObject) =>
Expand All @@ -347,7 +360,7 @@ export class Post {
const gasEstimate: number = Uint53.fromString(
simulationResponse.gasInfo.gasUsed.toString(),
).toNumber();
const fee = calculateFee(Math.floor(gasEstimate * GAS_MULTIPLIER), gasPrice);
const fee = calculateFee(Math.floor(gasEstimate * gasAdjustment), gasPrice);

// TODO(TRCL-2550): Temporary workaround before IBC denom is supported in '@cosmjs/stargate'.
// The '@cosmjs/stargate' does not support denom with '/', so currently GAS_PRICE is
Expand Down Expand Up @@ -881,4 +894,27 @@ export class Post {
): EncodeObject {
return this.composer.composeMsgWithdrawFromMegavault(...args);
}

async registerAffiliate(
subaccount: SubaccountInfo,
affiliate: string,
broadcastMode?: BroadcastMode,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
const msg = this.registerAffiliateMsg(subaccount.address, affiliate);
const gasAdjustment = 1.8;
return this.send(
subaccount.wallet,
() => Promise.resolve([msg]),
false,
undefined,
undefined,
broadcastMode,
undefined,
gasAdjustment,
);
}

registerAffiliateMsg(...args: Parameters<Composer['composeMsgRegisterAffiliate']>): EncodeObject {
return this.composer.composeMsgRegisterAffiliate(...args);
}
}
1 change: 1 addition & 0 deletions v4-client-js/src/clients/modules/proto-includes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export * as RewardsModule from '@dydxprotocol/v4-proto/src/codegen/dydxprotocol/
export * as StakingModule from '@dydxprotocol/v4-proto/src/codegen/cosmos/staking/v1beta1/query';
export * as BridgeModule from '@dydxprotocol/v4-proto/src/codegen/dydxprotocol/bridge/query';
export * as DistributionModule from '@dydxprotocol/v4-proto/src/codegen/cosmos/distribution/v1beta1/query';
export * as AffiliateModule from '@dydxprotocol/v4-proto/src/codegen/dydxprotocol/affiliates/query';
export * as VaultModule from '@dydxprotocol/v4-proto/src/codegen/dydxprotocol/vault/query';

export * from '@dydxprotocol/v4-proto/src/codegen/cosmos/base/abci/v1beta1/abci';
Expand Down

0 comments on commit 781a620

Please sign in to comment.