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

Add staking types sdk #7389

Merged
merged 4 commits into from
Jan 13, 2023
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
5 changes: 5 additions & 0 deletions .changeset/grumpy-queens-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@mysten/sui.js": minor
---

added getDelegatedStake and getValidators and validator type
67 changes: 50 additions & 17 deletions sdk/typescript/src/providers/json-rpc-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ import {
CoinMetadataStruct,
GetObjectDataResponse,
GetOwnedObjectsResponse,
DelegatedStake,
ValidatorMetaData,
} from '../types';
import {
PublicKey,
Expand All @@ -62,7 +64,7 @@ import { ApiEndpoints, Network, NETWORK_TO_API } from '../utils/api-endpoints';
import { requestSuiFromFaucet } from '../rpc/faucet-client';
import { lt } from '@suchipi/femver';
import { Base64DataBuffer } from '../serialization/base64';
import { any, is, number } from 'superstruct';
import { any, is, number, array } from 'superstruct';
import { RawMoveCall } from '../signers/txn-data-serializers/txn-data-serializer';

/**
Expand Down Expand Up @@ -582,22 +584,22 @@ export class JsonRpcProvider extends Provider {
try {
let resp;
// Serialize sigature field as: `flag || signature || pubkey`
const serialized_sig = new Uint8Array(
1 + signature.getLength() + pubkey.toBytes().length
);
serialized_sig.set([SIGNATURE_SCHEME_TO_FLAG[signatureScheme]]);
serialized_sig.set(signature.getData(), 1);
serialized_sig.set(pubkey.toBytes(), 1 + signature.getLength());

resp = await this.client.requestWithType(
'sui_executeTransactionSerializedSig',
[
txnBytes.toString(),
new Base64DataBuffer(serialized_sig).toString(),
requestType,
],
SuiExecuteTransactionResponse,
this.options.skipDataValidation
const serialized_sig = new Uint8Array(
1 + signature.getLength() + pubkey.toBytes().length
);
serialized_sig.set([SIGNATURE_SCHEME_TO_FLAG[signatureScheme]]);
serialized_sig.set(signature.getData(), 1);
serialized_sig.set(pubkey.toBytes(), 1 + signature.getLength());

resp = await this.client.requestWithType(
'sui_executeTransactionSerializedSig',
[
txnBytes.toString(),
new Base64DataBuffer(serialized_sig).toString(),
requestType,
],
SuiExecuteTransactionResponse,
this.options.skipDataValidation
);
return resp;
} catch (err) {
Expand Down Expand Up @@ -758,4 +760,35 @@ export class JsonRpcProvider extends Provider {
);
}
}

async getDelegatedStake(address: SuiAddress): Promise<DelegatedStake[]> {
try {
if (!address || !isValidSuiAddress(normalizeSuiAddress(address))) {
throw new Error('Invalid Sui address');
}
const resp = await this.client.requestWithType(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'sui_getDelegatedStakes',
[address],
array(DelegatedStake),
this.options.skipDataValidation
);
return resp;
} catch (err) {
throw new Error(`Error in getDelegatedStake: ${err}`);
}
}

async getValidators(): Promise<ValidatorMetaData[]> {
try {
const resp = await this.client.requestWithType(
'sui_getValidators',
[],
array(ValidatorMetaData),
this.options.skipDataValidation
);
return resp;
} catch (err) {
throw new Error(`Error in getValidators: ${err}`);
}
}
}
1 change: 1 addition & 0 deletions sdk/typescript/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export * from './sui-bcs';
export * from './version';
export * from './faucet';
export * from './normalized';
export * from './validator';
222 changes: 222 additions & 0 deletions sdk/typescript/src/types/validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

import {
any,
array,
boolean,
literal,
number,
object,
string,
union,
Infer,
} from 'superstruct';
import { SuiAddress } from './common';

export const ValidatorMetaData = object({
sui_address: SuiAddress,
pubkey_bytes: array(number()),
network_pubkey_bytes: array(number()),
worker_pubkey_bytes: array(number()),
proof_of_possession_bytes: array(number()),
name: array(number()),
net_address: array(number()),
consensus_address: array(number()),
worker_address: array(number()),
next_epoch_stake: number(),
next_epoch_delegation: number(),
next_epoch_gas_price: number(),
next_epoch_commission_rate: number(),
});

export type DelegatedStake = Infer<typeof DelegatedStake>;
export type ValidatorMetaData = Infer<typeof ValidatorMetaData>;
export type ValidatorsFields = Infer<typeof ValidatorsFields>;
export type Validators = Infer<typeof Validators>;
export type ActiveValidator = Infer<typeof ActiveValidator>;

// Staking
export const Id = object({
id: string(),
});

export const Balance = object({
value: number(),
});

export const StakedSui = object({
id: Id,
validator_address: SuiAddress,
pool_starting_epoch: number(),
delegation_request_epoch: number(),
principal: Balance,
sui_token_lock: union([number(), literal(null)]),
});

export const ID = object({
id: string(),
});

export const ActiveFields = object({
id: ID,
staked_sui_id: SuiAddress,
principal_sui_amount: number(),
pool_tokens: Balance,
});

export const ActiveDelegationStatus = object({
Active: ActiveFields,
});

export const DelegatedStake = object({
staked_sui: StakedSui,
delegation_status: union([literal('Pending'), ActiveDelegationStatus]),
});

export const ParametersFields = object({
max_validator_candidate_count: string(),
min_validator_stake: string(),
storage_gas_price: string(),
});

export const Parameters = object({
type: string(),
fields: ParametersFields,
});

export const StakeSubsidyFields = object({
balance: string(),
current_epoch_amount: string(),
epoch_counter: string(),
});

export const StakeSubsidy = object({
type: string(),
fields: StakeSubsidyFields,
});

export const SuiSupplyFields = object({
value: string(),
});

export const Supply = object({
type: string(),
fields: SuiSupplyFields,
});

//TODO : add type for contents
export const ValidatorReportRecordsFields = object({
contents: array(any()),
});

export const ValidatorReportRecords = object({
type: string(),
fields: ValidatorReportRecordsFields,
});

export const NextEpochValidatorFields = object({
consensus_address: array(number()),
name: array(number()),
net_address: array(number()),
network_pubkey_bytes: array(number()),
next_epoch_commission_rate: string(),
next_epoch_delegation: string(),
next_epoch_gas_price: string(),
next_epoch_stake: string(),
proof_of_possession: array(number()),
pubkey_bytes: array(number()),
sui_address: string(),
worker_address: array(number()),
worker_pubkey_bytes: array(number()),
});

export const NextEpochValidator = object({
type: string(),
fields: NextEpochValidatorFields,
});

export const ContentsFields = object({
id: ID,
size: string(),
});

export const Contents = object({
type: string(),
fields: ContentsFields,
});

export const PendingDelegationsFields = object({
contents: Contents,
});

export const Pending = object({
type: string(),
fields: PendingDelegationsFields,
});

export const DelegationStakingPoolFields = object({
delegation_token_supply: Supply,
pending_delegations: Pending,
pending_withdraws: Pending,
rewards_pool: string(),
starting_epoch: string(),
sui_balance: string(),
validator_address: string(),
});

export const DelegationStakingPool = object({
type: string(),
fields: DelegationStakingPoolFields,
});

export const ActiveValidatorFields = object({
commission_rate: string(),
delegation_staking_pool: DelegationStakingPool,
gas_price: string(),
metadata: NextEpochValidator,
pending_stake: string(),
pending_withdraw: string(),
stake_amount: string(),
});

export const ActiveValidator = object({
type: string(),
fields: ActiveValidatorFields,
});

export const ValidatorsFieldsClass = object({
active_validators: array(ActiveValidator),
next_epoch_validators: array(NextEpochValidator),
pending_delegation_switches: ValidatorReportRecords,
pending_removals: array(number()),
pending_validators: array(number()),
quorum_stake_threshold: string(),
total_delegation_stake: string(),
total_validator_stake: string(),
});

export const ValidatorsClass = object({
type: string(),
fields: ValidatorsFieldsClass,
});

export const ValidatorsFields = object({
chain_id: number(),
epoch: string(),
id: Id,
parameters: Parameters,
reference_gas_price: string(),
stake_subsidy: StakeSubsidy,
storage_fund: string(),
sui_supply: Supply,
validator_report_records: ValidatorReportRecords,
validators: ValidatorsClass,
});

export const Validators = object({
dataType: string(),
type: string(),
has_public_transfer: boolean(),
fields: ValidatorsFields,
});