Skip to content

Commit

Permalink
feat: remaining packages for api
Browse files Browse the repository at this point in the history
  • Loading branch information
janniks committed Mar 7, 2024
1 parent 0ae858c commit e3e5761
Show file tree
Hide file tree
Showing 14 changed files with 331 additions and 244 deletions.
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"dependencies": {
"@stacks/common": "^6.10.0",
"@stacks/network": "^6.11.3",
"@stacks/stacks-blockchain-api-types": "^0.61.0",
"@stacks/transactions": "^6.9.0"
},
"devDependencies": {
Expand Down
137 changes: 109 additions & 28 deletions packages/api/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ import {
networkFrom,
} from '@stacks/network';
import {
BurnchainRewardListResponse,
BurnchainRewardSlotHolderListResponse,
BurnchainRewardsTotal,
} from '@stacks/stacks-blockchain-api-types';
import {
Cl,
ClarityAbi,
FeeEstimation,
StacksTransaction,
Expand All @@ -17,6 +23,14 @@ import {
getAbi,
getNonce,
} from '@stacks/transactions';
import {
BaseErrorResponse,
ExtendedAccountBalances,
PaginationOptions,
V1InfoBlockTimesResponse,
V2CoreInfoResponse as V2InfoResponse,
V2PoxInfoResponse,
} from './types';

export class StacksNodeApi {
// TODO
Expand Down Expand Up @@ -87,39 +101,106 @@ export class StacksNodeApi {

/**
* Fetch a contract's ABI
* @param contractAddress - The contracts address
* @param contractName - The contracts name
* @returns A promise that resolves to a ClarityAbi if the operation succeeds
*/
getAbi = async (contractAddress: string, contractName: string): Promise<ClarityAbi> => {
getAbi = async (contract: `${string}.${string}`): Promise<ClarityAbi> => {
const [contractAddress, contractName] = contract.split('.');
return getAbi({ contractAddress, contractName, api: this });
};

// todo: migrate to new api pattern
getNameInfo(fullyQualifiedName: string) {
/*
TODO: Update to v2 API URL for name lookups
*/
const nameLookupURL = `${this.bnsLookupUrl}/v1/names/${fullyQualifiedName}`;
return this.fetch(nameLookupURL)
.then((resp: any) => {
if (resp.status === 404) {
throw new Error('Name not found');
} else if (resp.status !== 200) {
throw new Error(`Bad response status: ${resp.status}`);
} else {
return resp.json();
}
})
.then((nameInfo: any) => {
// the returned address _should_ be in the correct network ---
// stacks node gets into trouble because it tries to coerce back to mainnet
// and the regtest transaction generation libraries want to use testnet addresses
if (nameInfo.address) {
return Object.assign({}, nameInfo, { address: nameInfo.address });
} else {
return nameInfo;
}
/** Get stacks node info */
getInfo(): Promise<V2InfoResponse> {
return this.fetch(`${this.url}/v2/info`).then(res => res.json());
}

/** Get stacks node pox info */
getPoxInfo(): Promise<V2PoxInfoResponse> {
return this.fetch(`${this.url}/v2/pox`).then(res => res.json());
}

/** Get stacks node target block time */
async getTargetBlockTime() {
const res = await this.fetch(`${this.url}/extended/v1/info/network_block_times`).then(
(res: any): V1InfoBlockTimesResponse => res.json()
);

if (this.isMainnet()) return res.mainnet.target_block_time;
return res.testnet.target_block_time;
}

/** Get account status */
async getAccountInfo(address: string) {
// todo: add types for response
return this.fetch(`${this.url}/v2/accounts/${address}?proof=0`)
.then(res => res.json())
.then(json => {
json.balance = BigInt(json.balance);
json.locked = BigInt(json.locked);
return json;
});
}

/** Get extended account balances */
async getExtendedAccountBalances(address: string): Promise<ExtendedAccountBalances> {
return this.fetch(`${this.url}/extended/v1/address/${address}/balances`)
.then(res => res.json())
.then(json => {
json.stx.balance = BigInt(json.stx.balance);
json.stx.total_sent = BigInt(json.stx.total_sent);
json.stx.total_received = BigInt(json.stx.total_received);
json.stx.locked = BigInt(json.stx.locked);
return json;
});
}

/** Get the total BTC stacking rewards total for an address */
async getExtendedBtcRewardsTotal(
/** BTC or STX address */
address: string
): Promise<BurnchainRewardsTotal | BaseErrorResponse> {
return this.fetch(`${this.url}/extended/v1/burnchain/rewards/${address}/total`)
.then(res => res.json())
.then(json => {
json.reward_amount = BigInt(json.reward_amount);
return json;
});
}

/** Get paginated BTC stacking rewards total for an address */
async getExtendedBtcRewards(
/** BTC or STX address */
address: string,
options?: PaginationOptions
): Promise<BurnchainRewardListResponse | BaseErrorResponse> {
let url = `${this.url}/extended/v1/burnchain/rewards/${address}`;
if (options) url += `?limit=${options.limit}&offset=${options.offset}`;

return this.fetch(url).then(res => res.json());
}

/** Get BTC reward holders for the an address */
async getExtendedBtcRewardHolders(
/** BTC or STX address */
address: string,
options?: PaginationOptions
): Promise<BurnchainRewardSlotHolderListResponse | BaseErrorResponse> {
let url = `${this.url}/extended/v1/burnchain/reward_slot_holders/${address}`;
if (options) url += `?limit=${options.limit}&offset=${options.offset}`;

return this.fetch(url).then(res => res.json());
}

/** Gets the value of a data-var if it exists in the given contract */
async getDataVar(contract: `${string}.${string}`, dataVarName: string) {
// todo: (contractAddress: string, contractName: string, dataVarName: string) overload?
// todo: cleanup address/contract identifies types
const contractPath = contract.replace('.', '/');
const url = `${this.url}/v2/data_var/${contractPath}/${dataVarName}?proof=0`;
return this.fetch(url)
.then(res => res.json())
.then(json => ({
value: Cl.deserialize(json.value),
raw: json.data as string,
}));
}
}
1 change: 1 addition & 0 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './api';
export * from './types';
91 changes: 91 additions & 0 deletions packages/api/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
export interface V2CoreInfoResponse {
burn_block_height: number;
stable_pox_consensus: string;
}

export interface CycleInfoResponse {
id: number;
min_threshold_ustx: number;
stacked_ustx: number;
is_pox_active: boolean;
}

export interface ContractVersionResponse {
contract_id: `${string}.${string}`;
activation_burnchain_block_height: number;
first_reward_cycle_id: number;
}

export interface V2PoxInfoResponse {
contract_id: string;
contract_versions?: ContractVersionResponse[];
current_burnchain_block_height?: number;
first_burnchain_block_height: number;
min_amount_ustx: string;
next_reward_cycle_in: number;
prepare_cycle_length: number;
prepare_phase_block_length: number;
rejection_fraction: number;
rejection_votes_left_required: number;
reward_cycle_id: number;
reward_cycle_length: number;
reward_phase_block_length: number;
reward_slots: number;
current_cycle: CycleInfoResponse;
next_cycle: CycleInfoResponse & {
min_increment_ustx: number;
prepare_phase_start_block_height: number;
blocks_until_prepare_phase: number;
reward_phase_start_block_height: number;
blocks_until_reward_phase: number;
ustx_until_pox_rejection: number;
};
}

export interface V1InfoBlockTimesResponse {
mainnet: {
target_block_time: number;
};
testnet: {
target_block_time: number;
};
}

export interface ExtendedAccountBalancesResponse {
stx: {
balance: string;
total_sent: string;
total_received: string;
locked: string;
lock_tx_id: string;
lock_height: number;
burnchain_lock_height: number;
burnchain_unlock_height: number;
};
fungible_tokens: any;
non_fungible_tokens: any;
}

export interface ExtendedAccountBalances {
stx: {
balance: bigint;
total_sent: bigint;
total_received: bigint;
locked: bigint;
lock_tx_id: string;
lock_height: number;
burnchain_lock_height: number;
burnchain_unlock_height: number;
};
fungible_tokens: any;
non_fungible_tokens: any;
}

export interface PaginationOptions {
limit: number;
offset: number;
}

export interface BaseErrorResponse {
error: string;
}
4 changes: 2 additions & 2 deletions packages/common/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -629,8 +629,8 @@ export function concatArray(elements: (Uint8Array | number[] | number)[]) {
* Better `instanceof` check for types in different environments
* @ignore
*/
export function isInstance(object: any, type: any) {
return object instanceof type || object?.constructor?.name?.toLowerCase() === type.name;
export function isInstance<T>(object: any, clazz: { new (...args: any[]): T }): object is T {
return object instanceof clazz || object?.constructor?.name?.toLowerCase() === clazz.name;
}

/**
Expand Down
1 change: 1 addition & 0 deletions packages/encryption/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
},
"devDependencies": {
"@peculiar/webcrypto": "^1.1.6",
"@stacks/network": "^6.11.3",
"@stacks/transactions": "^6.11.3",
"@types/bs58check": "^2.1.0",
"@types/elliptic": "^6.4.12",
Expand Down
3 changes: 2 additions & 1 deletion packages/encryption/tests/messageSignature.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { bytesToHex, concatBytes, equals, utf8ToBytes } from '@stacks/common';
import { getAddressFromPublicKey, TransactionVersion } from '@stacks/transactions';
import { TransactionVersion } from '@stacks/network';
import { getAddressFromPublicKey } from '@stacks/transactions';
import { verifyMessageSignatureRsv } from '../src/ec';
import { decodeMessage, encodeMessage, hashMessage } from '../src/messageSignature';

Expand Down
1 change: 1 addition & 0 deletions packages/stacking/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
},
"dependencies": {
"@scure/base": "1.1.1",
"@stacks/api": "^6.11.3",
"@stacks/common": "^6.10.0",
"@stacks/encryption": "^6.11.3",
"@stacks/network": "^6.11.3",
Expand Down
Loading

0 comments on commit e3e5761

Please sign in to comment.