Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@coinbase/coinbase-sdk

Package Overview
Dependencies
Maintainers
0
Versions
32
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@coinbase/coinbase-sdk - npm Package Compare versions

Comparing version 0.0.12 to 0.0.13

35

dist/client/base.d.ts

@@ -0,4 +1,19 @@

/**
* Coinbase Platform API
* This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs.
*
* The version of the OpenAPI document: 0.0.1-alpha
* Contact: yuga.cohler@coinbase.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from './configuration';
import type { AxiosInstance, RawAxiosRequestConfig } from 'axios';
export declare const BASE_PATH: string;
/**
*
* @export
*/
export declare const COLLECTION_FORMATS: {

@@ -10,2 +25,7 @@ csv: string;

};
/**
*
* @export
* @interface RequestArgs
*/
export interface RequestArgs {

@@ -15,2 +35,7 @@ url: string;

}
/**
*
* @export
* @class BaseAPI
*/
export declare class BaseAPI {

@@ -22,2 +47,8 @@ protected basePath: string;

}
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export declare class RequiredError extends Error {

@@ -33,3 +64,7 @@ field: string;

}
/**
*
* @export
*/
export declare const operationServerMap: ServerMap;
export {};
"use strict";
/* tslint:disable */
/* eslint-disable */
/**
* Coinbase Platform API
* This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs.
*
* The version of the OpenAPI document: 0.0.1-alpha
* Contact: yuga.cohler@coinbase.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -9,2 +22,6 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.BASE_PATH = "https://api.cdp.coinbase.com/platform".replace(/\/+$/, "");
/**
*
* @export
*/
exports.COLLECTION_FORMATS = {

@@ -16,2 +33,7 @@ csv: ",",

};
/**
*
* @export
* @class BaseAPI
*/
class BaseAPI {

@@ -29,2 +51,8 @@ constructor(configuration, basePath = exports.BASE_PATH, axios = axios_1.default) {

;
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
class RequiredError extends Error {

@@ -38,2 +66,6 @@ constructor(field, msg) {

exports.RequiredError = RequiredError;
/**
*
* @export
*/
exports.operationServerMap = {};

@@ -0,13 +1,65 @@

/**
* Coinbase Platform API
* This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs.
*
* The version of the OpenAPI document: 0.0.1-alpha
* Contact: yuga.cohler@coinbase.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from "./configuration";
import type { RequestArgs } from "./base";
import type { AxiosInstance, AxiosResponse } from 'axios';
/**
*
* @export
*/
export declare const DUMMY_BASE_URL = "https://example.com";
/**
*
* @throws {RequiredError}
* @export
*/
export declare const assertParamExists: (functionName: string, paramName: string, paramValue: unknown) => void;
/**
*
* @export
*/
export declare const setApiKeyToObject: (object: any, keyParamName: string, configuration?: Configuration) => Promise<void>;
/**
*
* @export
*/
export declare const setBasicAuthToObject: (object: any, configuration?: Configuration) => void;
/**
*
* @export
*/
export declare const setBearerAuthToObject: (object: any, configuration?: Configuration) => Promise<void>;
/**
*
* @export
*/
export declare const setOAuthToObject: (object: any, name: string, scopes: string[], configuration?: Configuration) => Promise<void>;
/**
*
* @export
*/
export declare const setSearchParams: (url: URL, ...objects: any[]) => void;
/**
*
* @export
*/
export declare const serializeDataIfNeeded: (value: any, requestOptions: any, configuration?: Configuration) => any;
/**
*
* @export
*/
export declare const toPathString: (url: URL) => string;
/**
*
* @export
*/
export declare const createRequestFunction: (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) => <T = unknown, R = AxiosResponse<T, any>>(axios?: AxiosInstance, basePath?: string) => Promise<R>;
"use strict";
/* tslint:disable */
/* eslint-disable */
/**
* Coinbase Platform API
* This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs.
*
* The version of the OpenAPI document: 0.0.1-alpha
* Contact: yuga.cohler@coinbase.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRequestFunction = exports.toPathString = exports.serializeDataIfNeeded = exports.setSearchParams = exports.setOAuthToObject = exports.setBearerAuthToObject = exports.setBasicAuthToObject = exports.setApiKeyToObject = exports.assertParamExists = exports.DUMMY_BASE_URL = void 0;
const base_1 = require("./base");
/**
*
* @export
*/
exports.DUMMY_BASE_URL = 'https://example.com';
/**
*
* @throws {RequiredError}
* @export
*/
const assertParamExists = function (functionName, paramName, paramValue) {

@@ -12,2 +34,6 @@ if (paramValue === null || paramValue === undefined) {

exports.assertParamExists = assertParamExists;
/**
*
* @export
*/
const setApiKeyToObject = async function (object, keyParamName, configuration) {

@@ -22,2 +48,6 @@ if (configuration && configuration.apiKey) {

exports.setApiKeyToObject = setApiKeyToObject;
/**
*
* @export
*/
const setBasicAuthToObject = function (object, configuration) {

@@ -29,2 +59,6 @@ if (configuration && (configuration.username || configuration.password)) {

exports.setBasicAuthToObject = setBasicAuthToObject;
/**
*
* @export
*/
const setBearerAuthToObject = async function (object, configuration) {

@@ -39,2 +73,6 @@ if (configuration && configuration.accessToken) {

exports.setBearerAuthToObject = setBearerAuthToObject;
/**
*
* @export
*/
const setOAuthToObject = async function (object, name, scopes, configuration) {

@@ -69,2 +107,6 @@ if (configuration && configuration.accessToken) {

}
/**
*
* @export
*/
const setSearchParams = function (url, ...objects) {

@@ -76,2 +118,6 @@ const searchParams = new URLSearchParams(url.search);

exports.setSearchParams = setSearchParams;
/**
*
* @export
*/
const serializeDataIfNeeded = function (value, requestOptions, configuration) {

@@ -111,5 +157,11 @@ const nonString = typeof value !== 'string';

}
/**
* Ponyfill for Object.entries
*/
function objectEntries(object) {
return Object.keys(object).map(key => [key, object[key]]);
}
/**
* Ponyfill for Object.fromEntries
*/
function objectFromEntries(entries) {

@@ -121,2 +173,6 @@ return [...entries].reduce((object, [key, val]) => {

}
/**
*
* @export
*/
const toPathString = function (url) {

@@ -126,2 +182,6 @@ return url.pathname + url.search + url.hash;

exports.toPathString = toPathString;
/**
*
* @export
*/
const createRequestFunction = function (axiosArgs, globalAxios, BASE_PATH, configuration) {

@@ -128,0 +188,0 @@ return (axios = globalAxios, basePath = BASE_PATH) => {

@@ -0,1 +1,12 @@

/**
* Coinbase Platform API
* This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs.
*
* The version of the OpenAPI document: 0.0.1-alpha
* Contact: yuga.cohler@coinbase.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface ConfigurationParameters {

@@ -12,12 +23,70 @@ apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>);

export declare class Configuration {
/**
* parameter for apiKey security
* @param name security name
* @memberof Configuration
*/
apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>);
/**
* parameter for basic security
*
* @type {string}
* @memberof Configuration
*/
username?: string;
/**
* parameter for basic security
*
* @type {string}
* @memberof Configuration
*/
password?: string;
/**
* parameter for oauth2 security
* @param name security name
* @param scopes oauth2 scope
* @memberof Configuration
*/
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise<string>);
/**
* override base path
*
* @type {string}
* @memberof Configuration
*/
basePath?: string;
/**
* override server index
*
* @type {number}
* @memberof Configuration
*/
serverIndex?: number;
/**
* base options for axios calls
*
* @type {any}
* @memberof Configuration
*/
baseOptions?: any;
/**
* The FormData constructor that will be used to create multipart form data
* requests. You can inject this here so that execution environments that
* do not support the FormData class can still run the generated client.
*
* @type {new () => FormData}
*/
formDataCtor?: new () => any;
constructor(param?: ConfigurationParameters);
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
isJsonMime(mime: string): boolean;
}
"use strict";
/* tslint:disable */
/* eslint-disable */
/**
* Coinbase Platform API
* This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs.
*
* The version of the OpenAPI document: 0.0.1-alpha
* Contact: yuga.cohler@coinbase.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
Object.defineProperty(exports, "__esModule", { value: true });

@@ -15,2 +28,12 @@ exports.Configuration = void 0;

}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
isJsonMime(mime) {

@@ -17,0 +40,0 @@ const jsonMime = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');

@@ -0,2 +1,13 @@

/**
* Coinbase Platform API
* This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs.
*
* The version of the OpenAPI document: 0.0.1-alpha
* Contact: yuga.cohler@coinbase.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export * from "./api";
export * from "./configuration";
"use strict";
/* tslint:disable */
/* eslint-disable */
/**
* Coinbase Platform API
* This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs.
*
* The version of the OpenAPI document: 0.0.1-alpha
* Contact: yuga.cohler@coinbase.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {

@@ -3,0 +16,0 @@ if (k2 === undefined) k2 = k;

import Decimal from "decimal.js";
import { BalanceMap } from "./balance_map";
import { FaucetTransaction } from "./faucet_transaction";
/**
* A representation of a blockchain address, which is a user-controlled account on a network.
*/
export declare class Address {
protected networkId: string;
protected id: string;
/**
* Initializes a new Address instance.
*
* @param networkId - The network id.
* @param id - The onchain address id.
*/
constructor(networkId: string, id: string);
/**
* Returns the network ID.
*
* @returns The network ID.
*/
getNetworkId(): string;
/**
* Returns the address ID.
*
* @returns The address ID.
*/
getId(): string;
/**
* Returns the list of balances for the address.
*
* @returns The map from asset ID to balance.
*/
listBalances(): Promise<BalanceMap>;
/**
* Returns the balance of the provided asset.
*
* @param assetId - The asset ID.
* @returns The balance of the asset.
*/
getBalance(assetId: string): Promise<Decimal>;
/**
* Requests faucet funds for the address.
* Only supported on testnet networks.
*
* @returns The faucet transaction object.
* @throws {InternalError} If the request does not return a transaction hash.
* @throws {Error} If the request fails.
*/
faucet(): Promise<FaucetTransaction>;
/**
* Returns a string representation of the address.
*
* @returns A string representing the address.
*/
toString(): string;
}

@@ -13,3 +13,12 @@ "use strict";

const faucet_transaction_1 = require("./faucet_transaction");
/**
* A representation of a blockchain address, which is a user-controlled account on a network.
*/
class Address {
/**
* Initializes a new Address instance.
*
* @param networkId - The network id.
* @param id - The onchain address id.
*/
constructor(networkId, id) {

@@ -19,8 +28,23 @@ this.networkId = networkId;

}
/**
* Returns the network ID.
*
* @returns The network ID.
*/
getNetworkId() {
return this.networkId;
}
/**
* Returns the address ID.
*
* @returns The address ID.
*/
getId() {
return this.id;
}
/**
* Returns the list of balances for the address.
*
* @returns The map from asset ID to balance.
*/
async listBalances() {

@@ -30,2 +54,8 @@ const response = await coinbase_1.Coinbase.apiClients.externalAddress.listExternalAddressBalances(this.getNetworkId(), this.getId());

}
/**
* Returns the balance of the provided asset.
*
* @param assetId - The asset ID.
* @returns The balance of the asset.
*/
async getBalance(assetId) {

@@ -38,2 +68,10 @@ const response = await coinbase_1.Coinbase.apiClients.externalAddress.getExternalAddressBalance(this.getNetworkId(), this.getId(), asset_1.Asset.primaryDenomination(assetId));

}
/**
* Requests faucet funds for the address.
* Only supported on testnet networks.
*
* @returns The faucet transaction object.
* @throws {InternalError} If the request does not return a transaction hash.
* @throws {Error} If the request fails.
*/
async faucet() {

@@ -43,2 +81,7 @@ const response = await coinbase_1.Coinbase.apiClients.externalAddress.requestExternalFaucetFunds(this.getNetworkId(), this.getId());

}
/**
* Returns a string representation of the address.
*
* @returns A string representing the address.
*/
toString() {

@@ -45,0 +88,0 @@ return `Address { addressId: '${this.getId()}', networkId: '${this.getNetworkId()}' }`;

@@ -7,28 +7,152 @@ import { Address } from "../address";

import { StakingReward } from "../staking_reward";
/**
* A representation of a blockchain Address, which is a user-controlled account on a Network. Addresses are used to
* send and receive Assets. An ExternalAddress is an Address that is not controlled by the developer, but is instead
* controlled by the user.
*/
export declare class ExternalAddress extends Address {
/**
* Builds a stake operation for the supplied asset. The stake operation
* may take a few minutes to complete in the case when infrastructure is spun up.
*
* @param amount - The amount of the asset to stake.
* @param assetId - The asset to stake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the stake operation.
* @returns The stake operation.
*/
buildStakeOperation(amount: Amount, assetId: string, mode?: StakeOptionsMode, options?: {
[key: string]: string;
}): Promise<StakingOperation>;
/**
* Builds an unstake operation for the supplied asset.
*
* @param amount - The amount of the asset to unstake.
* @param assetId - The asset to unstake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the unstake operation.
* @returns The unstake operation.
*/
buildUnstakeOperation(amount: Amount, assetId: string, mode?: StakeOptionsMode, options?: {
[key: string]: string;
}): Promise<StakingOperation>;
/**
* Builds a claim stake operation for the supplied asset.
*
* @param amount - The amount of the asset to claim stake.
* @param assetId - The asset to claim stake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the claim stake operation.
* @returns The claim stake operation.
*/
buildClaimStakeOperation(amount: Amount, assetId: string, mode?: StakeOptionsMode, options?: {
[key: string]: string;
}): Promise<StakingOperation>;
/**
* Get the stakeable balance for the supplied asset.
*
* @param asset_id - The asset to check the stakeable balance for.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for getting the stakeable balance.
* @returns The stakeable balance.
*/
stakeableBalance(asset_id: string, mode?: StakeOptionsMode, options?: {
[key: string]: string;
}): Promise<Decimal>;
/**
* Get the unstakeable balance for the supplied asset.
*
* @param asset_id - The asset to check the unstakeable balance for.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for getting the unstakeable balance.
* @returns The unstakeable balance.
*/
unstakeableBalance(asset_id: string, mode?: StakeOptionsMode, options?: {
[key: string]: string;
}): Promise<Decimal>;
/**
* Get the claimable balance for the supplied asset.
*
* @param asset_id - The asset to check claimable balance for.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for getting the claimable balance.
* @returns The claimable balance.
*/
claimableBalance(asset_id: string, mode?: StakeOptionsMode, options?: {
[key: string]: string;
}): Promise<Decimal>;
/**
* Lists the staking rewards for the address.
*
* @param assetId - The asset ID.
* @param startTime - The start time.
* @param endTime - The end time.
* @param format - The format to return the rewards in. (usd, native). Defaults to usd.
* @returns The staking rewards.
*/
stakingRewards(assetId: string, startTime: string, endTime: string, format?: StakingRewardFormat): Promise<StakingReward[]>;
/**
* Validate if the operation is able to stake with the supplied input.
*
* @param amount - The amount of the asset to stake.
* @param assetId - The asset to stake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the stake operation.
* @private
* @throws {Error} If the supplied input is not able to create a stake operation.
*/
private validateCanStake;
/**
* Validate if the operation is able to unstake with the supplied input.
*
* @param amount - The amount of the asset to unstake.
* @param assetId - The asset to unstake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the unstake operation.
* @private
* @throws {Error} If the supplied input is not able to create an unstake operation.
*/
private validateCanUnstake;
/**
* Validate if the operation is able to claim stake with the supplied input.
*
* @param amount - The amount of the asset to claim stake.
* @param assetId - The asset to claim stake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the claim stake operation.
* @private
* @throws {Error} If the supplied input is not able to create a claim stake operation.
*/
private validateCanClaimStake;
/**
* Get the different staking balance types for the supplied asset.
*
* @param assetId - The asset to lookup balances for.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the balance lookup.
* @private
* @returns The different balance types.
*/
private getStakingBalances;
/**
* Builds the staking operation based on the supplied input.
*
* @param amount - The amount for the staking operation.
* @param assetId - The asset for the staking operation.
* @param action - The specific action for the staking operation. e.g. stake, unstake, claim_stake
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options to build a stake operation.
* @private
* @returns The staking operation.
* @throws {Error} If the supplied input cannot build a valid staking operation.
*/
private buildStakingOperation;
/**
* Create a shallow copy of given options.
*
* @param options - The supplied options to be copied
* @private
* @returns A copy of the options.
*/
private copyOptions;
}

@@ -16,3 +16,18 @@ "use strict";

const balance_1 = require("../balance");
/**
* A representation of a blockchain Address, which is a user-controlled account on a Network. Addresses are used to
* send and receive Assets. An ExternalAddress is an Address that is not controlled by the developer, but is instead
* controlled by the user.
*/
class ExternalAddress extends address_1.Address {
/**
* Builds a stake operation for the supplied asset. The stake operation
* may take a few minutes to complete in the case when infrastructure is spun up.
*
* @param amount - The amount of the asset to stake.
* @param assetId - The asset to stake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the stake operation.
* @returns The stake operation.
*/
async buildStakeOperation(amount, assetId, mode = types_1.StakeOptionsMode.DEFAULT, options = {}) {

@@ -22,2 +37,11 @@ await this.validateCanStake(amount, assetId, mode, options);

}
/**
* Builds an unstake operation for the supplied asset.
*
* @param amount - The amount of the asset to unstake.
* @param assetId - The asset to unstake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the unstake operation.
* @returns The unstake operation.
*/
async buildUnstakeOperation(amount, assetId, mode = types_1.StakeOptionsMode.DEFAULT, options = {}) {

@@ -27,2 +51,11 @@ await this.validateCanUnstake(amount, assetId, mode, options);

}
/**
* Builds a claim stake operation for the supplied asset.
*
* @param amount - The amount of the asset to claim stake.
* @param assetId - The asset to claim stake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the claim stake operation.
* @returns The claim stake operation.
*/
async buildClaimStakeOperation(amount, assetId, mode = types_1.StakeOptionsMode.DEFAULT, options = {}) {

@@ -32,2 +65,10 @@ await this.validateCanClaimStake(amount, assetId, mode, options);

}
/**
* Get the stakeable balance for the supplied asset.
*
* @param asset_id - The asset to check the stakeable balance for.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for getting the stakeable balance.
* @returns The stakeable balance.
*/
async stakeableBalance(asset_id, mode = types_1.StakeOptionsMode.DEFAULT, options = {}) {

@@ -37,2 +78,10 @@ const balances = await this.getStakingBalances(asset_id, mode, options);

}
/**
* Get the unstakeable balance for the supplied asset.
*
* @param asset_id - The asset to check the unstakeable balance for.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for getting the unstakeable balance.
* @returns The unstakeable balance.
*/
async unstakeableBalance(asset_id, mode = types_1.StakeOptionsMode.DEFAULT, options = {}) {

@@ -42,2 +91,10 @@ const balances = await this.getStakingBalances(asset_id, mode, options);

}
/**
* Get the claimable balance for the supplied asset.
*
* @param asset_id - The asset to check claimable balance for.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for getting the claimable balance.
* @returns The claimable balance.
*/
async claimableBalance(asset_id, mode = types_1.StakeOptionsMode.DEFAULT, options = {}) {

@@ -47,5 +104,24 @@ const balances = await this.getStakingBalances(asset_id, mode, options);

}
/**
* Lists the staking rewards for the address.
*
* @param assetId - The asset ID.
* @param startTime - The start time.
* @param endTime - The end time.
* @param format - The format to return the rewards in. (usd, native). Defaults to usd.
* @returns The staking rewards.
*/
async stakingRewards(assetId, startTime, endTime, format = client_1.StakingRewardFormat.Usd) {
return staking_reward_1.StakingReward.list(coinbase_1.Coinbase.normalizeNetwork(this.getNetworkId()), assetId, [this.getId()], startTime, endTime, format);
}
/**
* Validate if the operation is able to stake with the supplied input.
*
* @param amount - The amount of the asset to stake.
* @param assetId - The asset to stake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the stake operation.
* @private
* @throws {Error} If the supplied input is not able to create a stake operation.
*/
async validateCanStake(amount, assetId, mode, options) {

@@ -57,2 +133,12 @@ const stakeableBalance = await this.stakeableBalance(assetId, mode, options);

}
/**
* Validate if the operation is able to unstake with the supplied input.
*
* @param amount - The amount of the asset to unstake.
* @param assetId - The asset to unstake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the unstake operation.
* @private
* @throws {Error} If the supplied input is not able to create an unstake operation.
*/
async validateCanUnstake(amount, assetId, mode, options) {

@@ -64,2 +150,12 @@ const unstakeableBalance = new decimal_js_1.default(await this.unstakeableBalance(assetId, mode, options));

}
/**
* Validate if the operation is able to claim stake with the supplied input.
*
* @param amount - The amount of the asset to claim stake.
* @param assetId - The asset to claim stake.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the claim stake operation.
* @private
* @throws {Error} If the supplied input is not able to create a claim stake operation.
*/
async validateCanClaimStake(amount, assetId, mode, options) {

@@ -74,2 +170,11 @@ if (assetId === "eth" && options.mode === types_1.StakeOptionsMode.NATIVE) {

}
/**
* Get the different staking balance types for the supplied asset.
*
* @param assetId - The asset to lookup balances for.
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options for the balance lookup.
* @private
* @returns The different balance types.
*/
async getStakingBalances(assetId, mode, options) {

@@ -93,2 +198,14 @@ const newOptions = this.copyOptions(options);

}
/**
* Builds the staking operation based on the supplied input.
*
* @param amount - The amount for the staking operation.
* @param assetId - The asset for the staking operation.
* @param action - The specific action for the staking operation. e.g. stake, unstake, claim_stake
* @param mode - The staking mode. Defaults to DEFAULT.
* @param options - Additional options to build a stake operation.
* @private
* @returns The staking operation.
* @throws {Error} If the supplied input cannot build a valid staking operation.
*/
async buildStakingOperation(amount, assetId, action, mode, options) {

@@ -113,2 +230,9 @@ const stakingAmount = new decimal_js_1.default(amount.toString());

}
/**
* Create a shallow copy of given options.
*
* @param options - The supplied options to be copied
* @private
* @returns A copy of the options.
*/
copyOptions(options) {

@@ -115,0 +239,0 @@ return { ...options };

101

dist/coinbase/address/wallet_address.d.ts

@@ -6,19 +6,116 @@ import { ethers } from "ethers";

import { Transfer } from "../transfer";
import { Amount, CreateTransferOptions } from "../types";
import { CreateTransferOptions, CreateTradeOptions } from "../types";
/**
* A representation of a blockchain address, which is a wallet-controlled account on a network.
*/
export declare class WalletAddress extends Address {
private model;
private key?;
/**
* Initializes a new Wallet Address instance.
*
* @param model - The address model data.
* @param key - The ethers.js SigningKey the Address uses to sign data.
* @throws {InternalError} If the address model is empty.
*/
constructor(model: AddressModel, key?: ethers.Wallet);
/**
* Returns a string representation of the wallet address.
*
* @returns A string representing the wallet address.
*/
toString(): string;
/**
* Returns the wallet ID.
*
* @returns The wallet ID.
*/
getWalletId(): string;
/**
* Sets the private key.
*
* @param key - The ethers.js SigningKey the Address uses to sign data.
* @throws {InternalError} If the private key is already set.
*/
setKey(key: ethers.Wallet): void;
/**
* Returns all the trades associated with the address.
*
* @returns The list of trades.
*/
listTrades(): Promise<Trade[]>;
/**
* Returns all the transfers associated with the address.
*
* @returns The list of transfers.
*/
listTransfers(): Promise<Transfer[]>;
/**
* Transfers the given amount of the given Asset to the given address. Only same-Network Transfers are supported.
*
* @param options - The options to create the Transfer.
* @param options.amount - The amount of the Asset to send.
* @param options.assetId - The ID of the Asset to send. For Ether, Coinbase.assets.Eth, Coinbase.assets.Gwei, and Coinbase.assets.Wei supported.
* @param options.destination - The destination of the transfer. If a Wallet, sends to the Wallet's default address. If a String, interprets it as the address ID.
* @param options.timeoutSeconds - The maximum amount of time to wait for the Transfer to complete, in seconds.
* @param options.intervalSeconds - The interval at which to poll the Network for Transfer status, in seconds.
* @returns The transfer object.
* @throws {APIError} if the API request to create a Transfer fails.
* @throws {APIError} if the API request to broadcast a Transfer fails.
* @throws {Error} if the Transfer times out.
*/
createTransfer({ amount, assetId, destination, timeoutSeconds, intervalSeconds, }: CreateTransferOptions): Promise<Transfer>;
/**
* Returns the address and network ID of the given destination.
*
* @param destination - The destination to get the address and network ID of.
* @returns The address and network ID of the destination.
*/
private getDestinationAddressAndNetwork;
/**
* Returns whether the Address has a private key backing it to sign transactions.
*
* @returns Whether the Address has a private key backing it to sign transactions.
*/
canSign(): boolean;
createTrade(amount: Amount, fromAssetId: string, toAssetId: string): Promise<Trade>;
/**
* Trades the given amount of the given Asset for another Asset. Only same-network Trades are supported.
*
* @param options = The options to create the Trade.
* @param options.amount - The amount of the From Asset to send.
* @param options.fromAssetId - The ID of the Asset to trade from.
* @param options.toAssetId - The ID of the Asset to trade to.
* @param options.timeoutSeconds - The maximum amount of time to wait for the Trade to complete, in seconds.
* @param options.intervalSeconds - The interval at which to poll the Network for Trade status, in seconds.
* @returns The Trade object.
* @throws {APIError} if the API request to create or broadcast a Trade fails.
* @throws {Error} if the Trade times out.
*/
createTrade({ amount, fromAssetId, toAssetId, timeoutSeconds, intervalSeconds, }: CreateTradeOptions): Promise<Trade>;
/**
* Creates a trade model for the specified amount and assets.
*
* @param amount - The amount of the Asset to send.
* @param fromAsset - The Asset to trade from.
* @param toAsset - The Asset to trade to.
* @returns A promise that resolves to a Trade object representing the new trade.
*/
private createTradeRequest;
/**
* Broadcasts a trade using the provided signed payloads.
*
* @param trade - The Trade object representing the trade.
* @param signedPayload - The signed payload of the trade.
* @param approveTransactionPayload - The signed payload of the approval transaction, if any.
* @returns A promise that resolves to a Trade object representing the broadcasted trade.
*/
private broadcastTradeRequest;
/**
* Checks if trading is possible and raises an error if not.
*
* @param amount - The amount of the Asset to send.
* @param fromAssetId - The ID of the Asset to trade from. For Ether, eth, gwei, and wei are supported.
* @throws {Error} If the private key is not loaded, or if the asset IDs are unsupported, or if there are insufficient funds.
*/
private validateCanTrade;
}

@@ -15,3 +15,13 @@ "use strict";

const wallet_1 = require("../wallet");
/**
* A representation of a blockchain address, which is a wallet-controlled account on a network.
*/
class WalletAddress extends address_1.Address {
/**
* Initializes a new Wallet Address instance.
*
* @param model - The address model data.
* @param key - The ethers.js SigningKey the Address uses to sign data.
* @throws {InternalError} If the address model is empty.
*/
constructor(model, key) {

@@ -25,8 +35,24 @@ if (!model) {

}
/**
* Returns a string representation of the wallet address.
*
* @returns A string representing the wallet address.
*/
toString() {
return `WalletAddress{ addressId: '${this.getId()}', networkId: '${this.getNetworkId()}', walletId: '${this.getWalletId()}' }`;
}
/**
* Returns the wallet ID.
*
* @returns The wallet ID.
*/
getWalletId() {
return this.model.wallet_id;
}
/**
* Sets the private key.
*
* @param key - The ethers.js SigningKey the Address uses to sign data.
* @throws {InternalError} If the private key is already set.
*/
setKey(key) {

@@ -38,2 +64,7 @@ if (this.key !== undefined) {

}
/**
* Returns all the trades associated with the address.
*
* @returns The list of trades.
*/
async listTrades() {

@@ -45,4 +76,4 @@ const trades = [];

const response = await coinbase_1.Coinbase.apiClients.trade.listTrades(this.model.wallet_id, this.model.address_id, 100, page?.length ? page : undefined);
response.data.data.forEach(transferModel => {
trades.push(new trade_1.Trade(transferModel));
response.data.data.forEach(tradeModel => {
trades.push(new trade_1.Trade(tradeModel));
});

@@ -57,2 +88,7 @@ if (response.data.has_more) {

}
/**
* Returns all the transfers associated with the address.
*
* @returns The list of transfers.
*/
async listTransfers() {

@@ -75,2 +111,16 @@ const transfers = [];

}
/**
* Transfers the given amount of the given Asset to the given address. Only same-Network Transfers are supported.
*
* @param options - The options to create the Transfer.
* @param options.amount - The amount of the Asset to send.
* @param options.assetId - The ID of the Asset to send. For Ether, Coinbase.assets.Eth, Coinbase.assets.Gwei, and Coinbase.assets.Wei supported.
* @param options.destination - The destination of the transfer. If a Wallet, sends to the Wallet's default address. If a String, interprets it as the address ID.
* @param options.timeoutSeconds - The maximum amount of time to wait for the Transfer to complete, in seconds.
* @param options.intervalSeconds - The interval at which to poll the Network for Transfer status, in seconds.
* @returns The transfer object.
* @throws {APIError} if the API request to create a Transfer fails.
* @throws {APIError} if the API request to broadcast a Transfer fails.
* @throws {Error} if the Transfer times out.
*/
async createTransfer({ amount, assetId, destination, timeoutSeconds = 10, intervalSeconds = 0.2, }) {

@@ -117,2 +167,8 @@ if (!coinbase_1.Coinbase.useServerSigner && !this.key) {

}
/**
* Returns the address and network ID of the given destination.
*
* @param destination - The destination to get the address and network ID of.
* @returns The address and network ID of the destination.
*/
getDestinationAddressAndNetwork(destination) {

@@ -130,16 +186,54 @@ if (typeof destination !== "string" && destination.getNetworkId() !== this.getNetworkId()) {

}
/**
* Returns whether the Address has a private key backing it to sign transactions.
*
* @returns Whether the Address has a private key backing it to sign transactions.
*/
canSign() {
return !!this.key;
}
async createTrade(amount, fromAssetId, toAssetId) {
/**
* Trades the given amount of the given Asset for another Asset. Only same-network Trades are supported.
*
* @param options = The options to create the Trade.
* @param options.amount - The amount of the From Asset to send.
* @param options.fromAssetId - The ID of the Asset to trade from.
* @param options.toAssetId - The ID of the Asset to trade to.
* @param options.timeoutSeconds - The maximum amount of time to wait for the Trade to complete, in seconds.
* @param options.intervalSeconds - The interval at which to poll the Network for Trade status, in seconds.
* @returns The Trade object.
* @throws {APIError} if the API request to create or broadcast a Trade fails.
* @throws {Error} if the Trade times out.
*/
async createTrade({ amount, fromAssetId, toAssetId, timeoutSeconds = 10, intervalSeconds = 0.2, }) {
const fromAsset = await asset_1.Asset.fetch(this.getNetworkId(), fromAssetId);
const toAsset = await asset_1.Asset.fetch(this.getNetworkId(), toAssetId);
await this.validateCanTrade(amount, fromAssetId);
const trade = await this.createTradeRequest(amount, fromAsset, toAsset);
const signed_payload = await trade.getTransaction().sign(this.key);
const approveTransactionSignedPayload = trade.getApproveTransaction()
? await trade.getApproveTransaction().sign(this.key)
: undefined;
return this.broadcastTradeRequest(trade, signed_payload, approveTransactionSignedPayload);
let trade = await this.createTradeRequest(amount, fromAsset, toAsset);
if (!coinbase_1.Coinbase.useServerSigner) {
const signed_payload = await trade.getTransaction().sign(this.key);
const approveTransactionSignedPayload = trade.getApproveTransaction()
? await trade.getApproveTransaction().sign(this.key)
: undefined;
trade = await this.broadcastTradeRequest(trade, signed_payload, approveTransactionSignedPayload);
}
const startTime = Date.now();
while (Date.now() - startTime < timeoutSeconds * 1000) {
await trade.reload();
const status = trade.getStatus();
if (status === types_1.TransactionStatus.COMPLETE || status === types_1.TransactionStatus.FAILED) {
return trade;
}
await (0, utils_1.delay)(intervalSeconds);
}
throw new Error("Trade timed out");
}
/**
* Creates a trade model for the specified amount and assets.
*
* @param amount - The amount of the Asset to send.
* @param fromAsset - The Asset to trade from.
* @param toAsset - The Asset to trade to.
* @returns A promise that resolves to a Trade object representing the new trade.
*/
async createTradeRequest(amount, fromAsset, toAsset) {

@@ -154,2 +248,10 @@ const tradeRequestPayload = {

}
/**
* Broadcasts a trade using the provided signed payloads.
*
* @param trade - The Trade object representing the trade.
* @param signedPayload - The signed payload of the trade.
* @param approveTransactionPayload - The signed payload of the approval transaction, if any.
* @returns A promise that resolves to a Trade object representing the broadcasted trade.
*/
async broadcastTradeRequest(trade, signedPayload, approveTransactionPayload) {

@@ -165,4 +267,11 @@ const broadcastTradeRequestPayload = {

}
/**
* Checks if trading is possible and raises an error if not.
*
* @param amount - The amount of the Asset to send.
* @param fromAssetId - The ID of the Asset to trade from. For Ether, eth, gwei, and wei are supported.
* @throws {Error} If the private key is not loaded, or if the asset IDs are unsupported, or if there are insufficient funds.
*/
async validateCanTrade(amount, fromAssetId) {
if (!this.canSign()) {
if (!coinbase_1.Coinbase.useServerSigner && !this.key) {
throw new Error("Cannot trade from address without private key loaded");

@@ -169,0 +278,0 @@ }

import { AxiosError } from "axios";
import { InternalError } from "./errors";
/**
* A wrapper for API errors to provide more context.
*/
export declare class APIError extends AxiosError {

@@ -7,4 +10,21 @@ httpCode: number | null;

apiMessage: string | null;
/**
* Initializes a new APIError object.
*
* @class
* @param {AxiosError} error - The Axios error.
*/
constructor(error: any);
/**
* Creates a specific APIError based on the API error code.
*
* @param {AxiosError} error - The underlying error object.
* @returns {APIError} A specific APIError instance.
*/
static fromError(error: AxiosError): InternalError | APIError;
/**
* Returns a String representation of the APIError.
*
* @returns {string} a String representation of the APIError
*/
toString(): string;

@@ -11,0 +31,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NetworkFeatureUnsupportedError = exports.InvalidTransferStatusError = exports.InvalidSignedPayloadError = exports.FaucetLimitReachedError = exports.ResourceExhaustedError = exports.InvalidNetworkIDError = exports.InvalidDestinationError = exports.InvalidAssetIDError = exports.UnsupportedAssetError = exports.MalformedRequestError = exports.AlreadyExistsError = exports.InvalidLimitError = exports.InvalidPageError = exports.InvalidTransferIDError = exports.InvalidAmountError = exports.InvalidAddressError = exports.InvalidWalletError = exports.InvalidAddressIDError = exports.InvalidWalletIDError = exports.NotFoundError = exports.UnauthorizedError = exports.UnimplementedError = exports.APIError = void 0;
/* eslint-disable jsdoc/require-jsdoc */
const axios_1 = require("axios");
const errors_1 = require("./errors");
/**
* A wrapper for API errors to provide more context.
*/
class APIError extends axios_1.AxiosError {
/**
* Initializes a new APIError object.
*
* @class
* @param {AxiosError} error - The Axios error.
*/
constructor(error) {

@@ -19,2 +29,8 @@ super();

}
/**
* Creates a specific APIError based on the API error code.
*
* @param {AxiosError} error - The underlying error object.
* @returns {APIError} A specific APIError instance.
*/
static fromError(error) {

@@ -77,2 +93,7 @@ const apiError = new APIError(error);

}
/**
* Returns a String representation of the APIError.
*
* @returns {string} a String representation of the APIError
*/
toString() {

@@ -79,0 +100,0 @@ return `APIError{httpCode: ${this.httpCode}, apiCode: ${this.apiCode}, apiMessage: ${this.apiMessage}}`;

import Decimal from "decimal.js";
import { Asset as AssetModel } from "./../client/api";
/** A representation of an Asset. */
export declare class Asset {

@@ -8,11 +9,70 @@ readonly networkId: string;

readonly decimals: number;
/**
* Private constructor for the Asset class.
*
* @param networkId - The network ID.
* @param assetId - The asset ID.
* @param contractAddress - The address ID.
* @param decimals - The number of decimals.
*/
private constructor();
/**
* Creates an Asset from an Asset Model.
*
* @param model - The Asset Model.
* @param assetId - The Asset ID.
* @throws If the Asset Model is invalid.
* @returns The Asset Class.
*/
static fromModel(model: AssetModel, assetId?: string): Asset;
/**
* Fetches the Asset with the provided Asset ID.
*
* @param networkId - The network ID.
* @param assetId - The asset ID.
* @throws If the Asset cannot be fetched.
* @returns The Asset Class.
*/
static fetch(networkId: string, assetId: string): Promise<Asset>;
/**
* Returns the primary denomination for the provided Asset ID.
* For `gwei` and `wei` the primary denomination is `eth`.
* For all other assets, the primary denomination is the same asset ID.
*
* @param assetId - The Asset ID.
* @returns The primary denomination for the Asset ID.
*/
static primaryDenomination(assetId: string): string;
/**
* Returns the primary denomination for the Asset.
*
* @returns The primary denomination for the Asset.
*/
primaryDenomination(): string;
/**
* Converts the amount of the Asset from whole to atomic units.
*
* @param wholeAmount - The whole amount to convert to atomic units.
* @returns The amount in atomic units
*/
toAtomicAmount(wholeAmount: Decimal): Decimal;
/**
* Converts the amount of the Asset from atomic to whole units.
*
* @param wholeAmount - The atomic amount to convert to whole units.
* @returns The amount in atomic units
*/
fromAtomicAmount(wholeAmount: Decimal): Decimal;
/**
* Returns a string representation of the Asset.
*
* @returns a string representation of the Asset
*/
toString(): string;
/**
* Returns the Asset ID.
*
* @returns The Asset ID.
*/
getAssetId(): string;
}

@@ -11,3 +11,12 @@ "use strict";

const errors_1 = require("./errors");
/** A representation of an Asset. */
class Asset {
/**
* Private constructor for the Asset class.
*
* @param networkId - The network ID.
* @param assetId - The asset ID.
* @param contractAddress - The address ID.
* @param decimals - The number of decimals.
*/
constructor(networkId, assetId, contractAddress, decimals) {

@@ -19,2 +28,10 @@ this.networkId = networkId;

}
/**
* Creates an Asset from an Asset Model.
*
* @param model - The Asset Model.
* @param assetId - The Asset ID.
* @throws If the Asset Model is invalid.
* @returns The Asset Class.
*/
static fromModel(model, assetId) {

@@ -25,2 +42,3 @@ if (!model) {

let decimals = model.decimals;
// TODO: Push this logic down to the backend.
if (assetId &&

@@ -44,2 +62,10 @@ model.asset_id &&

}
/**
* Fetches the Asset with the provided Asset ID.
*
* @param networkId - The network ID.
* @param assetId - The asset ID.
* @throws If the Asset cannot be fetched.
* @returns The Asset Class.
*/
static async fetch(networkId, assetId) {

@@ -49,2 +75,10 @@ const asset = await coinbase_1.Coinbase.apiClients.asset.getAsset(coinbase_1.Coinbase.normalizeNetwork(networkId), Asset.primaryDenomination(assetId));

}
/**
* Returns the primary denomination for the provided Asset ID.
* For `gwei` and `wei` the primary denomination is `eth`.
* For all other assets, the primary denomination is the same asset ID.
*
* @param assetId - The Asset ID.
* @returns The primary denomination for the Asset ID.
*/
static primaryDenomination(assetId) {

@@ -55,14 +89,41 @@ return [coinbase_1.Coinbase.assets.Gwei, coinbase_1.Coinbase.assets.Wei].includes(assetId)

}
/**
* Returns the primary denomination for the Asset.
*
* @returns The primary denomination for the Asset.
*/
primaryDenomination() {
return Asset.primaryDenomination(this.assetId);
}
/**
* Converts the amount of the Asset from whole to atomic units.
*
* @param wholeAmount - The whole amount to convert to atomic units.
* @returns The amount in atomic units
*/
toAtomicAmount(wholeAmount) {
return wholeAmount.times(new decimal_js_1.default(10).pow(this.decimals));
}
/**
* Converts the amount of the Asset from atomic to whole units.
*
* @param wholeAmount - The atomic amount to convert to whole units.
* @returns The amount in atomic units
*/
fromAtomicAmount(wholeAmount) {
return wholeAmount.dividedBy(new decimal_js_1.default(10).pow(this.decimals));
}
/**
* Returns a string representation of the Asset.
*
* @returns a string representation of the Asset
*/
toString() {
return `Asset{ networkId: ${this.networkId}, assetId: ${this.assetId}, contractAddress: ${this.contractAddress}, decimals: ${this.decimals} }`;
}
/**
* Returns the Asset ID.
*
* @returns The Asset ID.
*/
getAssetId() {

@@ -69,0 +130,0 @@ return this.assetId;

import { InternalAxiosRequestConfig } from "axios";
/**
* A class that builds JWTs for authenticating with the Coinbase Platform APIs.
*/
export declare class CoinbaseAuthenticator {
private apiKey;
private privateKey;
/**
* Initializes the Authenticator.
*
* @param {string} apiKey - The API key name.
* @param {string} privateKey - The private key associated with the API key.
*/
constructor(apiKey: string, privateKey: string);
/**
* Middleware to intercept requests and add JWT to Authorization header.
*
* @param {InternalAxiosRequestConfig} config - The request configuration.
* @param {boolean} debugging - Flag to enable debugging.
* @returns {Promise<InternalAxiosRequestConfig>} The request configuration with the Authorization header added.
* @throws {InvalidAPIKeyFormat} If JWT could not be built.
*/
authenticateRequest(config: InternalAxiosRequestConfig, debugging?: boolean): Promise<InternalAxiosRequestConfig>;
/**
* Builds the JWT for the given API endpoint URL.
*
* @param {string} url - URL of the API endpoint.
* @param {string} method - HTTP method of the request.
* @returns {Promise<string>} JWT token.
* @throws {InvalidAPIKeyFormat} If the private key is not in the correct format.
*/
buildJWT(url: string, method?: string): Promise<string>;
/**
* Extracts the PEM key from the given private key string.
*
* @param {string} privateKeyString - The private key string.
* @returns {string} The PEM key.
* @throws {InvalidAPIKeyFormat} If the private key string is not in the correct format.
*/
private extractPemKey;
/**
* Generates a random nonce for the JWT.
*
* @returns {string} The generated nonce.
*/
private nonce;
}

@@ -8,3 +8,12 @@ "use strict";

const pemFooter = "-----END EC PRIVATE KEY-----";
/**
* A class that builds JWTs for authenticating with the Coinbase Platform APIs.
*/
class CoinbaseAuthenticator {
/**
* Initializes the Authenticator.
*
* @param {string} apiKey - The API key name.
* @param {string} privateKey - The private key associated with the API key.
*/
constructor(apiKey, privateKey) {

@@ -14,2 +23,10 @@ this.apiKey = apiKey;

}
/**
* Middleware to intercept requests and add JWT to Authorization header.
*
* @param {InternalAxiosRequestConfig} config - The request configuration.
* @param {boolean} debugging - Flag to enable debugging.
* @returns {Promise<InternalAxiosRequestConfig>} The request configuration with the Authorization header added.
* @throws {InvalidAPIKeyFormat} If JWT could not be built.
*/
async authenticateRequest(config, debugging = false) {

@@ -25,2 +42,10 @@ const method = config.method?.toString().toUpperCase();

}
/**
* Builds the JWT for the given API endpoint URL.
*
* @param {string} url - URL of the API endpoint.
* @param {string} method - HTTP method of the request.
* @returns {Promise<string>} JWT token.
* @throws {InvalidAPIKeyFormat} If the private key is not in the correct format.
*/
async buildJWT(url, method = "GET") {

@@ -51,3 +76,3 @@ const pemPrivateKey = this.extractPemKey(this.privateKey);

nbf: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 60,
exp: Math.floor(Date.now() / 1000) + 60, // +1 minute
uris: [uri],

@@ -66,2 +91,9 @@ };

}
/**
* Extracts the PEM key from the given private key string.
*
* @param {string} privateKeyString - The private key string.
* @returns {string} The PEM key.
* @throws {InvalidAPIKeyFormat} If the private key string is not in the correct format.
*/
extractPemKey(privateKeyString) {

@@ -74,2 +106,7 @@ privateKeyString = privateKeyString.replace(/\n/g, "");

}
/**
* Generates a random nonce for the JWT.
*
* @returns {string} The generated nonce.
*/
nonce() {

@@ -76,0 +113,0 @@ const range = "0123456789";

import { Balance } from "./balance";
import { Balance as BalanceModel } from "../client";
import { Decimal } from "decimal.js";
/**
* A convenience class for storing and manipulating Asset balances in a human-readable format.
*/
export declare class BalanceMap extends Map<string, Decimal> {
/**
* Converts a list of Balance models to a BalanceMap.
*
* @param {BalanceModel[]} balances - The list of balances fetched from the API.
* @returns {BalanceMap} The converted BalanceMap object.
*/
static fromBalances(balances: BalanceModel[]): BalanceMap;
/**
* Adds a balance to the map.
*
* @param {Balance} balance - The balance to add to the map.
*/
add(balance: Balance): void;
/**
* Returns a string representation of the balance map.
*
* @returns The string representation of the balance map.
*/
toString(): string;
}

@@ -5,3 +5,12 @@ "use strict";

const balance_1 = require("./balance");
/**
* A convenience class for storing and manipulating Asset balances in a human-readable format.
*/
class BalanceMap extends Map {
/**
* Converts a list of Balance models to a BalanceMap.
*
* @param {BalanceModel[]} balances - The list of balances fetched from the API.
* @returns {BalanceMap} The converted BalanceMap object.
*/
static fromBalances(balances) {

@@ -15,2 +24,7 @@ const balanceMap = new BalanceMap();

}
/**
* Adds a balance to the map.
*
* @param {Balance} balance - The balance to add to the map.
*/
add(balance) {

@@ -22,2 +36,7 @@ if (!(balance instanceof balance_1.Balance)) {

}
/**
* Returns a string representation of the balance map.
*
* @returns The string representation of the balance map.
*/
toString() {

@@ -24,0 +43,0 @@ const result = {};

import Decimal from "decimal.js";
import { Balance as BalanceModel } from "../client";
import { Asset } from "./asset";
/** A representation of a balance. */
export declare class Balance {

@@ -8,5 +9,26 @@ readonly amount: Decimal;

readonly asset?: Asset;
/**
* Private constructor to prevent direct instantiation outside of the factory methods.
*
* @ignore
* @param {Decimal} amount - The amount of the balance.
* @param {string} assetId - The asset ID.
* @hideconstructor
*/
private constructor();
/**
* Converts a BalanceModel into a Balance object.
*
* @param {BalanceModel} model - The balance model object.
* @returns {Balance} The Balance object.
*/
static fromModel(model: BalanceModel): Balance;
/**
* Converts a BalanceModel and asset ID into a Balance object.
*
* @param {BalanceModel} model - The balance model object.
* @param {string} assetId - The asset ID.
* @returns {Balance} The Balance object.
*/
static fromModelAndAssetId(model: BalanceModel, assetId: string): Balance;
}

@@ -9,3 +9,12 @@ "use strict";

const asset_1 = require("./asset");
/** A representation of a balance. */
class Balance {
/**
* Private constructor to prevent direct instantiation outside of the factory methods.
*
* @ignore
* @param {Decimal} amount - The amount of the balance.
* @param {string} assetId - The asset ID.
* @hideconstructor
*/
constructor(amount, assetId, asset) {

@@ -16,2 +25,8 @@ this.amount = amount;

}
/**
* Converts a BalanceModel into a Balance object.
*
* @param {BalanceModel} model - The balance model object.
* @returns {Balance} The Balance object.
*/
static fromModel(model) {

@@ -21,2 +36,9 @@ const asset = asset_1.Asset.fromModel(model.asset);

}
/**
* Converts a BalanceModel and asset ID into a Balance object.
*
* @param {BalanceModel} model - The balance model object.
* @param {string} assetId - The asset ID.
* @returns {Balance} The Balance object.
*/
static fromModelAndAssetId(model, assetId) {

@@ -23,0 +45,0 @@ const asset = asset_1.Asset.fromModel(model.asset, assetId);

import { ApiClients, CoinbaseConfigureFromJsonOptions, CoinbaseOptions } from "./types";
import { User } from "./user";
/**
* The Coinbase SDK.
*/
export declare class Coinbase {
/**
* The list of supported networks.
*
* @constant
*/
static networks: {

@@ -10,2 +18,7 @@ BaseSepolia: string;

};
/**
* The list of supported assets.
*
* @constant
*/
static assets: {

@@ -19,9 +32,63 @@ Eth: string;

static apiClients: ApiClients;
/**
* The CDP API key Private Key.
*
* @constant
*/
static apiKeyPrivateKey: string;
/**
* Whether to use a server signer or not.
*
* @constant
*/
static useServerSigner: boolean;
/**
* Initializes the Coinbase SDK.
*
* @class
* @param options - The constructor options.
* @param options.apiKeyName - The API key name.
* @param options.privateKey - The private key associated with the API key.
* @param options.useServerSigner - Whether to use a Server-Signer or not.
* @param options.debugging - If true, logs API requests and responses to the console.
* @param options.basePath - The base path for the API.
* @throws {InternalError} If the configuration is invalid.
* @throws {InvalidAPIKeyFormat} If not able to create JWT token.
*/
constructor({ apiKeyName, privateKey, useServerSigner, debugging, basePath, }: CoinbaseOptions);
/**
* Reads the API key and private key from a JSON file and initializes the Coinbase SDK.
*
* @param options - The configuration options.
* @param options.filePath - The path to the JSON file containing the API key and private key.
* @param options.useServerSigner - Whether to use a Server-Signer or not.
* @param options.debugging - If true, logs API requests and responses to the console.
* @param options.basePath - The base path for the API.
* @returns A new instance of the Coinbase SDK.
* @throws {InvalidAPIKeyFormat} If the file does not exist or the configuration values are missing/invalid.
* @throws {InvalidConfiguration} If the configuration is invalid.
* @throws {InvalidAPIKeyFormat} If not able to create JWT token.
*/
static configureFromJson({ filePath, useServerSigner, debugging, basePath, }?: CoinbaseConfigureFromJsonOptions): Coinbase;
/**
* Converts a network symbol to a string, replacing underscores with hyphens.
*
* @param network - The network symbol to convert
* @returns the converted string
*/
static normalizeNetwork(network: string): string;
/**
* Converts a string to a symbol, replacing hyphens with underscores.
*
* @param asset - The string to convert
* @returns the converted symbol
*/
static toAssetId(asset: string): string;
/**
* Returns User object for the default user.
*
* @returns The default user.
* @throws {APIError} If the request fails.
*/
getDefaultUser(): Promise<User>;
}

@@ -40,3 +40,19 @@ "use strict";

const os = __importStar(require("os"));
/**
* The Coinbase SDK.
*/
class Coinbase {
/**
* Initializes the Coinbase SDK.
*
* @class
* @param options - The constructor options.
* @param options.apiKeyName - The API key name.
* @param options.privateKey - The private key associated with the API key.
* @param options.useServerSigner - Whether to use a Server-Signer or not.
* @param options.debugging - If true, logs API requests and responses to the console.
* @param options.basePath - The base path for the API.
* @throws {InternalError} If the configuration is invalid.
* @throws {InvalidAPIKeyFormat} If not able to create JWT token.
*/
constructor({ apiKeyName, privateKey, useServerSigner = false, debugging = false, basePath = base_1.BASE_PATH, }) {

@@ -54,3 +70,5 @@ if (apiKeyName === "") {

const axiosInstance = axios_1.default.create();
(0, utils_1.registerAxiosInterceptors)(axiosInstance, config => coinbaseAuthenticator.authenticateRequest(config, debugging), response => (0, utils_1.logApiResponse)(response, debugging));
(0, utils_1.registerAxiosInterceptors)(axiosInstance, config => coinbaseAuthenticator.authenticateRequest(config, debugging),
/* istanbul ignore file */
response => (0, utils_1.logApiResponse)(response, debugging));
Coinbase.apiClients.user = (0, client_1.UsersApiFactory)(config, basePath, axiosInstance);

@@ -69,2 +87,15 @@ Coinbase.apiClients.wallet = (0, client_1.WalletsApiFactory)(config, basePath, axiosInstance);

}
/**
* Reads the API key and private key from a JSON file and initializes the Coinbase SDK.
*
* @param options - The configuration options.
* @param options.filePath - The path to the JSON file containing the API key and private key.
* @param options.useServerSigner - Whether to use a Server-Signer or not.
* @param options.debugging - If true, logs API requests and responses to the console.
* @param options.basePath - The base path for the API.
* @returns A new instance of the Coinbase SDK.
* @throws {InvalidAPIKeyFormat} If the file does not exist or the configuration values are missing/invalid.
* @throws {InvalidConfiguration} If the configuration is invalid.
* @throws {InvalidAPIKeyFormat} If not able to create JWT token.
*/
static configureFromJson({ filePath = "coinbase_cloud_api_key.json", useServerSigner = false, debugging = false, basePath = base_1.BASE_PATH, } = {}) {

@@ -98,8 +129,26 @@ filePath = filePath.startsWith("~") ? filePath.replace("~", os.homedir()) : filePath;

}
/**
* Converts a network symbol to a string, replacing underscores with hyphens.
*
* @param network - The network symbol to convert
* @returns the converted string
*/
static normalizeNetwork(network) {
return network.replace(/_/g, "-");
}
/**
* Converts a string to a symbol, replacing hyphens with underscores.
*
* @param asset - The string to convert
* @returns the converted symbol
*/
static toAssetId(asset) {
return asset.replace(/-/g, "_");
}
/**
* Returns User object for the default user.
*
* @returns The default user.
* @throws {APIError} If the request fails.
*/
async getDefaultUser() {

@@ -111,2 +160,7 @@ const userResponse = await Coinbase.apiClients.user.getCurrentUser();

exports.Coinbase = Coinbase;
/**
* The list of supported networks.
*
* @constant
*/
Coinbase.networks = {

@@ -118,2 +172,7 @@ BaseSepolia: "base-sepolia",

};
/**
* The list of supported assets.
*
* @constant
*/
Coinbase.assets = {

@@ -120,0 +179,0 @@ Eth: "eth",

@@ -0,20 +1,60 @@

/**
* InvalidaAPIKeyFormat error is thrown when the API key format is invalid.
*/
export declare class InvalidAPIKeyFormat extends Error {
static DEFAULT_MESSAGE: string;
/**
* Initializes a new InvalidAPIKeyFormat instance.
*
* @param message - The error message.
*/
constructor(message?: string);
}
/**
* ArgumentError is thrown when an argument is invalid.
*/
export declare class ArgumentError extends Error {
static DEFAULT_MESSAGE: string;
/**
* Initializes a new ArgumentError instance.
*
* @param message - The error message.
*/
constructor(message?: string);
}
/**
* InternalError is thrown when there is an internal error in the SDK.
*/
export declare class InternalError extends Error {
static DEFAULT_MESSAGE: string;
/**
* Initializes a new InternalError instance.
*
* @param message - The error message.
*/
constructor(message?: string);
}
/**
* InvalidConfiguration error is thrown when apikey/privateKey configuration is invalid.
*/
export declare class InvalidConfiguration extends Error {
static DEFAULT_MESSAGE: string;
/**
* Initializes a new InvalidConfiguration instance.
*
* @param message - The error message.
*/
constructor(message?: string);
}
/**
* InvalidUnsignedPayload error is thrown when the unsigned payload is invalid.
*/
export declare class InvalidUnsignedPayload extends Error {
static DEFAULT_MESSAGE: string;
/**
* Initializes a new InvalidUnsignedPayload instance.
*
* @param message - The error message.
*/
constructor(message?: string);
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidUnsignedPayload = exports.InvalidConfiguration = exports.InternalError = exports.ArgumentError = exports.InvalidAPIKeyFormat = void 0;
/**
* InvalidaAPIKeyFormat error is thrown when the API key format is invalid.
*/
class InvalidAPIKeyFormat extends Error {
/**
* Initializes a new InvalidAPIKeyFormat instance.
*
* @param message - The error message.
*/
constructor(message = InvalidAPIKeyFormat.DEFAULT_MESSAGE) {

@@ -15,3 +23,11 @@ super(message);

InvalidAPIKeyFormat.DEFAULT_MESSAGE = "Invalid API key format";
/**
* ArgumentError is thrown when an argument is invalid.
*/
class ArgumentError extends Error {
/**
* Initializes a new ArgumentError instance.
*
* @param message - The error message.
*/
constructor(message = ArgumentError.DEFAULT_MESSAGE) {

@@ -27,3 +43,11 @@ super(message);

ArgumentError.DEFAULT_MESSAGE = "Argument Error";
/**
* InternalError is thrown when there is an internal error in the SDK.
*/
class InternalError extends Error {
/**
* Initializes a new InternalError instance.
*
* @param message - The error message.
*/
constructor(message = InternalError.DEFAULT_MESSAGE) {

@@ -39,3 +63,11 @@ super(message);

InternalError.DEFAULT_MESSAGE = "Internal Error";
/**
* InvalidConfiguration error is thrown when apikey/privateKey configuration is invalid.
*/
class InvalidConfiguration extends Error {
/**
* Initializes a new InvalidConfiguration instance.
*
* @param message - The error message.
*/
constructor(message = InvalidConfiguration.DEFAULT_MESSAGE) {

@@ -51,3 +83,11 @@ super(message);

InvalidConfiguration.DEFAULT_MESSAGE = "Invalid configuration";
/**
* InvalidUnsignedPayload error is thrown when the unsigned payload is invalid.
*/
class InvalidUnsignedPayload extends Error {
/**
* Initializes a new InvalidUnsignedPayload instance.
*
* @param message - The error message.
*/
constructor(message = InvalidUnsignedPayload.DEFAULT_MESSAGE) {

@@ -54,0 +94,0 @@ super(message);

import { FaucetTransaction as FaucetTransactionModel } from "../client";
/**
* Represents a transaction from a faucet.
*/
export declare class FaucetTransaction {
private model;
/**
* Creates a new FaucetTransaction instance.
* Do not use this method directly - instead, use Address.faucet().
*
* @class
* @param {FaucetTransactionModel} model - The FaucetTransaction model.
* @throws {InternalError} If the model does not exist.
*/
constructor(model: FaucetTransactionModel);
/**
* Returns the transaction hash.
*
* @returns {string} The transaction hash.
*/
getTransactionHash(): string;
/**
* Returns the link to the transaction on the blockchain explorer.
*
* @returns {string} The link to the transaction on the blockchain explorer
*/
getTransactionLink(): string;
/**
* Returns a string representation of the FaucetTransaction.
*
* @returns {string} A string representation of the FaucetTransaction.
*/
toString(): string;
}

@@ -5,3 +5,14 @@ "use strict";

const errors_1 = require("./errors");
/**
* Represents a transaction from a faucet.
*/
class FaucetTransaction {
/**
* Creates a new FaucetTransaction instance.
* Do not use this method directly - instead, use Address.faucet().
*
* @class
* @param {FaucetTransactionModel} model - The FaucetTransaction model.
* @throws {InternalError} If the model does not exist.
*/
constructor(model) {

@@ -13,8 +24,23 @@ if (!model?.transaction_hash) {

}
/**
* Returns the transaction hash.
*
* @returns {string} The transaction hash.
*/
getTransactionHash() {
return this.model.transaction_hash;
}
/**
* Returns the link to the transaction on the blockchain explorer.
*
* @returns {string} The link to the transaction on the blockchain explorer
*/
getTransactionLink() {
return this.model.transaction_link;
}
/**
* Returns a string representation of the FaucetTransaction.
*
* @returns {string} A string representation of the FaucetTransaction.
*/
toString() {

@@ -21,0 +47,0 @@ return `Coinbase::FaucetTransaction{transaction_hash: '${this.getTransactionHash()}', transaction_link: '${this.getTransactionLink()}'}`;

@@ -0,8 +1,42 @@

/**
* A representation of a Server-Signer. Server-Signers are assigned to sign transactions for a Wallet.
*/
export declare class ServerSigner {
private model;
/**
* Private constructor to prevent direct instantiation outside of factory method.
* Creates a new ServerSigner instance.
* Do not use this method directly. Instead, use ServerSigner.getDefault().
*
* @ignore
* @param serverSignerModel - The Server-Signer model.
* @hideconstructor
*/
private constructor();
/**
* Returns the default Server-Signer for the CDP Project.
*
* @returns The default Server-Signer.
* @throws {APIError} if the API request to list Server-Signers fails.
* @throws {Error} if there is no Server-Signer associated with the CDP Project.
*/
static getDefault(): Promise<ServerSigner>;
/**
* Returns the ID of the Server-Signer.
*
* @returns The Server-Signer ID.
*/
getId(): string;
/**
* Returns the IDs of the Wallet's the Server-Signer can sign for.
*
* @returns The Wallet IDs.
*/
getWallets(): string[] | undefined;
/**
* Returns a String representation of the Server-Signer.
*
* @returns a String representation of the Server-Signer.
*/
toString(): string;
}

@@ -5,6 +5,25 @@ "use strict";

const coinbase_1 = require("./coinbase");
/**
* A representation of a Server-Signer. Server-Signers are assigned to sign transactions for a Wallet.
*/
class ServerSigner {
/**
* Private constructor to prevent direct instantiation outside of factory method.
* Creates a new ServerSigner instance.
* Do not use this method directly. Instead, use ServerSigner.getDefault().
*
* @ignore
* @param serverSignerModel - The Server-Signer model.
* @hideconstructor
*/
constructor(serverSignerModel) {
this.model = serverSignerModel;
}
/**
* Returns the default Server-Signer for the CDP Project.
*
* @returns The default Server-Signer.
* @throws {APIError} if the API request to list Server-Signers fails.
* @throws {Error} if there is no Server-Signer associated with the CDP Project.
*/
static async getDefault() {

@@ -17,8 +36,23 @@ const response = await coinbase_1.Coinbase.apiClients.serverSigner.listServerSigners();

}
/**
* Returns the ID of the Server-Signer.
*
* @returns The Server-Signer ID.
*/
getId() {
return this.model.server_signer_id;
}
/**
* Returns the IDs of the Wallet's the Server-Signer can sign for.
*
* @returns The Wallet IDs.
*/
getWallets() {
return this.model.wallets;
}
/**
* Returns a String representation of the Server-Signer.
*
* @returns a String representation of the Server-Signer.
*/
toString() {

@@ -25,0 +59,0 @@ return `ServerSigner{id: '${this.getId()}', wallets: '${this.getWallets()}'}`;

import { ethers } from "ethers";
import { StakingOperation as StakingOperationModel, StakingOperationStatusEnum } from "../client/api";
import { Transaction } from "./transaction";
/**
* A representation of a staking operation (stake, unstake, claim rewards, etc). It
* may have multiple steps with some being transactions to sign, and others to wait.
*/
export declare class StakingOperation {
private model;
private transactions;
/**
* Creates a StakingOperation object.
*
* @class
* @param model - The staking operation response from the API call.
*/
constructor(model: StakingOperationModel);
/**
* Get the staking operation ID.
*
* @returns The unique ID of the staking operation.
*/
getID(): string;
/**
* Get the transactions associated with this staking operation.
*
* @returns The array of transactions.
*/
getTransactions(): Transaction[];
/**
* Get signed voluntary exit messages for native eth unstaking
*
* @returns The signed voluntary exit messages for a native eth unstaking operation.
*/
getSignedVoluntaryExitMessages(): string[];
/**
* Get the status of the staking operation.
*
* @returns The status of the staking operation.
*/
getStatus(): StakingOperationStatusEnum;
/**
* Returns whether the Staking operation is in a terminal State.
*
* @returns Whether the Staking operation is in a terminal State
*/
isTerminalState(): boolean;
/**
* Waits until the Staking Operation is completed or failed by polling its status at the given interval.
*
* @param options - The options to configure the wait function.
* @param options.intervalSeconds - The interval at which to poll, in seconds
* @param options.timeoutSeconds - The maximum amount of time to wait for the StakingOperation to complete, in seconds
* @throws {Error} If the StakingOperation takes longer than the given timeout.
* @returns The completed StakingOperation object.
*/
wait({ intervalSeconds, timeoutSeconds, }?: {

@@ -17,4 +61,14 @@ intervalSeconds?: number | undefined;

}): Promise<StakingOperationModel>;
/**
* Get the staking operation for the given ID.
*
* @returns The staking operation object.
*/
fetch(): Promise<StakingOperationModel>;
/**
* Sign the transactions in the StakingOperation object.
*
* @param key - The key used to sign the transactions.
*/
sign(key: ethers.Wallet): Promise<void>;
}

@@ -8,3 +8,13 @@ "use strict";

const utils_1 = require("./utils");
/**
* A representation of a staking operation (stake, unstake, claim rewards, etc). It
* may have multiple steps with some being transactions to sign, and others to wait.
*/
class StakingOperation {
/**
* Creates a StakingOperation object.
*
* @class
* @param model - The staking operation response from the API call.
*/
constructor(model) {

@@ -22,8 +32,23 @@ if (!model) {

}
/**
* Get the staking operation ID.
*
* @returns The unique ID of the staking operation.
*/
getID() {
return this.model.id;
}
/**
* Get the transactions associated with this staking operation.
*
* @returns The array of transactions.
*/
getTransactions() {
return this.transactions;
}
/**
* Get signed voluntary exit messages for native eth unstaking
*
* @returns The signed voluntary exit messages for a native eth unstaking operation.
*/
getSignedVoluntaryExitMessages() {

@@ -39,8 +64,27 @@ const signedVoluntaryExitMessages = [];

}
/**
* Get the status of the staking operation.
*
* @returns The status of the staking operation.
*/
getStatus() {
return this.model.status;
}
/**
* Returns whether the Staking operation is in a terminal State.
*
* @returns Whether the Staking operation is in a terminal State
*/
isTerminalState() {
return this.getStatus() === api_1.StakingOperationStatusEnum.Complete;
}
/**
* Waits until the Staking Operation is completed or failed by polling its status at the given interval.
*
* @param options - The options to configure the wait function.
* @param options.intervalSeconds - The interval at which to poll, in seconds
* @param options.timeoutSeconds - The maximum amount of time to wait for the StakingOperation to complete, in seconds
* @throws {Error} If the StakingOperation takes longer than the given timeout.
* @returns The completed StakingOperation object.
*/
async wait({ intervalSeconds = 5, timeoutSeconds = 3600, } = {}) {

@@ -60,2 +104,7 @@ const startTime = Date.now();

}
/**
* Get the staking operation for the given ID.
*
* @returns The staking operation object.
*/
async fetch() {

@@ -71,2 +120,7 @@ const response = await coinbase_1.Coinbase.apiClients.stake.getExternalStakingOperation(this.model.network_id, this.model.address_id, this.model.id);

}
/**
* Sign the transactions in the StakingOperation object.
*
* @param key - The key used to sign the transactions.
*/
async sign(key) {

@@ -73,0 +127,0 @@ for (const tx of this.transactions) {

import { StakingRewardFormat, StakingReward as StakingRewardModel } from "../client";
import { Asset } from "./asset";
import { Amount } from "./types";
/**
* A representation of a staking reward earned on a network for a given asset.
*/
export declare class StakingReward {

@@ -8,8 +11,46 @@ private model;

private format;
/**
* Creates the StakingReward object.
*
* @param model - The underlying staking reward object.
* @param asset - The asset for the staking reward.
* @param format - The format to return the rewards in. (usd, native). Defaults to usd.
*/
constructor(model: StakingRewardModel, asset: Asset, format: StakingRewardFormat);
/**
* Returns a list of StakingRewards for the provided network, asset, and addresses.
*
* @param networkId - The network ID.
* @param assetId - The asset ID.
* @param addressIds - The address ID.
* @param startTime - The start time.
* @param endTime - The end time.
* @param format - The format to return the rewards in. (usd, native). Defaults to usd.
* @returns The staking rewards.
*/
static list(networkId: string, assetId: string, addressIds: Array<string>, startTime: string, endTime: string, format?: StakingRewardFormat): Promise<StakingReward[]>;
/**
* Returns the amount of the StakingReward.
*
* @returns The amount.
*/
amount(): Amount;
/**
* Returns the date of the StakingReward.
*
* @returns The date.
*/
date(): Date;
/**
* Returns the onchain address of the StakingReward.
*
* @returns The onchain address.
*/
addressId(): string;
/**
* Print the Staking Reward as a string.
*
* @returns The string representation of the Staking Reward.
*/
toString(): string;
}

@@ -11,3 +11,13 @@ "use strict";

const asset_1 = require("./asset");
/**
* A representation of a staking reward earned on a network for a given asset.
*/
class StakingReward {
/**
* Creates the StakingReward object.
*
* @param model - The underlying staking reward object.
* @param asset - The asset for the staking reward.
* @param format - The format to return the rewards in. (usd, native). Defaults to usd.
*/
constructor(model, asset, format) {

@@ -18,2 +28,13 @@ this.model = model;

}
/**
* Returns a list of StakingRewards for the provided network, asset, and addresses.
*
* @param networkId - The network ID.
* @param assetId - The asset ID.
* @param addressIds - The address ID.
* @param startTime - The start time.
* @param endTime - The end time.
* @param format - The format to return the rewards in. (usd, native). Defaults to usd.
* @returns The staking rewards.
*/
static async list(networkId, assetId, addressIds, startTime, endTime, format = client_1.StakingRewardFormat.Usd) {

@@ -45,2 +66,7 @@ const stakingRewards = [];

}
/**
* Returns the amount of the StakingReward.
*
* @returns The amount.
*/
amount() {

@@ -52,8 +78,23 @@ if (this.format == client_1.StakingRewardFormat.Usd) {

}
/**
* Returns the date of the StakingReward.
*
* @returns The date.
*/
date() {
return new Date(this.model.date);
}
/**
* Returns the onchain address of the StakingReward.
*
* @returns The onchain address.
*/
addressId() {
return this.model.address_id;
}
/**
* Print the Staking Reward as a string.
*
* @returns The string representation of the Staking Reward.
*/
toString() {

@@ -60,0 +101,0 @@ return `StakingReward { date: '${this.date().toISOString()}' address: '${this.addressId()}' amount: '${this.amount().toString()}' }`;

@@ -5,2 +5,6 @@ import { Decimal } from "decimal.js";

import { TransactionStatus } from "./types";
/**
* A representation of a Trade, which trades an amount of an Asset to another Asset on a Network.
* The fee is assumed to be paid in the native Asset of the Network.
*/
export declare class Trade {

@@ -10,14 +14,87 @@ private model;

private approveTransaction?;
/**
* Trades should be created through Wallet.trade or Address.trade.
*
* @class
* @param model - The underlying Trade object.
* @throws {InternalError} - If the Trade model is empty.
*/
constructor(model: CoinbaseTrade);
/**
* Returns the Trade ID.
*
* @returns The Trade ID.
*/
getId(): string;
/**
* Returns the Network ID of the Trade.
*
* @returns The Network ID.
*/
getNetworkId(): string;
/**
* Returns the Wallet ID of the Trade.
*
* @returns The Wallet ID.
*/
getWalletId(): string;
/**
* Returns the Address ID of the Trade.
*
* @returns The Address ID.
*/
getAddressId(): string;
/**
* Returns the From Asset ID of the Trade.
*
* @returns The From Asset ID.
*/
getFromAssetId(): string;
/**
* Returns the amount of the from asset for the Trade.
*
* @returns The amount of the from asset.
*/
getFromAmount(): Decimal;
/**
* Returns the To Asset ID of the Trade.
*
* @returns The To Asset ID.
*/
getToAssetId(): string;
/**
* Returns the amount of the to asset for the Trade.
*
* @returns The amount of the to asset.
*/
getToAmount(): Decimal;
/**
* Returns the Trade transaction.
*
* @returns The Trade transaction.
*/
getTransaction(): Transaction;
/**
* Returns the approve transaction if it exists.
*
* @returns The approve transaction.
*/
getApproveTransaction(): Transaction | undefined;
/**
* Returns the status of the Trade.
*
* @returns The status.
*/
getStatus(): TransactionStatus | undefined;
/**
* Waits until the Trade is completed or failed by polling the Network at the given interval. Raises a
* Error if the Trade takes longer than the given timeout.
*
* @param options - The options to configure the wait function.
* @param options.intervalSeconds - The interval at which to poll the Network, in seconds
* @param options.timeoutSeconds - The maximum amount of time to wait for the Trade to complete, in seconds
* @throws {Error} If the Trade takes longer than the given timeout.
* @throws {APIError} If the request fails.
* @returns The completed Trade object.
*/
wait({ intervalSeconds, timeoutSeconds }?: {

@@ -27,4 +104,14 @@ intervalSeconds?: number | undefined;

}): Promise<Trade>;
/**
* Reloads the Trade model with the latest version from the server side.
*
* @returns The most recent version of Trade from the server.
*/
reload(): Promise<Trade>;
/**
* Returns a String representation of the Trade.
*
* @returns A String representation of the Trade.
*/
toString(): string;
}

@@ -9,3 +9,14 @@ "use strict";

const utils_1 = require("./utils");
/**
* A representation of a Trade, which trades an amount of an Asset to another Asset on a Network.
* The fee is assumed to be paid in the native Asset of the Network.
*/
class Trade {
/**
* Trades should be created through Wallet.trade or Address.trade.
*
* @class
* @param model - The underlying Trade object.
* @throws {InternalError} - If the Trade model is empty.
*/
constructor(model) {

@@ -17,17 +28,47 @@ if (!model) {

}
/**
* Returns the Trade ID.
*
* @returns The Trade ID.
*/
getId() {
return this.model.trade_id;
}
/**
* Returns the Network ID of the Trade.
*
* @returns The Network ID.
*/
getNetworkId() {
return this.model.network_id;
}
/**
* Returns the Wallet ID of the Trade.
*
* @returns The Wallet ID.
*/
getWalletId() {
return this.model.wallet_id;
}
/**
* Returns the Address ID of the Trade.
*
* @returns The Address ID.
*/
getAddressId() {
return this.model.address_id;
}
/**
* Returns the From Asset ID of the Trade.
*
* @returns The From Asset ID.
*/
getFromAssetId() {
return this.model.from_asset.asset_id;
}
/**
* Returns the amount of the from asset for the Trade.
*
* @returns The amount of the from asset.
*/
getFromAmount() {

@@ -37,5 +78,15 @@ const amount = new decimal_js_1.Decimal(this.model.from_amount);

}
/**
* Returns the To Asset ID of the Trade.
*
* @returns The To Asset ID.
*/
getToAssetId() {
return this.model.to_asset.asset_id;
}
/**
* Returns the amount of the to asset for the Trade.
*
* @returns The amount of the to asset.
*/
getToAmount() {

@@ -45,2 +96,7 @@ const amount = new decimal_js_1.Decimal(this.model.to_amount);

}
/**
* Returns the Trade transaction.
*
* @returns The Trade transaction.
*/
getTransaction() {

@@ -50,2 +106,7 @@ this.transaction = new transaction_1.Transaction(this.model.transaction);

}
/**
* Returns the approve transaction if it exists.
*
* @returns The approve transaction.
*/
getApproveTransaction() {

@@ -57,5 +118,21 @@ if (!this.approveTransaction && this.model.approve_transaction) {

}
/**
* Returns the status of the Trade.
*
* @returns The status.
*/
getStatus() {
return this.getTransaction()?.getStatus();
}
/**
* Waits until the Trade is completed or failed by polling the Network at the given interval. Raises a
* Error if the Trade takes longer than the given timeout.
*
* @param options - The options to configure the wait function.
* @param options.intervalSeconds - The interval at which to poll the Network, in seconds
* @param options.timeoutSeconds - The maximum amount of time to wait for the Trade to complete, in seconds
* @throws {Error} If the Trade takes longer than the given timeout.
* @throws {APIError} If the request fails.
* @returns The completed Trade object.
*/
async wait({ intervalSeconds = 0.2, timeoutSeconds = 10 } = {}) {

@@ -75,2 +152,7 @@ const startTime = Date.now();

}
/**
* Reloads the Trade model with the latest version from the server side.
*
* @returns The most recent version of Trade from the server.
*/
async reload() {

@@ -85,2 +167,7 @@ const result = await coinbase_1.Coinbase.apiClients.trade.getTrade(this.getWalletId(), this.getAddressId(), this.getId());

}
/**
* Returns a String representation of the Trade.
*
* @returns A String representation of the Trade.
*/
toString() {

@@ -87,0 +174,0 @@ return (`Trade { transfer_id: '${this.getId()}', network_id: '${this.getNetworkId()}', ` +

import { ethers } from "ethers";
import { Transaction as TransactionModel } from "../client/api";
import { TransactionStatus } from "./types";
/**
* A representation of an onchain Transaction.
*/
export declare class Transaction {

@@ -8,14 +11,77 @@ private model;

private signed;
/**
* Transactions should be constructed via higher level abstractions like Trade or Transfer.
*
* @class
* @param model - The underlying Transaction object.
*/
constructor(model: TransactionModel);
/**
* Returns the Unsigned Payload of the Transaction.
*
* @returns The Unsigned Payload
*/
getUnsignedPayload(): string;
/**
* Returns the Signed Payload of the Transaction.
*
* @returns The Signed Payload
*/
getSignedPayload(): string | undefined;
/**
* Returns the Transaction Hash of the Transaction.
*
* @returns The Transaction Hash
*/
getTransactionHash(): string | undefined;
/**
* Returns the Status of the Transaction.
*
* @returns The Status
*/
getStatus(): TransactionStatus | undefined;
/**
* Returns the From Address ID for the Transaction.
*
* @returns The From Address ID
*/
fromAddressId(): string;
/**
* Returns whether the Transaction is in a terminal State.
*
* @returns Whether the Transaction is in a terminal State
*/
isTerminalState(): boolean;
/**
* Returns the link to the Transaction on the blockchain explorer.
*
* @returns The link to the Transaction on the blockchain explorer
*/
getTransactionLink(): string;
/**
* Returns the underlying raw transaction.
*
* @throws {InvalidUnsignedPayload} If the Unsigned Payload is invalid.
* @returns The ethers.js Transaction object
*/
rawTransaction(): ethers.Transaction;
/**
* Signs the Transaction with the provided key and returns the hex signing payload.
*
* @param key - The key to sign the transaction with
* @returns The hex-encoded signed payload
*/
sign(key: ethers.Wallet): Promise<string>;
/**
* Returns whether the transaction has been signed.
*
* @returns if the transaction has been signed.
*/
isSigned(): boolean | undefined;
/**
* Returns a string representation of the Transaction.
*
* @returns A string representation of the Transaction.
*/
toString(): string;
}

@@ -7,3 +7,12 @@ "use strict";

const utils_1 = require("./utils");
/**
* A representation of an onchain Transaction.
*/
class Transaction {
/**
* Transactions should be constructed via higher level abstractions like Trade or Transfer.
*
* @class
* @param model - The underlying Transaction object.
*/
constructor(model) {

@@ -15,11 +24,31 @@ if (!model) {

}
/**
* Returns the Unsigned Payload of the Transaction.
*
* @returns The Unsigned Payload
*/
getUnsignedPayload() {
return this.model.unsigned_payload;
}
/**
* Returns the Signed Payload of the Transaction.
*
* @returns The Signed Payload
*/
getSignedPayload() {
return this.model.signed_payload;
}
/**
* Returns the Transaction Hash of the Transaction.
*
* @returns The Transaction Hash
*/
getTransactionHash() {
return this.model.transaction_hash;
}
/**
* Returns the Status of the Transaction.
*
* @returns The Status
*/
getStatus() {

@@ -39,5 +68,15 @@ switch (this.model.status) {

}
/**
* Returns the From Address ID for the Transaction.
*
* @returns The From Address ID
*/
fromAddressId() {
return this.model.from_address_id;
}
/**
* Returns whether the Transaction is in a terminal State.
*
* @returns Whether the Transaction is in a terminal State
*/
isTerminalState() {

@@ -49,5 +88,16 @@ const status = this.getStatus();

}
/**
* Returns the link to the Transaction on the blockchain explorer.
*
* @returns The link to the Transaction on the blockchain explorer
*/
getTransactionLink() {
return this.model.transaction_link;
}
/**
* Returns the underlying raw transaction.
*
* @throws {InvalidUnsignedPayload} If the Unsigned Payload is invalid.
* @returns The ethers.js Transaction object
*/
rawTransaction() {

@@ -63,2 +113,3 @@ if (this.raw) {

transaction.maxFeePerGas = BigInt(parsedPayload.maxFeePerGas);
// TODO: Handle multiple currencies.
transaction.gasLimit = BigInt(parsedPayload.gas);

@@ -71,2 +122,8 @@ transaction.to = parsedPayload.to;

}
/**
* Signs the Transaction with the provided key and returns the hex signing payload.
*
* @param key - The key to sign the transaction with
* @returns The hex-encoded signed payload
*/
async sign(key) {

@@ -76,7 +133,18 @@ const signedPayload = await key.signTransaction(this.rawTransaction());

this.signed = true;
// Removes the '0x' prefix as required by the API.
return signedPayload.slice(2);
}
/**
* Returns whether the transaction has been signed.
*
* @returns if the transaction has been signed.
*/
isSigned() {
return this.signed;
}
/**
* Returns a string representation of the Transaction.
*
* @returns A string representation of the Transaction.
*/
toString() {

@@ -83,0 +151,0 @@ return `Transaction { transactionHash: '${this.getTransactionHash()}', status: '${this.getStatus()}' }`;

@@ -5,23 +5,122 @@ import { Decimal } from "decimal.js";

import { ethers } from "ethers";
/**
* A representation of a Transfer, which moves an Amount of an Asset from
* a user-controlled Wallet to another Address. The fee is assumed to be paid
* in the native Asset of the Network.
*/
export declare class Transfer {
private model;
private transaction?;
/**
* Private constructor to prevent direct instantiation outside of the factory methods.
*
* @ignore
* @param transferModel - The Transfer model.
* @hideconstructor
*/
private constructor();
/**
* Converts a TransferModel into a Transfer object.
*
* @param transferModel - The Transfer model object.
* @returns The Transfer object.
*/
static fromModel(transferModel: TransferModel): Transfer;
/**
* Returns the ID of the Transfer.
*
* @returns The Transfer ID.
*/
getId(): string;
/**
* Returns the Network ID of the Transfer.
*
* @returns The Network ID.
*/
getNetworkId(): string;
/**
* Returns the Wallet ID of the Transfer.
*
* @returns The Wallet ID.
*/
getWalletId(): string;
/**
* Returns the From Address ID of the Transfer.
*
* @returns The From Address ID.
*/
getFromAddressId(): string;
/**
* Returns the Destination Address ID of the Transfer.
*
* @returns The Destination Address ID.
*/
getDestinationAddressId(): string;
/**
* Returns the Asset ID of the Transfer.
*
* @returns The Asset ID.
*/
getAssetId(): string;
/**
* Returns the Amount of the Transfer.
*
* @returns The Amount of the Asset.
*/
getAmount(): Decimal;
/**
* Returns the Unsigned Payload of the Transfer.
*
* @returns The Unsigned Payload as a Hex string.
*/
getUnsignedPayload(): string;
/**
* Returns the Signed Payload of the Transfer.
*
* @returns The Signed Payload as a Hex string, or undefined if not yet available.
*/
getSignedPayload(): string | undefined;
/**
* Returns the Transaction Hash of the Transfer.
*
* @returns The Transaction Hash as a Hex string, or undefined if not yet available.
*/
getTransactionHash(): string | undefined;
/**
* Returns the Transaction of the Transfer.
*
* @returns The ethers.js Transaction object.
* @throws (InvalidUnsignedPayload) If the Unsigned Payload is invalid.
*/
getTransaction(): ethers.Transaction;
/**
* Sets the Signed Transaction of the Transfer.
*
* @param transaction - The Signed Transaction.
*/
setSignedTransaction(transaction: ethers.Transaction): void;
/**
* Returns the Status of the Transfer.
*
* @returns The Status of the Transfer.
*/
getStatus(): TransferStatus | undefined;
/**
* Returns the link to the Transaction on the blockchain explorer.
*
* @returns The link to the Transaction on the blockchain explorer.
*/
getTransactionLink(): string;
/**
* Reloads the Transfer model with the latest data from the server.
*
* @throws {APIError} if the API request to get a Transfer fails.
*/
reload(): Promise<void>;
/**
* Returns a string representation of the Transfer.
*
* @returns The string representation of the Transfer.
*/
toString(): string;
}

@@ -10,3 +10,15 @@ "use strict";

const utils_1 = require("./utils");
/**
* A representation of a Transfer, which moves an Amount of an Asset from
* a user-controlled Wallet to another Address. The fee is assumed to be paid
* in the native Asset of the Network.
*/
class Transfer {
/**
* Private constructor to prevent direct instantiation outside of the factory methods.
*
* @ignore
* @param transferModel - The Transfer model.
* @hideconstructor
*/
constructor(transferModel) {

@@ -18,23 +30,64 @@ if (!transferModel) {

}
/**
* Converts a TransferModel into a Transfer object.
*
* @param transferModel - The Transfer model object.
* @returns The Transfer object.
*/
static fromModel(transferModel) {
return new Transfer(transferModel);
}
/**
* Returns the ID of the Transfer.
*
* @returns The Transfer ID.
*/
getId() {
return this.model.transfer_id;
}
/**
* Returns the Network ID of the Transfer.
*
* @returns The Network ID.
*/
getNetworkId() {
return this.model.network_id;
}
/**
* Returns the Wallet ID of the Transfer.
*
* @returns The Wallet ID.
*/
getWalletId() {
return this.model.wallet_id;
}
/**
* Returns the From Address ID of the Transfer.
*
* @returns The From Address ID.
*/
getFromAddressId() {
return this.model.address_id;
}
/**
* Returns the Destination Address ID of the Transfer.
*
* @returns The Destination Address ID.
*/
getDestinationAddressId() {
return this.model.destination;
}
/**
* Returns the Asset ID of the Transfer.
*
* @returns The Asset ID.
*/
getAssetId() {
return this.model.asset_id;
}
/**
* Returns the Amount of the Transfer.
*
* @returns The Amount of the Asset.
*/
getAmount() {

@@ -44,11 +97,32 @@ const amount = new decimal_js_1.Decimal(this.model.amount);

}
/**
* Returns the Unsigned Payload of the Transfer.
*
* @returns The Unsigned Payload as a Hex string.
*/
getUnsignedPayload() {
return this.model.unsigned_payload;
}
/**
* Returns the Signed Payload of the Transfer.
*
* @returns The Signed Payload as a Hex string, or undefined if not yet available.
*/
getSignedPayload() {
return this.model.signed_payload;
}
/**
* Returns the Transaction Hash of the Transfer.
*
* @returns The Transaction Hash as a Hex string, or undefined if not yet available.
*/
getTransactionHash() {
return this.model.transaction_hash;
}
/**
* Returns the Transaction of the Transfer.
*
* @returns The ethers.js Transaction object.
* @throws (InvalidUnsignedPayload) If the Unsigned Payload is invalid.
*/
getTransaction() {

@@ -70,5 +144,15 @@ if (this.transaction)

}
/**
* Sets the Signed Transaction of the Transfer.
*
* @param transaction - The Signed Transaction.
*/
setSignedTransaction(transaction) {
this.transaction = transaction;
}
/**
* Returns the Status of the Transfer.
*
* @returns The Status of the Transfer.
*/
getStatus() {

@@ -88,5 +172,15 @@ switch (this.model.status) {

}
/**
* Returns the link to the Transaction on the blockchain explorer.
*
* @returns The link to the Transaction on the blockchain explorer.
*/
getTransactionLink() {
return `https://sepolia.basescan.org/tx/${this.getTransactionHash()}`;
}
/**
* Reloads the Transfer model with the latest data from the server.
*
* @throws {APIError} if the API request to get a Transfer fails.
*/
async reload() {

@@ -96,2 +190,7 @@ const result = await coinbase_1.Coinbase.apiClients.transfer.getTransfer(this.getWalletId(), this.getFromAddressId(), this.getId());

}
/**
* Returns a string representation of the Transfer.
*
* @returns The string representation of the Transfer.
*/
toString() {

@@ -98,0 +197,0 @@ return (`Transfer{transferId: '${this.getId()}', networkId: '${this.getNetworkId()}', ` +

@@ -7,53 +7,357 @@ import { Decimal } from "decimal.js";

export type AssetAPIClient = {
/**
* Get the asset for the specified asset ID.
*
* @summary Get the asset for the specified asset ID.
* @param networkId - networkId The ID of the blockchain network.
* @param assetId - assetId The ID of the asset to fetch.
* @param options - Override http request option.
* @throws {RequiredError} If the required parameter is not provided.
*/
getAsset(networkId: string, assetId: string, options?: RawAxiosRequestConfig): AxiosPromise<AssetModel>;
};
export type TradeApiClients = {
/**
* Broadcast a trade.
*
* @param walletId - The ID of the wallet the address belongs to.
* @param addressId - The ID of the address the trade belongs to.
* @param tradeId - The ID of the trade to broadcast.
* @param broadcastTradeRequest - The request body.
* @param options - Override http request option.
* @throws {RequiredError} If the required parameter is not provided.
*/
broadcastTrade(walletId: string, addressId: string, tradeId: string, broadcastTradeRequest: BroadcastTradeRequest, options?: RawAxiosRequestConfig): AxiosPromise<TradeModel>;
/**
* Create a new trade.
*
* @param walletId - The ID of the wallet the source address belongs to.
* @param addressId - The ID of the address to conduct the trade from.
* @param createTradeRequest - The request body.
* @param options - Override http request option.
* @throws {RequiredError} If the required parameter is not provided.
*/
createTrade(walletId: string, addressId: string, createTradeRequest: CreateTradeRequest, options?: RawAxiosRequestConfig): AxiosPromise<TradeModel>;
/**
* Get a trade by ID.
*
* @param walletId - The ID of the wallet the address belongs to.
* @param addressId - The ID of the address the trade belongs to.
* @param tradeId - The ID of the trade to fetch.
* @param options - Override http request option.
* @throws {RequiredError} If the required parameter is not provided.
*/
getTrade(walletId: string, addressId: string, tradeId: string, options?: RawAxiosRequestConfig): AxiosPromise<TradeModel>;
/**
* List trades for an address.
*
* @param walletId - The ID of the wallet the address belongs to.
* @param addressId - The ID of the address to list trades for.
* @param limit - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.
* @param page - A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.
* @param options - Override http request option.
* @throws {RequiredError} If the required parameter is not provided.
*/
listTrades(walletId: string, addressId: string, limit?: number, page?: string, options?: RawAxiosRequestConfig): AxiosPromise<TradeListModel>;
};
/**
* WalletAPI client type definition.
*/
export type WalletAPIClient = {
/**
* Create a new wallet scoped to the user.
*
* @class
* @param createdWalletRequest - The wallet creation request.
* @param options - Axios request options.
* @throws {APIError} If the request fails.
*/
createWallet: (createWalletRequest?: CreateWalletRequest, options?: RawAxiosRequestConfig) => AxiosPromise<WalletModel>;
/**
* Returns the wallet model with the given ID.
*
* @param walletId - The ID of the wallet to fetch.
* @param options - Override http request option.
* @throws {APIError} If the request fails.
*/
getWallet: (walletId: string, options?: RawAxiosRequestConfig) => AxiosPromise<WalletModel>;
/**
* List the balances of all of the addresses in the wallet aggregated by asset.
*
* @param walletId - The ID of the wallet to fetch the balances for.
* @param options - Override http request option.
* @throws {RequiredError} If the required parameter is not provided.
* @throws {APIError} If the request fails.
*/
listWalletBalances(walletId: string, options?: RawAxiosRequestConfig): AxiosPromise<AddressBalanceList>;
/**
* List the balances of all of the addresses in the wallet aggregated by asset.
*
* @param walletId - The ID of the wallet to fetch the balances for.
* @param options - Override http request option.
* @throws {RequiredError} If the required parameter is not provided.
* @throws {APIError} If the request fails.
*/
listWalletBalances(walletId: string, options?: RawAxiosRequestConfig): AxiosPromise<AddressBalanceList>;
/**
* Get the aggregated balance of an asset across all of the addresses in the wallet.
*
* @param walletId - The ID of the wallet to fetch the balance for.
* @param assetId - The symbol of the asset to fetch the balance for.
* @param options - Override http request option.
* @throws {RequiredError} If the required parameter is not provided.
* @throws {APIError} If the request fails.
*/
getWalletBalance(walletId: string, assetId: string, options?: RawAxiosRequestConfig): AxiosPromise<Balance>;
/**
* List wallets belonging to the user.
*
* @param limit - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.
* @param page - A cursor for pagination across multiple pages of results. Don\&#39;t include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.
* @param options - Override http request option.
* @throws {APIError} If the request fails.
* @throws {RequiredError} If the required parameter is not provided.
*/
listWallets(limit?: number, page?: string, options?: RawAxiosRequestConfig): AxiosPromise<WalletList>;
};
/**
* AddressAPI client type definition.
*/
export type AddressAPIClient = {
/**
* Requests faucet funds for the address.
*
* @param walletId - The wallet ID.
* @param addressId - The address ID.
* @returns The transaction hash.
* @throws {APIError} If the request fails.
*/
requestFaucetFunds(walletId: string, addressId: string): AxiosPromise<FaucetTransaction>;
/**
* Get address by onchain address.
*
* @param walletId - The ID of the wallet the address belongs to.
* @param addressId - The onchain address of the address that is being fetched.
* @param options - Axios request options.
* @throws {APIError} If the request fails.
*/
getAddress(walletId: string, addressId: string, options?: AxiosRequestConfig): AxiosPromise<AddressModel>;
/**
* Lists addresses.
*
* @param walletId - The ID of the wallet the addresses belong to.
* @param limit - The maximum number of addresses to return.
* @param page - A cursor for pagination across multiple pages of results. Do not include this parameter on the first call.
* Use the next_page value returned in a previous response to request subsequent results.
* @param options - Override http request option.
* @throws {APIError} If the request fails.
*/
listAddresses(walletId: string, limit?: number, page?: string, options?: AxiosRequestConfig): AxiosPromise<AddressList>;
/**
* Get address balance
*
* @param walletId - The ID of the wallet to fetch the balance for.
* @param addressId - The onchain address of the address that is being fetched.
* @param assetId - The symbol of the asset to fetch the balance for.
* @param options - Axios request options.
* @throws {APIError}
*/
getAddressBalance(walletId: string, addressId: string, assetId: string, options?: AxiosRequestConfig): AxiosPromise<Balance>;
/**
* Lists address balances
*
* @param walletId - The ID of the wallet to fetch the balances for.
* @param addressId - The onchain address of the address that is being fetched.
* @param page - A cursor for pagination across multiple pages of results. Do not include this parameter on the first call.
* Use the next_page value returned in a previous response to request subsequent results.
* @param options - Override http request option.
* @throws {APIError}
*/
listAddressBalances(walletId: string, addressId: string, page?: string, options?: AxiosRequestConfig): AxiosPromise<AddressBalanceList>;
/**
* Create a new address scoped to the wallet.
*
* @param walletId - The ID of the wallet to create the address in.
* @param createAddressRequest - The address creation request.
* @param options - Axios request options.
* @throws {APIError} If the request fails.
*/
createAddress(walletId: string, createAddressRequest?: CreateAddressRequest, options?: AxiosRequestConfig): AxiosPromise<AddressModel>;
};
/**
* ExternalAddressAPIClient client type definition.
*/
export type ExternalAddressAPIClient = {
/**
* List all of the balances of an external address
*
* @param networkId - The ID of the blockchain network
* @param addressId - The ID of the address to fetch the balance for
* @param page - A cursor for pagination across multiple pages of results. Don\&#39;t include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.
* @param options - Override http request option.
* @throws {APIError} If the request fails.
*/
listExternalAddressBalances(networkId: string, addressId: string, page?: string, options?: RawAxiosRequestConfig): AxiosPromise<AddressBalanceList>;
/**
* Get the balance of an asset in an external address
*
* @param networkId - The ID of the blockchain network
* @param addressId - The ID of the address to fetch the balance for
* @param assetId - The ID of the asset to fetch the balance for
* @param options - Override http request option.
* @throws {APIError} If the request fails.
*/
getExternalAddressBalance(networkId: string, addressId: string, assetId: string, options?: RawAxiosRequestConfig): AxiosPromise<Balance>;
/**
* Request faucet funds to be sent to external address.
*
* @param networkId - The ID of the blockchain network
* @param addressId - The onchain address of the address that is being fetched.
* @param options - Override http request option.
* @throws {APIError} If the request fails.
*/
requestExternalFaucetFunds(networkId: string, addressId: string, options?: RawAxiosRequestConfig): AxiosPromise<FaucetTransaction>;
};
/**
* UserAPI client type definition.
*/
export type UserAPIClient = {
/**
* Retrieves the current user.
*
* @param options - Axios request options.
* @returns - A promise resolvindg to the User model.
* @throws {APIError} If the request fails.
*/
getCurrentUser(options?: AxiosRequestConfig): AxiosPromise<UserModel>;
};
export type StakeAPIClient = {
/**
* Build a new staking operation.
*
* @param buildStakingOperationRequest - The request to build a staking operation.
* @param options - Axios request options.
* @throws {APIError} If the request fails.
*/
buildStakingOperation(buildStakingOperationRequest: BuildStakingOperationRequest, options?: AxiosRequestConfig): AxiosPromise<StakingOperationModel>;
/**
* Get a staking operation.
*
* @param networkId - The ID of the blockchain network
* @param addressId - The ID of the address the staking operation corresponds to.
* @param stakingOperationID - The ID of the staking operation to fetch.
* @param options - Axios request options.
* @throws {APIError} If the request fails.
*/
getExternalStakingOperation(networkId: string, addressId: string, stakingOperationID: string, options?: AxiosRequestConfig): AxiosPromise<StakingOperationModel>;
/**
* Get staking context for an address.
*
* @param getStakingContextRequest - The request to get the staking context for an address.
* @param options - Axios request options.
* @throws {APIError} If the request fails.
*/
getStakingContext(getStakingContextRequest: GetStakingContextRequest, options?: AxiosRequestConfig): AxiosPromise<StakingContextModel>;
/**
* Get the staking rewards for an address.
*
* @param fetchStakingRewardsRequest - The request to get the staking rewards for an address.
* @param limit - The amount of records to return in a single call.
* @param page - The batch of records for a given section in the response.
* @param options - Axios request options.
*/
fetchStakingRewards(fetchStakingRewardsRequest: FetchStakingRewardsRequest, limit?: number, page?: string, options?: AxiosRequestConfig): AxiosPromise<FetchStakingRewards200Response>;
};
export type ValidatorAPIClient = {
/**
* List the validators for a given network and asset.
*
* @param networkId - The ID of the blockchain network.
* @param assetId - The ID of the asset to fetch the validator for.
* @param status - The status to filter by.
* @param limit - The amount of records to return in a single call.
* @param page - The batch of records for a given section in the response.
* @param options - Axios request options.
*/
listValidators(networkId: string, assetId: string, status?: string, limit?: number, page?: string, options?: AxiosRequestConfig): AxiosPromise<ValidatorList>;
/**
* Get the validator for a given network, asset, and address.
*
* @param networkId - The ID of the blockchain network.
* @param assetId - The ID of the asset to fetch the validator for.
* @param id - The unique publicly identifiable id of the validator for which to fetch the data.
* @param options - Axios request options.
*/
getValidator(networkId: string, assetId: string, id: string, options?: RawAxiosRequestConfig): AxiosPromise<Validator>;
};
/**
* TransferAPI client type definition.
*/
export type TransferAPIClient = {
/**
* Broadcasts a transfer.
*
* @param walletId - The ID of the wallet the address belongs to.
* @param addressId - The ID of the address the transfer belongs to.
* @param transferId - The ID of the transfer to broadcast.
* @param broadcastTransferRequest - The request body.
* @param options - Axios request options.
* @returns - A promise resolving to the Transfer model.
* @throws {APIError} If the request fails.
*/
broadcastTransfer(walletId: string, addressId: string, transferId: string, broadcastTransferRequest: BroadcastTransferRequest, options?: AxiosRequestConfig): AxiosPromise<TransferModel>;
/**
* Creates a Transfer.
*
* @param walletId - The ID of the wallet the address belongs to.
* @param addressId - The ID of the address the transfer belongs to.
* @param createTransferRequest - The request body.
* @param options - Axios request options.
* @returns - A promise resolving to the Transfer model.
* @throws {APIError} If the request fails.
*/
createTransfer(walletId: string, addressId: string, createTransferRequest: CreateTransferRequest, options?: AxiosRequestConfig): AxiosPromise<TransferModel>;
/**
* Retrieves a Transfer.
*
* @param walletId - The ID of the wallet the address belongs to.
* @param addressId - The ID of the address the transfer belongs to.
* @param transferId - The ID of the transfer to retrieve.
* @param options - Axios request options.
* @returns - A promise resolving to the Transfer model.
* @throws {APIError} If the request fails.
*/
getTransfer(walletId: string, addressId: string, transferId: string, options?: AxiosRequestConfig): AxiosPromise<TransferModel>;
/**
* Lists Transfers.
*
* @param walletId - The ID of the wallet the address belongs to.
* @param addressId - The ID of the address the transfers belong to.
* @param limit - The maximum number of transfers to return.
* @param page - The cursor for pagination across multiple pages of Transfers.
* @param options - Axios request options.
* @returns - A promise resolving to the Transfer list.
* @throws {APIError} If the request fails.
*/
listTransfers(walletId: string, addressId: string, limit?: number, page?: string, options?: AxiosRequestConfig): AxiosPromise<TransferList>;
};
/**
* ServerSignerAPI client type definition.
*/
export type ServerSignerAPIClient = {
/**
* Lists Server-Signers.
*
* @param limit - The maximum number of Server-Signers to return.
* @param page - The cursor for pagination across multiple pages of Server-Signers.
* @param options - Axios request options.
* @returns - A promise resolving to the Server-Signer list.
* @throws {APIError} If the request fails.
*/
listServerSigners(limit?: number, page?: string, options?: AxiosRequestConfig): AxiosPromise<ServerSignerList>;
};
/**
* API clients type definition for the Coinbase SDK.
* Represents the set of API clients available in the SDK.
*/
export type ApiClients = {

@@ -71,2 +375,5 @@ user?: UserAPIClient;

};
/**
* Transfer status type definition.
*/
export declare enum TransferStatus {

@@ -78,2 +385,5 @@ PENDING = "pending",

}
/**
* Transaction status type definition.
*/
export declare enum TransactionStatus {

@@ -85,2 +395,6 @@ PENDING = "pending",

}
/**
* The Wallet Data type definition.
* The data required to recreate a Wallet.
*/
export type WalletData = {

@@ -90,2 +404,5 @@ walletId: string;

};
/**
* The Seed Data type definition.
*/
export type SeedData = {

@@ -97,4 +414,13 @@ seed: string;

};
/**
* Amount type definition.
*/
export type Amount = number | bigint | Decimal;
/**
* Destination type definition.
*/
export type Destination = string | Address | Wallet;
/**
* ServerSigner status type definition.
*/
export declare enum ServerSignerStatus {

@@ -104,2 +430,5 @@ PENDING = "pending_seed_creation",

}
/**
* Options for creating a Wallet.
*/
export type WalletCreateOptions = {

@@ -110,20 +439,68 @@ networkId?: string;

};
/**
* CoinbaseOptions type definition.
*/
export type CoinbaseOptions = {
/**
* The API key name.
*/
apiKeyName: string;
/**
* The private key associated with the API key.
*/
privateKey: string;
/**
* Whether to use a Server-Signer or not.
*/
useServerSigner?: boolean;
/**
* If true, logs API requests and responses to the console.
*/
debugging?: boolean;
/**
* The base path for the API.
*/
basePath?: string;
};
/**
* CoinbaseConfigureFromJsonOptions type definition.
*/
export type CoinbaseConfigureFromJsonOptions = {
/**
* The path to the JSON file containing the API key and private key.
*/
filePath?: string;
/**
* Whether to use a Server-Signer or not.
*/
useServerSigner?: boolean;
/**
* If true, logs API requests and responses to the console.
*/
debugging?: boolean;
/**
* The base path for the API.
*/
basePath?: string;
};
/**
* StakeOptionsMode type definition.
*/
export declare enum StakeOptionsMode {
/**
* Defaults to the mode specific to the asset.
*/
DEFAULT = "default",
/**
* Partial represents Partial Ethereum Staking mode.
*/
PARTIAL = "partial",
/**
* Native represents Native Ethereum Staking mode.
*/
NATIVE = "native"
}
/**
* Options for creating a Transfer.
*/
export type CreateTransferOptions = {

@@ -136,1 +513,11 @@ amount: Amount;

};
/**
* Options for creating a Trade.
*/
export type CreateTradeOptions = {
amount: Amount;
fromAssetId: string;
toAssetId: string;
timeoutSeconds?: number;
intervalSeconds?: number;
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StakeOptionsMode = exports.ServerSignerStatus = exports.TransactionStatus = exports.TransferStatus = void 0;
/**
* Transfer status type definition.
*/
var TransferStatus;

@@ -11,2 +14,5 @@ (function (TransferStatus) {

})(TransferStatus || (exports.TransferStatus = TransferStatus = {}));
/**
* Transaction status type definition.
*/
var TransactionStatus;

@@ -19,2 +25,5 @@ (function (TransactionStatus) {

})(TransactionStatus || (exports.TransactionStatus = TransactionStatus = {}));
/**
* ServerSigner status type definition.
*/
var ServerSignerStatus;

@@ -25,7 +34,19 @@ (function (ServerSignerStatus) {

})(ServerSignerStatus || (exports.ServerSignerStatus = ServerSignerStatus = {}));
/**
* StakeOptionsMode type definition.
*/
var StakeOptionsMode;
(function (StakeOptionsMode) {
/**
* Defaults to the mode specific to the asset.
*/
StakeOptionsMode["DEFAULT"] = "default";
/**
* Partial represents Partial Ethereum Staking mode.
*/
StakeOptionsMode["PARTIAL"] = "partial";
/**
* Native represents Native Ethereum Staking mode.
*/
StakeOptionsMode["NATIVE"] = "native";
})(StakeOptionsMode || (exports.StakeOptionsMode = StakeOptionsMode = {}));

@@ -7,7 +7,39 @@ import { User as UserModel } from "./../client/api";

};
/**
* A representation of a User.
* Users have Wallets, which can hold balances of Assets.
* Access the default User through Coinbase.defaultUser().
*/
export declare class User {
private model;
/**
* Initializes a new User instance.
*
* @param user - The user model.
*/
constructor(user: UserModel);
/**
* Creates a new Wallet belonging to the User.
*
* @param createWalletOptions - The options for creating the Wallet.
* @param createWalletOptions.networkId - the ID of the blockchain network. Defaults to 'base-sepolia'.
* @throws {APIError} - If the request fails.
* @throws {ArgumentError} - If the model or client is not provided.
* @throws {InternalError} - If address derivation or caching fails.
* @returns the new Wallet
*/
createWallet(createWalletOptions?: CreateWalletOptionsType): Promise<Wallet>;
/**
* Returns the user's ID.
*
* @returns The user's ID.
*/
getId(): string;
/**
* Lists the Wallets belonging to the User.
*
* @param pageSize - The number of Wallets to return per page. Defaults to 10
* @param nextPageToken - The token for the next page of Wallets
* @returns An object containing the Wallets and the token for the next page
*/
listWallets(pageSize?: number, nextPageToken?: string): Promise<{

@@ -17,6 +49,28 @@ wallets: Wallet[];

}>;
/**
* Returns the Wallet with the given ID.
*
* @param wallet_id - the ID of the Wallet
* @returns the Wallet with the given ID
*/
getWallet(wallet_id: string): Promise<Wallet>;
/**
* Imports a Wallet belonging to a User.
*
* @param data - The Wallet data to import.
* @param data.walletId - The ID of the Wallet to import.
* @param data.seed - The seed to use for the Wallet.
* @returns The imported Wallet.
* @throws {ArgumentError} If the Wallet ID is not provided.
* @throws {ArgumentError} If the seed is not provided.
* @throws {APIError} If the request fails.
*/
importWallet(data: WalletData): Promise<Wallet>;
/**
* Returns a string representation of the User.
*
* @returns The string representation of the User.
*/
toString(): string;
}
export {};

@@ -5,15 +5,53 @@ "use strict";

const wallet_1 = require("./wallet");
/**
* A representation of a User.
* Users have Wallets, which can hold balances of Assets.
* Access the default User through Coinbase.defaultUser().
*/
class User {
/**
* Initializes a new User instance.
*
* @param user - The user model.
*/
constructor(user) {
this.model = user;
}
/**
* Creates a new Wallet belonging to the User.
*
* @param createWalletOptions - The options for creating the Wallet.
* @param createWalletOptions.networkId - the ID of the blockchain network. Defaults to 'base-sepolia'.
* @throws {APIError} - If the request fails.
* @throws {ArgumentError} - If the model or client is not provided.
* @throws {InternalError} - If address derivation or caching fails.
* @returns the new Wallet
*/
async createWallet(createWalletOptions = {}) {
return await wallet_1.Wallet.create(createWalletOptions);
}
/**
* Returns the user's ID.
*
* @returns The user's ID.
*/
getId() {
return this.model.id;
}
/**
* Lists the Wallets belonging to the User.
*
* @param pageSize - The number of Wallets to return per page. Defaults to 10
* @param nextPageToken - The token for the next page of Wallets
* @returns An object containing the Wallets and the token for the next page
*/
async listWallets(pageSize = 10, nextPageToken) {
return await wallet_1.Wallet.listWallets(pageSize, nextPageToken);
}
/**
* Returns the Wallet with the given ID.
*
* @param wallet_id - the ID of the Wallet
* @returns the Wallet with the given ID
*/
async getWallet(wallet_id) {

@@ -24,5 +62,21 @@ const wallet = await wallet_1.Wallet.fetch(wallet_id);

}
/**
* Imports a Wallet belonging to a User.
*
* @param data - The Wallet data to import.
* @param data.walletId - The ID of the Wallet to import.
* @param data.seed - The seed to use for the Wallet.
* @returns The imported Wallet.
* @throws {ArgumentError} If the Wallet ID is not provided.
* @throws {ArgumentError} If the seed is not provided.
* @throws {APIError} If the request fails.
*/
async importWallet(data) {
return await wallet_1.Wallet.import(data);
}
/**
* Returns a string representation of the User.
*
* @returns The string representation of the User.
*/
toString() {

@@ -29,0 +83,0 @@ return `User{ userId: ${this.model.id} }`;

import { Axios, AxiosResponse, InternalAxiosRequestConfig } from "axios";
/**
* Prints Axios response to the console for debugging purposes.
*
* @param response - The Axios response object.
* @param debugging - Flag to enable or disable logging.
* @returns The Axios response object.
*/
export declare const logApiResponse: (response: AxiosResponse, debugging?: boolean) => AxiosResponse;
/**
* Axios Request interceptor function type.
*
* @param value - The Axios request configuration.
* @returns The modified Axios request configuration.
*/
type RequestFunctionType = (value: InternalAxiosRequestConfig<any>) => Promise<InternalAxiosRequestConfig> | InternalAxiosRequestConfig;
/**
* Axios Response interceptor function type.
*
* @param value - The Axios response object.
* @returns The modified Axios response object.
*/
type ResponseFunctionType = (value: AxiosResponse<any, any>) => AxiosResponse<any, any>;
/**
* Registers request and response interceptors to an Axios instance.
*
* @param axiosInstance - The Axios instance to register the interceptors.
* @param requestFn - The request interceptor function.
* @param responseFn - The response interceptor function.
*/
export declare const registerAxiosInterceptors: (axiosInstance: Axios, requestFn: RequestFunctionType, responseFn: ResponseFunctionType) => void;
/**
* Converts a Uint8Array to a hex string.
*
* @param key - The key to convert.
* @returns The converted hex string.
*/
export declare const convertStringToHex: (key: Uint8Array) => string;
/**
* Delays the execution of the function by the specified number of seconds.
*
* @param seconds - The number of seconds to delay the execution.
* @returns A promise that resolves after the specified number of seconds.
*/
export declare function delay(seconds: number): Promise<void>;
/**
* Parses an Unsigned Payload and returns the JSON object.
*
* @throws {InvalidUnsignedPayload} If the Unsigned Payload is invalid.
* @param payload - The Unsigned Payload.
* @returns The parsed JSON object.
*/
export declare function parseUnsignedPayload(payload: string): Record<string, any>;
export {};

@@ -6,2 +6,9 @@ "use strict";

const errors_1 = require("./errors");
/**
* Prints Axios response to the console for debugging purposes.
*
* @param response - The Axios response object.
* @param debugging - Flag to enable or disable logging.
* @returns The Axios response object.
*/
const logApiResponse = (response, debugging = false) => {

@@ -21,2 +28,9 @@ if (debugging) {

exports.logApiResponse = logApiResponse;
/**
* Registers request and response interceptors to an Axios instance.
*
* @param axiosInstance - The Axios instance to register the interceptors.
* @param requestFn - The request interceptor function.
* @param responseFn - The response interceptor function.
*/
const registerAxiosInterceptors = (axiosInstance, requestFn, responseFn) => {

@@ -29,2 +43,8 @@ axiosInstance.interceptors.request.use(requestFn);

exports.registerAxiosInterceptors = registerAxiosInterceptors;
/**
* Converts a Uint8Array to a hex string.
*
* @param key - The key to convert.
* @returns The converted hex string.
*/
const convertStringToHex = (key) => {

@@ -34,2 +54,8 @@ return Buffer.from(key).toString("hex");

exports.convertStringToHex = convertStringToHex;
/**
* Delays the execution of the function by the specified number of seconds.
*
* @param seconds - The number of seconds to delay the execution.
* @returns A promise that resolves after the specified number of seconds.
*/
async function delay(seconds) {

@@ -39,2 +65,9 @@ return new Promise(resolve => setTimeout(resolve, seconds * 1000));

exports.delay = delay;
/**
* Parses an Unsigned Payload and returns the JSON object.
*
* @throws {InvalidUnsignedPayload} If the Unsigned Payload is invalid.
* @param payload - The Unsigned Payload.
* @returns The parsed JSON object.
*/
function parseUnsignedPayload(payload) {

@@ -41,0 +74,0 @@ const rawPayload = payload.match(/../g)?.map(byte => parseInt(byte, 16));

import { Validator as ValidatorModel } from "../client/api";
/**
* A representation of a validator onchain.
*/
export declare class Validator {
private model;
/**
* Creates a Validator object.
*
* @class
* @param model - The underlying Validator object.
* @throws {InternalError} - If the Validator model is empty.
*/
constructor(model: ValidatorModel);
/**
* Returns the list of Validators.
*
* @param networkId - The network ID.
* @param assetId - The asset ID.
* @param status - The status to filter by.
* @returns The list of Validators.
*/
static list(networkId: string, assetId: string, status?: string): Promise<Validator[]>;
/**
*
* Returns the details of a specific validator.
*
* @param networkId - The network ID.
* @param assetId - The asset ID.
* @param id - The unique publicly identifiable id of the validator for which to fetch the data.
* @returns The requested validator details.
*/
static fetch(networkId: string, assetId: string, id: string): Promise<Validator>;
/**
* Returns the Validator ID.
*
* @returns The Validator ID.
*/
getValidatorId(): string;
/**
* Returns the Validator status.
*
* @returns The Validator status.
*/
getStatus(): string;
/**
* Returns the string representation of the Validator.
*
* @returns The string representation of the Validator.
*/
toString(): string;
}

@@ -6,3 +6,13 @@ "use strict";

const errors_1 = require("./errors");
/**
* A representation of a validator onchain.
*/
class Validator {
/**
* Creates a Validator object.
*
* @class
* @param model - The underlying Validator object.
* @throws {InternalError} - If the Validator model is empty.
*/
constructor(model) {

@@ -14,2 +24,10 @@ if (!model) {

}
/**
* Returns the list of Validators.
*
* @param networkId - The network ID.
* @param assetId - The asset ID.
* @param status - The status to filter by.
* @returns The list of Validators.
*/
static async list(networkId, assetId, status) {

@@ -23,2 +41,11 @@ const validators = [];

}
/**
*
* Returns the details of a specific validator.
*
* @param networkId - The network ID.
* @param assetId - The asset ID.
* @param id - The unique publicly identifiable id of the validator for which to fetch the data.
* @returns The requested validator details.
*/
static async fetch(networkId, assetId, id) {

@@ -28,8 +55,23 @@ const response = await coinbase_1.Coinbase.apiClients.validator.getValidator(networkId, assetId, id);

}
/**
* Returns the Validator ID.
*
* @returns The Validator ID.
*/
getValidatorId() {
return this.model.validator_id;
}
/**
* Returns the Validator status.
*
* @returns The Validator status.
*/
getStatus() {
return this.model.status;
}
/**
* Returns the string representation of the Validator.
*
* @returns The string representation of the Validator.
*/
toString() {

@@ -36,0 +78,0 @@ return `Id: ${this.getValidatorId()}, Status: ${this.getStatus()}`;

@@ -9,3 +9,8 @@ import Decimal from "decimal.js";

import { Transfer } from "./transfer";
import { Amount, CreateTransferOptions, ServerSignerStatus, WalletCreateOptions, WalletData } from "./types";
import { CreateTransferOptions, CreateTradeOptions, ServerSignerStatus, WalletCreateOptions, WalletData } from "./types";
/**
* A representation of a Wallet. Wallets come with a single default Address, but can expand to have a set of Addresses,
* each of which can hold a balance of one or more Assets. Wallets can create new Addresses, list their addresses,
* list their balances, and transfer Assets to other Addresses. Wallets should be created through User.createWallet or User.importWallet.
*/
export declare class Wallet {

@@ -18,3 +23,19 @@ static MAX_ADDRESSES: number;

private readonly addressPathPrefix;
/**
* Private constructor to prevent direct instantiation outside of factory method. Use Wallet.init instead.
*
* @ignore
* @param model - The wallet model object.
* @param master - The HD master key.
* @param seed - The seed to use for the Wallet. Expects a 32-byte hexadecimal with no 0x prefix.
* @hideconstructor
*/
private constructor();
/**
* Lists the Wallets belonging to the User.
*
* @param pageSize - The number of Wallets to return per page. Defaults to 10
* @param nextPageToken - The token for the next page of Wallets
* @returns An object containing the Wallets and the token for the next page
*/
static listWallets(pageSize?: number, nextPageToken?: string): Promise<{

@@ -24,33 +45,257 @@ wallets: Wallet[];

}>;
/**
* Fetches a Wallet by its ID. The returned wallet can be immediately used for signing operations if backed by a server signer.
* If the wallet is not backed by a server signer, the wallet's seed will need to be set before it can be used for signing operations.
*
* @param wallet_id - The ID of the Wallet to fetch
* @returns The fetched Wallet
*/
static fetch(wallet_id: string): Promise<Wallet>;
/**
* Imports a Wallet for the given Wallet data.
*
* @param data - The Wallet data to import.
* @param data.walletId - The ID of the Wallet to import.
* @param data.seed - The seed to use for the Wallet.
* @returns The imported Wallet.
* @throws {ArgumentError} If the Wallet ID is not provided.
* @throws {ArgumentError} If the seed is not provided.
* @throws {APIError} If the request fails.
*/
static import(data: WalletData): Promise<Wallet>;
/**
* Returns a newly created Wallet object. Do not use this method directly.
* Instead, use User.createWallet.
*
* @constructs Wallet
* @param options - The options to create the Wallet.
* @param options.networkId - the ID of the blockchain network. Defaults to 'base-sepolia'.
* @param options.intervalSeconds - The interval at which to poll the CDPService, in seconds.
* @param options.timeoutSeconds - The maximum amount of time to wait for the ServerSigner to create a seed, in seconds.
* @throws {ArgumentError} If the model or client is not provided.
* @throws {InternalError} - If address derivation or caching fails.
* @throws {APIError} - If the request fails.
* @returns A promise that resolves with the new Wallet object.
*/
static create({ networkId, timeoutSeconds, intervalSeconds, }?: WalletCreateOptions): Promise<Wallet>;
/**
* Returns a new Wallet object. Do not use this method directly. Instead, use User.createWallet or User.importWallet.
*
* @constructs Wallet
* @param model - The underlying Wallet model object
* @param seed - The seed to use for the Wallet. Expects a 32-byte hexadecimal with no 0x prefix. If null or undefined, a new seed will be generated.
* If the empty string, no seed is generated, and the Wallet will be instantiated without a seed and its corresponding private keys.
* @throws {ArgumentError} If the model or client is not provided.
* @throws {InternalError} - If address derivation or caching fails.
* @throws {APIError} - If the request fails.
* @returns A promise that resolves with the new Wallet object.
*/
static init(model: WalletModel, seed?: string | undefined): Wallet;
/**
* Exports the Wallet's data to a WalletData object.
*
* @returns The Wallet's data.
* @throws {APIError} - If the request fails.
*/
export(): WalletData;
/**
* Creates a new Address in the Wallet.
*
* @returns The new Address.
* @throws {APIError} - If the address creation fails.
*/
createAddress(): Promise<Address>;
/**
* Set the seed for the Wallet.
*
* @param seed - The seed to use for the Wallet. Expects a 32-byte hexadecimal with no 0x prefix.
* @throws {ArgumentError} If the seed is empty.
* @throws {InternalError} If the seed is already set.
*/
setSeed(seed: string): void;
/**
* Returns the Address with the given ID.
*
* @param addressId - The ID of the Address to retrieve.
* @returns The Address.
*/
getAddress(addressId: string): Address | undefined;
/**
* Returns the list of Addresses in the Wallet.
*
* @returns The list of Addresses.
*/
listAddresses(): Promise<WalletAddress[]>;
createTrade(amount: Amount, fromAssetId: string, toAssetId: string): Promise<Trade>;
/**
* Trades the given amount of the given Asset for another Asset. Currently only the default address is used to source the Trade
*
* @param options - The options to create the Trade.
* @param options.amount - The amount of the Asset to send.
* @param options.fromAssetId - The ID of the Asset to trade from.
* @param options.toAssetId - The ID of the Asset to trade to.
* @param options.timeoutSeconds - The maximum amount of time to wait for the Trade to complete, in seconds.
* @param options.intervalSeconds - The interval at which to poll the Network for Trade status, in seconds.
* @throws {InternalError} If the default address is not found.
* @throws {Error} If the private key is not loaded, or if the asset IDs are unsupported, or if there are insufficient funds.
* @returns The Trade object.
*/
createTrade({ amount, fromAssetId, toAssetId, timeoutSeconds, intervalSeconds, }: CreateTradeOptions): Promise<Trade>;
/**
* Returns the list of balances of this Wallet. Balances are aggregated across all Addresses in the Wallet.
*
* @returns The list of balances. The key is the Asset ID, and the value is the balance.
*/
listBalances(): Promise<BalanceMap>;
/**
* Returns the balance of the provided Asset. Balances are aggregated across all Addresses in the Wallet.
*
* @param assetId - The ID of the Asset to retrieve the balance for.
* @returns The balance of the Asset.
*/
getBalance(assetId: string): Promise<Decimal>;
/**
* Returns the Network ID of the Wallet.
*
* @returns The network ID.
*/
getNetworkId(): string;
/**
* Returns the ServerSigner Status of the Wallet.
*
* @returns the ServerSigner Status.
*/
getServerSignerStatus(): ServerSignerStatus | undefined;
/**
* Returns the wallet ID.
*
* @returns The wallet ID.
*/
getId(): string | undefined;
/**
* Saves the seed of the Wallet to the given file. Wallets whose seeds are saved this way can be
* rehydrated using load_seed. A single file can be used for multiple Wallet seeds.
* This is an insecure method of storing Wallet seeds and should only be used for development purposes.
*
* @param filePath - The path of the file to save the seed to
* @param encrypt - Whether the seed information persisted to the local file system should be
* encrypted or not. Data is unencrypted by default.
* @returns A string indicating the success of the operation
* @throws {InternalError} If the Wallet does not have a seed
*/
saveSeed(filePath: string, encrypt?: boolean): string;
/**
* Loads the seed of the Wallet from the given file.
*
* @param filePath - The path of the file to load the seed from
* @returns A string indicating the success of the operation
*/
loadSeed(filePath: string): Promise<string>;
/**
* Returns the default address of the Wallet.
*
* @returns The default address
*/
getDefaultAddress(): WalletAddress | undefined;
/**
* Returns whether the Wallet has a seed with which to derive keys and sign transactions.
*
* @returns Whether the Wallet has a seed with which to derive keys and sign transactions.
*/
canSign(): boolean;
/**
* Requests funds from the faucet for the Wallet's default address and returns the faucet transaction.
* This is only supported on testnet networks.
*
* @throws {InternalError} If the default address is not found.
* @throws {APIError} If the request fails.
* @returns The successful faucet transaction
*/
faucet(): Promise<FaucetTransaction>;
/**
* Transfers the given amount of the given Asset to the given address. Only same-Network Transfers are supported.
* Currently only the default_address is used to source the Transfer.
*
* @param options - The options to create the Transfer.
* @param options.amount - The amount of the Asset to send.
* @param options.assetId - The ID of the Asset to send.
* @param options.destination - The destination of the transfer. If a Wallet, sends to the Wallet's default address. If a String, interprets it as the address ID.
* @param options.timeoutSeconds - The maximum amount of time to wait for the Transfer to complete, in seconds.
* @param options.intervalSeconds - The interval at which to poll the Network for Transfer status, in seconds.
* @returns The hash of the Transfer transaction.
* @throws {APIError} if the API request to create a Transfer fails.
* @throws {APIError} if the API request to broadcast a Transfer fails.
* @throws {Error} if the Transfer times out.
*/
createTransfer({ amount, assetId, destination, timeoutSeconds, intervalSeconds, }: CreateTransferOptions): Promise<Transfer>;
/**
* Returns a String representation of the Wallet.
*
* @returns a String representation of the Wallet
*/
toString(): string;
/**
* Validates the seed and address models passed to the constructor.
*
* @param seed - The seed to use for the Wallet
*/
private validateSeed;
/**
* Loads the seed data from the given file.
*
* @param filePath - The path of the file to load the seed data from
* @returns The seed data
*/
private getExistingSeeds;
/**
* Gets the key for encrypting seed data.
*
* @returns The encryption key.
*/
private getEncryptionKey;
/**
* Returns a WalletAddress object for the given AddressModel.
*
* @param addressModel - The AddressModel to build the WalletAddress from.
* @param index - The index of the AddressModel.
* @returns The WalletAddress object.
*/
private buildWalletAddress;
/**
* Waits until the ServerSigner has created a seed for the Wallet.
*
* @param walletId - The ID of the Wallet that is awaiting seed creation.
* @param intervalSeconds - The interval at which to poll the CDPService, in seconds.
* @param timeoutSeconds - The maximum amount of time to wait for the ServerSigner to create a seed, in seconds.
* @throws {APIError} if the API request to get a Wallet fails.
* @throws {Error} if the ServerSigner times out.
*/
private waitForSigner;
/**
* Sets the master node for the given seed, if valid. If the seed is undefined it will set the master node using a random seed.
*
* @param seed - The seed to use for the Wallet.
* @returns The master node for the given seed.
*/
private setMasterNode;
/**
* Derives a key for an already registered Address in the Wallet.
*
* @param index - The index of the Address to derive.
* @throws {InternalError} - If the key derivation fails.
* @returns The derived key.
*/
private deriveKey;
/**
* Creates an attestation for the Address currently being created.
*
* @param key - The key of the Wallet.
* @returns The attestation.
*/
private createAttestation;
/**
* Reloads the Wallet model with the latest data from the server.
*
* @throws {APIError} if the API request to get a Wallet fails.
*/
private reload;
}

@@ -44,3 +44,17 @@ "use strict";

const utils_1 = require("./utils");
/**
* A representation of a Wallet. Wallets come with a single default Address, but can expand to have a set of Addresses,
* each of which can hold a balance of one or more Assets. Wallets can create new Addresses, list their addresses,
* list their balances, and transfer Assets to other Addresses. Wallets should be created through User.createWallet or User.importWallet.
*/
class Wallet {
/**
* Private constructor to prevent direct instantiation outside of factory method. Use Wallet.init instead.
*
* @ignore
* @param model - The wallet model object.
* @param master - The HD master key.
* @param seed - The seed to use for the Wallet. Expects a 32-byte hexadecimal with no 0x prefix.
* @hideconstructor
*/
constructor(model, master, seed) {

@@ -53,2 +67,9 @@ this.addresses = [];

}
/**
* Lists the Wallets belonging to the User.
*
* @param pageSize - The number of Wallets to return per page. Defaults to 10
* @param nextPageToken - The token for the next page of Wallets
* @returns An object containing the Wallets and the token for the next page
*/
static async listWallets(pageSize = 10, nextPageToken) {

@@ -61,2 +82,9 @@ const walletList = await coinbase_1.Coinbase.apiClients.wallet.listWallets(pageSize, nextPageToken ? nextPageToken : undefined);

}
/**
* Fetches a Wallet by its ID. The returned wallet can be immediately used for signing operations if backed by a server signer.
* If the wallet is not backed by a server signer, the wallet's seed will need to be set before it can be used for signing operations.
*
* @param wallet_id - The ID of the Wallet to fetch
* @returns The fetched Wallet
*/
static async fetch(wallet_id) {

@@ -66,2 +94,13 @@ const response = await coinbase_1.Coinbase.apiClients.wallet.getWallet(wallet_id);

}
/**
* Imports a Wallet for the given Wallet data.
*
* @param data - The Wallet data to import.
* @param data.walletId - The ID of the Wallet to import.
* @param data.seed - The seed to use for the Wallet.
* @returns The imported Wallet.
* @throws {ArgumentError} If the Wallet ID is not provided.
* @throws {ArgumentError} If the seed is not provided.
* @throws {APIError} If the request fails.
*/
static async import(data) {

@@ -78,2 +117,16 @@ if (!data.walletId) {

}
/**
* Returns a newly created Wallet object. Do not use this method directly.
* Instead, use User.createWallet.
*
* @constructs Wallet
* @param options - The options to create the Wallet.
* @param options.networkId - the ID of the blockchain network. Defaults to 'base-sepolia'.
* @param options.intervalSeconds - The interval at which to poll the CDPService, in seconds.
* @param options.timeoutSeconds - The maximum amount of time to wait for the ServerSigner to create a seed, in seconds.
* @throws {ArgumentError} If the model or client is not provided.
* @throws {InternalError} - If address derivation or caching fails.
* @throws {APIError} - If the request fails.
* @returns A promise that resolves with the new Wallet object.
*/
static async create({ networkId = coinbase_1.Coinbase.networks.BaseSepolia, timeoutSeconds = 20, intervalSeconds = 0.2, } = {}) {

@@ -93,2 +146,14 @@ const result = await coinbase_1.Coinbase.apiClients.wallet.createWallet({

}
/**
* Returns a new Wallet object. Do not use this method directly. Instead, use User.createWallet or User.importWallet.
*
* @constructs Wallet
* @param model - The underlying Wallet model object
* @param seed - The seed to use for the Wallet. Expects a 32-byte hexadecimal with no 0x prefix. If null or undefined, a new seed will be generated.
* If the empty string, no seed is generated, and the Wallet will be instantiated without a seed and its corresponding private keys.
* @throws {ArgumentError} If the model or client is not provided.
* @throws {InternalError} - If address derivation or caching fails.
* @throws {APIError} - If the request fails.
* @returns A promise that resolves with the new Wallet object.
*/
static init(model, seed) {

@@ -102,2 +167,8 @@ const wallet = new Wallet(model, undefined, seed);

}
/**
* Exports the Wallet's data to a WalletData object.
*
* @returns The Wallet's data.
* @throws {APIError} - If the request fails.
*/
export() {

@@ -109,2 +180,8 @@ if (!this.seed) {

}
/**
* Creates a new Address in the Wallet.
*
* @returns The new Address.
* @throws {APIError} - If the address creation fails.
*/
async createAddress() {

@@ -130,2 +207,9 @@ let payload, key;

}
/**
* Set the seed for the Wallet.
*
* @param seed - The seed to use for the Wallet. Expects a 32-byte hexadecimal with no 0x prefix.
* @throws {ArgumentError} If the seed is empty.
* @throws {InternalError} If the seed is already set.
*/
setSeed(seed) {

@@ -151,2 +235,8 @@ if (seed === undefined || seed === "") {

}
/**
* Returns the Address with the given ID.
*
* @param addressId - The ID of the Address to retrieve.
* @returns The Address.
*/
getAddress(addressId) {

@@ -157,2 +247,7 @@ return this.addresses.find(address => {

}
/**
* Returns the list of Addresses in the Wallet.
*
* @returns The list of Addresses.
*/
async listAddresses() {

@@ -166,8 +261,32 @@ const response = await coinbase_1.Coinbase.apiClients.address.listAddresses(this.getId(), Wallet.MAX_ADDRESSES);

}
async createTrade(amount, fromAssetId, toAssetId) {
/**
* Trades the given amount of the given Asset for another Asset. Currently only the default address is used to source the Trade
*
* @param options - The options to create the Trade.
* @param options.amount - The amount of the Asset to send.
* @param options.fromAssetId - The ID of the Asset to trade from.
* @param options.toAssetId - The ID of the Asset to trade to.
* @param options.timeoutSeconds - The maximum amount of time to wait for the Trade to complete, in seconds.
* @param options.intervalSeconds - The interval at which to poll the Network for Trade status, in seconds.
* @throws {InternalError} If the default address is not found.
* @throws {Error} If the private key is not loaded, or if the asset IDs are unsupported, or if there are insufficient funds.
* @returns The Trade object.
*/
async createTrade({ amount, fromAssetId, toAssetId, timeoutSeconds = 10, intervalSeconds = 0.2, }) {
if (!this.getDefaultAddress()) {
throw new errors_1.InternalError("Default address not found");
}
return await this.getDefaultAddress().createTrade(amount, fromAssetId, toAssetId);
return await this.getDefaultAddress().createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
timeoutSeconds,
intervalSeconds,
});
}
/**
* Returns the list of balances of this Wallet. Balances are aggregated across all Addresses in the Wallet.
*
* @returns The list of balances. The key is the Asset ID, and the value is the balance.
*/
async listBalances() {

@@ -177,2 +296,8 @@ const response = await coinbase_1.Coinbase.apiClients.wallet.listWalletBalances(this.model.id);

}
/**
* Returns the balance of the provided Asset. Balances are aggregated across all Addresses in the Wallet.
*
* @param assetId - The ID of the Asset to retrieve the balance for.
* @returns The balance of the Asset.
*/
async getBalance(assetId) {

@@ -186,5 +311,15 @@ const response = await coinbase_1.Coinbase.apiClients.wallet.getWalletBalance(this.model.id, asset_1.Asset.primaryDenomination(assetId));

}
/**
* Returns the Network ID of the Wallet.
*
* @returns The network ID.
*/
getNetworkId() {
return this.model.network_id;
}
/**
* Returns the ServerSigner Status of the Wallet.
*
* @returns the ServerSigner Status.
*/
getServerSignerStatus() {

@@ -197,5 +332,21 @@ const status = {

}
/**
* Returns the wallet ID.
*
* @returns The wallet ID.
*/
getId() {
return this.model.id;
}
/**
* Saves the seed of the Wallet to the given file. Wallets whose seeds are saved this way can be
* rehydrated using load_seed. A single file can be used for multiple Wallet seeds.
* This is an insecure method of storing Wallet seeds and should only be used for development purposes.
*
* @param filePath - The path of the file to save the seed to
* @param encrypt - Whether the seed information persisted to the local file system should be
* encrypted or not. Data is unencrypted by default.
* @returns A string indicating the success of the operation
* @throws {InternalError} If the Wallet does not have a seed
*/
saveSeed(filePath, encrypt = false) {

@@ -228,2 +379,8 @@ if (!this.master) {

}
/**
* Loads the seed of the Wallet from the given file.
*
* @param filePath - The path of the file to load the seed from
* @returns A string indicating the success of the operation
*/
async loadSeed(filePath) {

@@ -240,2 +397,3 @@ const existingSeedsInStore = this.getExistingSeeds(filePath);

if (!seed) {
/* istanbul ignore next */
throw new errors_1.ArgumentError("Seed data is malformed");

@@ -246,2 +404,3 @@ }

if (!seedData.iv || !seedData.authTag) {
/* istanbul ignore next */
throw new errors_1.ArgumentError("Encrypted seed data is malformed");

@@ -261,8 +420,26 @@ }

}
/**
* Returns the default address of the Wallet.
*
* @returns The default address
*/
getDefaultAddress() {
return this.addresses.find(address => address.getId() === this.model.default_address?.address_id);
}
/**
* Returns whether the Wallet has a seed with which to derive keys and sign transactions.
*
* @returns Whether the Wallet has a seed with which to derive keys and sign transactions.
*/
canSign() {
return this.master?.publicKey !== undefined;
}
/**
* Requests funds from the faucet for the Wallet's default address and returns the faucet transaction.
* This is only supported on testnet networks.
*
* @throws {InternalError} If the default address is not found.
* @throws {APIError} If the request fails.
* @returns The successful faucet transaction
*/
async faucet() {

@@ -275,2 +452,17 @@ if (!this.model.default_address) {

}
/**
* Transfers the given amount of the given Asset to the given address. Only same-Network Transfers are supported.
* Currently only the default_address is used to source the Transfer.
*
* @param options - The options to create the Transfer.
* @param options.amount - The amount of the Asset to send.
* @param options.assetId - The ID of the Asset to send.
* @param options.destination - The destination of the transfer. If a Wallet, sends to the Wallet's default address. If a String, interprets it as the address ID.
* @param options.timeoutSeconds - The maximum amount of time to wait for the Transfer to complete, in seconds.
* @param options.intervalSeconds - The interval at which to poll the Network for Transfer status, in seconds.
* @returns The hash of the Transfer transaction.
* @throws {APIError} if the API request to create a Transfer fails.
* @throws {APIError} if the API request to broadcast a Transfer fails.
* @throws {Error} if the Transfer times out.
*/
async createTransfer({ amount, assetId, destination, timeoutSeconds = 10, intervalSeconds = 0.2, }) {

@@ -288,5 +480,15 @@ if (!this.getDefaultAddress()) {

}
/**
* Returns a String representation of the Wallet.
*
* @returns a String representation of the Wallet
*/
toString() {
return `Wallet{id: '${this.model.id}', networkId: '${this.model.network_id}'}`;
}
/**
* Validates the seed and address models passed to the constructor.
*
* @param seed - The seed to use for the Wallet
*/
validateSeed(seed) {

@@ -297,2 +499,8 @@ if (seed && seed.length !== 64) {

}
/**
* Loads the seed data from the given file.
*
* @param filePath - The path of the file to load the seed data from
* @returns The seed data
*/
getExistingSeeds(filePath) {

@@ -306,2 +514,3 @@ try {

if (!Object.entries(seedData).every(([key, value]) => typeof key === "string" &&
/* eslint-disable @typescript-eslint/no-explicit-any */
typeof value.authTag === "string" &&

@@ -316,2 +525,3 @@ typeof value.encrypted === "boolean" &&

catch (error) {
/* eslint-enable @typescript-eslint/no-explicit-any */
if (error.code === "ENOENT") {

@@ -323,2 +533,7 @@ return {};

}
/**
* Gets the key for encrypting seed data.
*
* @returns The encryption key.
*/
getEncryptionKey() {

@@ -333,2 +548,9 @@ const privateKey = crypto.createPrivateKey(coinbase_1.Coinbase.apiKeyPrivateKey);

}
/**
* Returns a WalletAddress object for the given AddressModel.
*
* @param addressModel - The AddressModel to build the WalletAddress from.
* @param index - The index of the AddressModel.
* @returns The WalletAddress object.
*/
buildWalletAddress(addressModel, index) {

@@ -345,2 +567,11 @@ if (!this.master) {

}
/**
* Waits until the ServerSigner has created a seed for the Wallet.
*
* @param walletId - The ID of the Wallet that is awaiting seed creation.
* @param intervalSeconds - The interval at which to poll the CDPService, in seconds.
* @param timeoutSeconds - The maximum amount of time to wait for the ServerSigner to create a seed, in seconds.
* @throws {APIError} if the API request to get a Wallet fails.
* @throws {Error} if the ServerSigner times out.
*/
async waitForSigner(walletId, intervalSeconds = 0.2, timeoutSeconds = 20) {

@@ -357,2 +588,8 @@ const startTime = Date.now();

}
/**
* Sets the master node for the given seed, if valid. If the seed is undefined it will set the master node using a random seed.
*
* @param seed - The seed to use for the Wallet.
* @returns The master node for the given seed.
*/
setMasterNode(seed) {

@@ -369,2 +606,9 @@ if (seed === "") {

}
/**
* Derives a key for an already registered Address in the Wallet.
*
* @param index - The index of the Address to derive.
* @throws {InternalError} - If the key derivation fails.
* @returns The derived key.
*/
deriveKey(index) {

@@ -375,2 +619,3 @@ if (!this.master) {

const [networkPrefix] = this.model.network_id.split("-");
// TODO: Push this logic to the backend.
if (!["base", "ethereum"].includes(networkPrefix)) {

@@ -385,4 +630,11 @@ throw new errors_1.InternalError(`Unsupported network ID: ${this.model.network_id}`);

}
/**
* Creates an attestation for the Address currently being created.
*
* @param key - The key of the Wallet.
* @returns The attestation.
*/
createAttestation(key) {
if (!key.publicKey || !key.privateKey) {
/* istanbul ignore next */
throw errors_1.InternalError;

@@ -404,2 +656,7 @@ }

}
/**
* Reloads the Wallet model with the latest data from the server.
*
* @throws {APIError} if the API request to get a Wallet fails.
*/
async reload() {

@@ -406,0 +663,0 @@ const result = await coinbase_1.Coinbase.apiClients.wallet.getWallet(this.model.id);

2

dist/tests/api_error_test.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = require("axios");
const api_error_1 = require("./../coinbase/api_error");
const api_error_1 = require("./../coinbase/api_error"); // Adjust the import path accordingly
describe("APIError", () => {

@@ -6,0 +6,0 @@ test("should create default APIError without response data", () => {

@@ -13,2 +13,3 @@ "use strict";

const filePath = "./config/test_api_key.json";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const keys = require(filePath);

@@ -15,0 +16,0 @@ const authenticator = new authenticator_1.CoinbaseAuthenticator(keys.name, keys.privateKey);

@@ -10,2 +10,3 @@ "use strict";

beforeAll(() => {
// Mock the stake functions.
coinbase_1.Coinbase.apiClients.stake = utils_1.stakeApiMock;

@@ -12,0 +13,0 @@ });

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = require("../coinbase/errors");
const utils_1 = require("./../coinbase/utils");
const utils_1 = require("./../coinbase/utils"); // Adjust the path as necessary
describe("parseUnsignedPayload", () => {
it("should parse and return a valid payload", () => {
const payload = "7b226b6579223a2276616c7565227d";
const payload = "7b226b6579223a2276616c7565227d"; // {"key":"value"} in hex
const expectedOutput = { key: "value" };

@@ -16,3 +16,3 @@ expect((0, utils_1.parseUnsignedPayload)(payload)).toEqual(expectedOutput);

it("should throw InvalidUnsignedPayload error if payload cannot be decoded to JSON", () => {
const payload = "000102";
const payload = "000102"; // Invalid JSON
expect(() => (0, utils_1.parseUnsignedPayload)(payload)).toThrow(errors_1.InvalidUnsignedPayload);

@@ -25,3 +25,3 @@ });

it("should throw InvalidUnsignedPayload error if payload contains non-hex characters", () => {
const payload = "7b226b6579223a2276616c75657g7d";
const payload = "7b226b6579223a2276616c75657g7d"; // Invalid hex due to 'g'
expect(() => (0, utils_1.parseUnsignedPayload)(payload)).toThrow(errors_1.InvalidUnsignedPayload);

@@ -28,0 +28,0 @@ });

@@ -24,5 +24,21 @@ /// <reference types="jest" />

export declare const VALID_STAKING_OPERATION_MODEL: StakingOperationModel;
/**
* mockStakingOperation returns a mock StakingOperation object with the provided status.
*
* @param status - The status of the validator.
*
* @returns The mock StakingOperationModel object.
*/
export declare function mockStakingOperation(status: StakingOperationStatusEnum): StakingOperationModel;
export declare const VALID_NATIVE_ETH_UNSTAKE_OPERATION_MODEL: StakingOperationModel;
export declare const VALID_ADDRESS_BALANCE_LIST: AddressBalanceList;
/**
* mockEthereumValidator returns a mock EthereumValidator object with the provided index and status.
*
* @param index - The index of the validator.
* @param status - The status of the validator.
* @param public_key - The public key of the validator.
*
* @returns The mock EthereumValidator object.
*/
export declare function mockEthereumValidator(index: string, status: string, public_key: string): Validator;

@@ -32,4 +48,17 @@ export declare const VALID_ACTIVE_VALIDATOR_LIST: ValidatorList;

export declare const VALID_BALANCE_MODEL: BalanceModel;
/**
* getAssetMock returns a mock function that returns an AssetModel with the provided network ID and asset ID.
*
* @returns The mock function.
*/
export declare const getAssetMock: () => any;
/**
* AxiosMockReturn type. Represents the Axios instance, configuration, and base path.
*/
type AxiosMockType = [AxiosInstance, Configuration, string];
/**
* Returns an Axios instance with interceptors and configuration for testing.
*
* @returns The Axios instance, configuration, and base path.
*/
export declare const createAxiosMock: () => AxiosMockType;

@@ -36,0 +65,0 @@ export declare const usersApiMock: {

@@ -7,2 +7,3 @@ "use strict";

exports.serverSignersApiMock = exports.externalAddressApiMock = exports.validatorApiMock = exports.stakeApiMock = exports.transfersApiMock = exports.tradeApiMock = exports.addressesApiMock = exports.walletsApiMock = exports.assetsApiMock = exports.usersApiMock = exports.createAxiosMock = exports.getAssetMock = exports.VALID_BALANCE_MODEL = exports.VALID_EXITING_VALIDATOR_LIST = exports.VALID_ACTIVE_VALIDATOR_LIST = exports.mockEthereumValidator = exports.VALID_ADDRESS_BALANCE_LIST = exports.VALID_NATIVE_ETH_UNSTAKE_OPERATION_MODEL = exports.mockStakingOperation = exports.VALID_STAKING_OPERATION_MODEL = exports.VALID_TRANSFER_MODEL = exports.VALID_WALLET_MODEL = exports.VALID_ADDRESS_MODEL = exports.newAddressModel = exports.generateRandomHash = exports.generateWalletFromSeed = exports.transferId = exports.walletId = exports.mockListAddress = exports.getAddressFromHDKey = exports.mockReturnRejectedValue = exports.mockReturnValue = exports.mockFn = void 0;
/* eslint-disable @typescript-eslint/no-explicit-any */
const axios_1 = __importDefault(require("axios"));

@@ -73,2 +74,3 @@ const decimal_js_1 = require("decimal.js");

exports.generateRandomHash = generateRandomHash;
// newAddressModel creates a new AddressModel with a random wallet ID and a random Ethereum address.
const newAddressModel = (walletId, address_id = "", network_id = coinbase_1.Coinbase.networks.BaseSepolia) => {

@@ -164,2 +166,9 @@ const ethAddress = ethers_1.ethers.Wallet.createRandom();

};
/**
* mockStakingOperation returns a mock StakingOperation object with the provided status.
*
* @param status - The status of the validator.
*
* @returns The mock StakingOperationModel object.
*/
function mockStakingOperation(status) {

@@ -241,2 +250,11 @@ return {

};
/**
* mockEthereumValidator returns a mock EthereumValidator object with the provided index and status.
*
* @param index - The index of the validator.
* @param status - The status of the validator.
* @param public_key - The public key of the validator.
*
* @returns The mock EthereumValidator object.
*/
function mockEthereumValidator(index, status, public_key) {

@@ -299,2 +317,7 @@ return {

};
/**
* getAssetMock returns a mock function that returns an AssetModel with the provided network ID and asset ID.
*
* @returns The mock function.
*/
const getAssetMock = () => {

@@ -321,2 +344,7 @@ return (0, exports.mockFn)((...request) => {

exports.getAssetMock = getAssetMock;
/**
* Returns an Axios instance with interceptors and configuration for testing.
*
* @returns The Axios instance, configuration, and base path.
*/
const createAxiosMock = () => {

@@ -323,0 +351,0 @@ const axiosInstance = axios_1.default.create();

@@ -8,2 +8,3 @@ "use strict";

beforeAll(() => {
// Mock the validator functions.
coinbase_1.Coinbase.apiClients.validator = utils_1.validatorApiMock;

@@ -10,0 +11,0 @@ });

@@ -29,2 +29,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/no-explicit-any */
const crypto = __importStar(require("crypto"));

@@ -44,2 +45,3 @@ const ethers_1 = require("ethers");

const wallet_1 = require("../coinbase/wallet");
// Test suite for the WalletAddress class
describe("WalletAddress", () => {

@@ -236,20 +238,2 @@ const transactionHash = (0, utils_1.generateRandomHash)();

});
it("it should successfully create and complete a transfer if using signer and key is not loaded", async () => {
coinbase_1.Coinbase.apiClients.transfer.createTransfer = (0, utils_1.mockReturnValue)(utils_1.VALID_TRANSFER_MODEL);
coinbase_1.Coinbase.apiClients.transfer.getTransfer = (0, utils_1.mockReturnValue)({
...utils_1.VALID_TRANSFER_MODEL,
status: types_1.TransferStatus.COMPLETE,
});
coinbase_1.Coinbase.useServerSigner = true;
const addressWithoutKey = new wallet_address_1.WalletAddress(utils_1.VALID_ADDRESS_MODEL, null);
await addressWithoutKey.createTransfer({
amount: weiAmount,
assetId: coinbase_1.Coinbase.assets.Wei,
destination,
timeoutSeconds,
intervalSeconds,
});
expect(coinbase_1.Coinbase.apiClients.transfer.createTransfer).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.transfer.getTransfer).toHaveBeenCalledTimes(1);
});
it("should throw an ArgumentError if the Wallet Network ID does not match the Address Network ID", async () => {

@@ -384,3 +368,3 @@ coinbase_1.Coinbase.apiClients.wallet = utils_1.walletsApiMock;

});
describe("#trade", () => {
describe("#createTrade", () => {
let addressId;

@@ -469,3 +453,3 @@ let toAddressId;

amount = new decimal_js_1.default(0.5);
useServerSigner = false;
coinbase_1.Coinbase.useServerSigner = false;
});

@@ -480,10 +464,18 @@ describe("when the trade is successful", () => {

coinbase_1.Coinbase.apiClients.asset.getAsset = (0, utils_1.getAssetMock)();
coinbase_1.Coinbase.apiClients.trade.broadcastTrade = (0, utils_1.mockReturnValue)(broadcastedTradeModel);
coinbase_1.Coinbase.apiClients.trade.getTrade = (0, utils_1.mockReturnValue)({
...broadcastedTradeModel,
transaction: { ...broadcastedTransactionModel, status: types_1.TransactionStatus.COMPLETE },
});
jest.spyOn(transaction_1.Transaction.prototype, "sign").mockReturnValue(signedPayload);
});
it("should return the broadcasted trade", async () => {
coinbase_1.Coinbase.apiClients.trade.broadcastTrade = (0, utils_1.mockReturnValue)(broadcastedTradeModel);
const result = await address.createTrade(amount, fromAssetId, toAssetId);
it("should return the completed trade", async () => {
const result = await address.createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
});
const transaction = result.getTransaction();
expect(transaction.getSignedPayload()).toEqual(signedPayload);
expect(transaction.getStatus()).toEqual(types_1.TransactionStatus.BROADCAST);
expect(transaction.getStatus()).toEqual(types_1.TransactionStatus.COMPLETE);
expect(transaction.getUnsignedPayload()).toEqual(unsignedPayload);

@@ -495,8 +487,15 @@ expect(coinbase_1.Coinbase.apiClients.trade.createTrade).toHaveBeenCalledWith(address.getWalletId(), address.getId(), {

});
expect(coinbase_1.Coinbase.apiClients.trade.broadcastTrade).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.trade.getTrade).toHaveBeenCalledTimes(1);
});
it("should sign the transaction with the key", async () => {
coinbase_1.Coinbase.apiClients.trade.broadcastTrade = (0, utils_1.mockReturnValue)(broadcastedTradeModel);
const result = await address.createTrade(amount, fromAssetId, toAssetId);
const result = await address.createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
});
const transaction = result.getTransaction();
expect(transaction.sign).toHaveBeenCalledWith(key);
expect(coinbase_1.Coinbase.apiClients.trade.broadcastTrade).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.trade.getTrade).toHaveBeenCalledTimes(1);
});

@@ -510,4 +509,7 @@ describe("when the asset is Gwei", () => {

it("should return the broadcast trade", async () => {
coinbase_1.Coinbase.apiClients.trade.broadcastTrade = (0, utils_1.mockReturnValue)(broadcastedTradeModel);
await address.createTrade(amount, fromAssetId, toAssetId);
await address.createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
});
expect(coinbase_1.Coinbase.apiClients.trade.createTrade).toHaveBeenCalledWith(address.getWalletId(), address.getId(), {

@@ -518,8 +520,15 @@ amount: `500000000000000000`,

});
expect(coinbase_1.Coinbase.apiClients.trade.broadcastTrade).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.trade.getTrade).toHaveBeenCalledTimes(1);
});
it("should sign the transaction with the address key", async () => {
coinbase_1.Coinbase.apiClients.trade.broadcastTrade = (0, utils_1.mockReturnValue)(broadcastedTradeModel);
const result = await address.createTrade(amount, fromAssetId, toAssetId);
const result = await address.createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
});
const transaction = result.getTransaction();
expect(transaction.sign).toHaveBeenCalledWith(key);
expect(coinbase_1.Coinbase.apiClients.trade.broadcastTrade).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.trade.getTrade).toHaveBeenCalledTimes(1);
});

@@ -534,4 +543,7 @@ });

it("should return the broadcast trade", async () => {
coinbase_1.Coinbase.apiClients.trade.broadcastTrade = (0, utils_1.mockReturnValue)(broadcastedTradeModel);
await address.createTrade(amount, fromAssetId, toAssetId);
await address.createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
});
expect(coinbase_1.Coinbase.apiClients.trade.createTrade).toHaveBeenCalledWith(address.getWalletId(), address.getId(), {

@@ -542,8 +554,15 @@ amount: `500000000000000000`,

});
expect(coinbase_1.Coinbase.apiClients.trade.broadcastTrade).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.trade.getTrade).toHaveBeenCalledTimes(1);
});
it("should sign the transaction with the address key", async () => {
coinbase_1.Coinbase.apiClients.trade.broadcastTrade = (0, utils_1.mockReturnValue)(broadcastedTradeModel);
const result = await address.createTrade(amount, fromAssetId, toAssetId);
const result = await address.createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
});
const transaction = result.getTransaction();
expect(transaction.sign).toHaveBeenCalledWith(key);
expect(coinbase_1.Coinbase.apiClients.trade.broadcastTrade).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.trade.getTrade).toHaveBeenCalledTimes(1);
});

@@ -561,4 +580,7 @@ });

it("should return the broadcast trade", async () => {
coinbase_1.Coinbase.apiClients.trade.broadcastTrade = (0, utils_1.mockReturnValue)(broadcastedTradeModel);
await address.createTrade(amount, fromAssetId, toAssetId);
await address.createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
});
expect(coinbase_1.Coinbase.apiClients.trade.createTrade).toHaveBeenCalledWith(address.getWalletId(), address.getId(), {

@@ -569,8 +591,15 @@ amount: `5000000`,

});
expect(coinbase_1.Coinbase.apiClients.trade.broadcastTrade).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.trade.getTrade).toHaveBeenCalledTimes(1);
});
it("should sign the transaction with the address key", async () => {
coinbase_1.Coinbase.apiClients.trade.broadcastTrade = (0, utils_1.mockReturnValue)(broadcastedTradeModel);
const result = await address.createTrade(amount, fromAssetId, toAssetId);
const result = await address.createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
});
const transaction = result.getTransaction();
expect(transaction.sign).toHaveBeenCalledWith(key);
expect(coinbase_1.Coinbase.apiClients.trade.broadcastTrade).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.trade.getTrade).toHaveBeenCalledTimes(1);
});

@@ -589,12 +618,46 @@ });

it("should sign the trade transaction with the address key", async () => {
const trade = await address.createTrade(amount, fromAssetId, toAssetId);
const trade = await address.createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
});
const transaction = trade.getTransaction();
expect(transaction.sign).toHaveBeenCalledWith(key);
expect(coinbase_1.Coinbase.apiClients.trade.broadcastTrade).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.trade.getTrade).toHaveBeenCalledTimes(1);
});
});
});
describe("when using server signer", () => {
beforeEach(() => {
jest.clearAllMocks();
coinbase_1.Coinbase.apiClients.asset = utils_1.assetsApiMock;
coinbase_1.Coinbase.apiClients.trade = utils_1.tradeApiMock;
coinbase_1.Coinbase.apiClients.address.getAddressBalance = (0, utils_1.mockReturnValue)(balanceResponse);
coinbase_1.Coinbase.apiClients.trade.createTrade = (0, utils_1.mockReturnValue)(tradeModel);
coinbase_1.Coinbase.apiClients.asset.getAsset = (0, utils_1.getAssetMock)();
coinbase_1.Coinbase.useServerSigner = true;
});
it("should successfully create and complete a trade", async () => {
coinbase_1.Coinbase.apiClients.trade.getTrade = (0, utils_1.mockReturnValue)({
...broadcastedTradeModel,
transaction: { ...broadcastedTransactionModel, status: types_1.TransactionStatus.COMPLETE },
});
await address.createTrade({
amount: amount,
fromAssetId: fromAssetId,
toAssetId: toAssetId,
});
expect(coinbase_1.Coinbase.apiClients.trade.createTrade).toHaveBeenCalledTimes(1);
expect(coinbase_1.Coinbase.apiClients.trade.getTrade).toHaveBeenCalledTimes(1);
});
});
describe("when the address cannot sign", () => {
it("should raise an Error", async () => {
const newAddress = new wallet_address_1.WalletAddress(utils_1.VALID_ADDRESS_MODEL, null);
await expect(newAddress.createTrade(new decimal_js_1.default(100), "eth", "usdc")).rejects.toThrow(Error);
await expect(newAddress.createTrade({
amount: new decimal_js_1.default(100),
fromAssetId: "eth",
toAssetId: "usdc",
})).rejects.toThrow(Error);
});

@@ -604,3 +667,3 @@ });

it("should raise an ArgumentError", async () => {
await expect(address.createTrade(new decimal_js_1.default(100), "XYZ", "eth")).rejects.toThrow(Error);
await expect(address.createTrade({ amount: new decimal_js_1.default(100), fromAssetId: "XYZ", toAssetId: "eth" })).rejects.toThrow(Error);
});

@@ -610,3 +673,3 @@ });

it("should raise an ArgumentError", async () => {
await expect(address.createTrade(new decimal_js_1.default(100), "eth", "XYZ")).rejects.toThrow(Error);
await expect(address.createTrade({ amount: new decimal_js_1.default(100), fromAssetId: "eth", toAssetId: "XYZ" })).rejects.toThrow(Error);
});

@@ -620,3 +683,3 @@ });

it("should raise an Error", async () => {
await expect(address.createTrade(new decimal_js_1.default(100), "eth", "usdc")).rejects.toThrow(Error);
await expect(address.createTrade({ amount: new decimal_js_1.default(100), fromAssetId: "eth", toAssetId: "usdc" })).rejects.toThrow(Error);
});

@@ -623,0 +686,0 @@ });

@@ -54,2 +54,3 @@ "use strict";

walletId = crypto_1.default.randomUUID();
// Mock the API calls
coinbase_1.Coinbase.apiClients.wallet = utils_1.walletsApiMock;

@@ -702,3 +703,3 @@ coinbase_1.Coinbase.apiClients.address = utils_1.addressesApiMock;

});
describe("#trade", () => {
describe("#createTrade", () => {
const tradeObject = new trade_1.Trade({

@@ -719,3 +720,3 @@ network_id: coinbase_1.Coinbase.networks.BaseSepolia,

const newWallet = wallet_1.Wallet.init(walletModel);
await expect(async () => await newWallet.createTrade(0.01, "eth", "usdc")).rejects.toThrow(errors_1.InternalError);
await expect(async () => await newWallet.createTrade({ amount: 0.01, fromAssetId: "eth", toAssetId: "usdc" })).rejects.toThrow(errors_1.InternalError);
});

@@ -726,3 +727,7 @@ it("should create a trade from the default address", async () => {

const wallet = await wallet_1.Wallet.create();
const result = await wallet.createTrade(0.01, "eth", "usdc");
const result = await wallet.createTrade({
amount: 0.01,
fromAssetId: "eth",
toAssetId: "usdc",
});
expect(result).toBeInstanceOf(trade_1.Trade);

@@ -729,0 +734,0 @@ expect(result.getAddressId()).toBe(tradeObject.getAddressId());

@@ -7,3 +7,3 @@ {

"repository": "https://github.com/coinbase/coinbase-sdk-nodejs",
"version": "0.0.12",
"version": "0.0.13",
"main": "dist/index.js",

@@ -10,0 +10,0 @@ "types": "dist/index.d.ts",

@@ -168,3 +168,3 @@ # Coinbase Node.js SDK

// Trade 0.00001 ETH to USDC
let trade = await wallet.createTrade(0.00001, Coinbase.assets.Eth, Coinbase.assets.Usdc);
let trade = await wallet.createTrade({ amount: 0.00001, fromAssetId: Coinbase.assets.Eth, toAssetId: Coinbase.assets.Usdc });

@@ -226,2 +226,2 @@ console.log(`Second trade successfully completed: ${trade}`);

[npmtrends-url]: https://www.npmtrends.com/@coinbase/coinbase-sdk
[npm-downloads]: https://img.shields.io/npm/dw/@coinbase/coinbase-sdk
[npm-downloads]: https://img.shields.io/npm/dw/@coinbase/coinbase-sdk

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc