Skip to content
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## Unreleased

### Changed
- `getDefaultAddress` wallet method updated to return a promise, and `getAddress` wallet methods now return a promise and `WalletAddress` instead of `Address`. Both functions will now fetch addresses for the wallet if they haven't been loaded.

## [0.3.0] - 2024-09-05

### Added
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ Next, view the default Address of your Wallet. You will need this default Addres

```typescript
// A Wallet has a default Address.
const address = wallet.getDefaultAddress();
const address = await wallet.getDefaultAddress();
console.log(`Address: ${address}`);
```

Expand Down
4 changes: 2 additions & 2 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ module.exports = {
maxWorkers: 1,
coverageThreshold: {
"./src/coinbase/**": {
branches: 80,
branches: 78,
functions: 90,
statements: 85,
lines: 90,
lines: 88,
},
},
};
2 changes: 1 addition & 1 deletion quickstart-template/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ let wallet = await Wallet.create();
console.log(`Wallet successfully created: `, wallet.toString());

// Wallets come with a single default Address, accessible via getDefaultAddress:
let address = wallet.getDefaultAddress();
let address = await wallet.getDefaultAddress();
console.log(`Default address for the wallet: `, address.toString());

const faucetTransaction = await wallet.faucet();
Expand Down
4 changes: 2 additions & 2 deletions quickstart-template/mass-payout.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ async function createReceivingWallets() {
let receivingWallet = await Wallet.create();
console.log(`Receiving Wallet${i} successfully created: `, receivingWallet.toString());

let receivingAddress = receivingWallet.getDefaultAddress();
let receivingAddress = await receivingWallet.getDefaultAddress();
console.log(`Default address for Wallet${i}: `, receivingAddress.getId());
addresses.push([receivingAddress.getId()]); // Storing Address as an array.
}
Expand Down Expand Up @@ -41,7 +41,7 @@ async function createAndFundSendingWallet() {
console.log(`sendingWallet successfully created: `, sendingWallet.toString());

// Get sending Wallet Address.
let sendingAddress = sendingWallet.getDefaultAddress();
let sendingAddress = await sendingWallet.getDefaultAddress();
console.log(`Default address for sendingWallet: `, sendingAddress.toString());

// Fund sending Wallet.
Expand Down
6 changes: 3 additions & 3 deletions src/coinbase/address/wallet_address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export class WalletAddress extends Address {
}
const asset = await Asset.fetch(this.getNetworkId(), assetId);
const [destinationAddress, destinationNetworkId] =
this.getDestinationAddressAndNetwork(destination);
await this.getDestinationAddressAndNetwork(destination);

const normalizedAmount = new Decimal(amount.toString());
const currentBalance = await this.getBalance(assetId);
Expand Down Expand Up @@ -532,12 +532,12 @@ export class WalletAddress extends Address {
* @param destination - The destination to get the address and network ID of.
* @returns The address and network ID of the destination.
*/
private getDestinationAddressAndNetwork(destination: Destination): [string, string] {
private async getDestinationAddressAndNetwork(destination: Destination): Promise<[string, string]> {
if (typeof destination !== "string" && destination.getNetworkId() !== this.getNetworkId()) {
throw new ArgumentError("Transfer must be on the same Network");
}
if (destination instanceof WalletClass) {
return [destination.getDefaultAddress()!.getId(), destination.getNetworkId()];
return [(await destination.getDefaultAddress()).getId(), destination.getNetworkId()];
}
if (destination instanceof Address) {
return [destination.getId(), destination.getNetworkId()];
Expand Down
95 changes: 31 additions & 64 deletions src/coinbase/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,12 +266,16 @@ export class Wallet {
}

/**
* Returns the Address with the given ID.
* Returns the WalletAddress with the given ID.
*
* @param addressId - The ID of the Address to retrieve.
* @returns The Address.
* @param addressId - The ID of the WalletAddress to retrieve.
* @returns The WalletAddress.
*/
public getAddress(addressId: string): Address | undefined {
public async getAddress(addressId: string): Promise<WalletAddress | undefined> {
if (this.addresses.length < 1) {
this.addresses = await this.listAddresses();
}

return this.addresses.find(address => {
return address.getId() === addressId;
});
Expand Down Expand Up @@ -308,10 +312,7 @@ export class Wallet {
* @returns The created Trade object.
*/
public async createTrade(options: CreateTradeOptions): Promise<Trade> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}
return await this.getDefaultAddress()!.createTrade(options);
return (await this.getDefaultAddress()).createTrade(options);
}

/**
Expand All @@ -328,10 +329,7 @@ export class Wallet {
mode: StakeOptionsMode = StakeOptionsMode.DEFAULT,
options: { [key: string]: string } = {},
): Promise<Decimal> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}
return await this.getDefaultAddress()!.stakeableBalance(asset_id, mode, options);
return (await this.getDefaultAddress()).stakeableBalance(asset_id, mode, options);
}

/**
Expand All @@ -348,10 +346,7 @@ export class Wallet {
mode: StakeOptionsMode = StakeOptionsMode.DEFAULT,
options: { [key: string]: string } = {},
): Promise<Decimal> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}
return await this.getDefaultAddress()!.unstakeableBalance(asset_id, mode, options);
return (await this.getDefaultAddress()).unstakeableBalance(asset_id, mode, options);
}

/**
Expand All @@ -368,10 +363,7 @@ export class Wallet {
mode: StakeOptionsMode = StakeOptionsMode.DEFAULT,
options: { [key: string]: string } = {},
): Promise<Decimal> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}
return await this.getDefaultAddress()!.claimableBalance(asset_id, mode, options);
return (await this.getDefaultAddress()).claimableBalance(asset_id, mode, options);
}

/**
Expand All @@ -390,10 +382,7 @@ export class Wallet {
endTime = formatDate(new Date()),
format: StakingRewardFormat = StakingRewardFormat.Usd,
): Promise<StakingReward[]> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}
return await this.getDefaultAddress()!.stakingRewards(assetId, startTime, endTime, format);
return (await this.getDefaultAddress()).stakingRewards(assetId, startTime, endTime, format);
}

/**
Expand All @@ -410,10 +399,7 @@ export class Wallet {
startTime = getWeekBackDate(new Date()),
endTime = formatDate(new Date()),
): Promise<StakingBalance[]> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}
return await this.getDefaultAddress()!.historicalStakingBalances(assetId, startTime, endTime);
return (await this.getDefaultAddress()).historicalStakingBalances(assetId, startTime, endTime);
}

/**
Expand All @@ -430,10 +416,7 @@ export class Wallet {
limit,
page,
}: ListHistoricalBalancesOptions): Promise<ListHistoricalBalancesResult> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}
return await this.getDefaultAddress()!.listHistoricalBalances({
return (await this.getDefaultAddress()).listHistoricalBalances({
assetId: assetId,
limit: limit,
page: page,
Expand All @@ -460,10 +443,7 @@ export class Wallet {
timeoutSeconds = 60,
intervalSeconds = 0.2,
): Promise<StakingOperation> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}
return await this.getDefaultAddress()!.createStake(
return (await this.getDefaultAddress()).createStake(
amount,
assetId,
mode,
Expand Down Expand Up @@ -493,10 +473,7 @@ export class Wallet {
timeoutSeconds = 60,
intervalSeconds = 0.2,
): Promise<StakingOperation> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}
return await this.getDefaultAddress()!.createUnstake(
return (await this.getDefaultAddress()).createUnstake(
amount,
assetId,
mode,
Expand Down Expand Up @@ -526,10 +503,7 @@ export class Wallet {
timeoutSeconds = 60,
intervalSeconds = 0.2,
): Promise<StakingOperation> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}
return await this.getDefaultAddress()!.createClaimStake(
return (await this.getDefaultAddress()).createClaimStake(
amount,
assetId,
mode,
Expand Down Expand Up @@ -705,10 +679,15 @@ export class Wallet {
*
* @returns The default address
*/
public getDefaultAddress(): WalletAddress | undefined {
return this.addresses.find(
address => address.getId() === this.model.default_address?.address_id,
);
public async getDefaultAddress(): Promise<WalletAddress> {
if (this.model.default_address === undefined) {
throw new Error("WalletModel default address not set");
}
const defaultAddress = await this.getAddress(this.model.default_address.address_id);
if (!defaultAddress) {
throw new Error("Default address not found");
}
return defaultAddress;
}

/**
Expand All @@ -733,7 +712,7 @@ export class Wallet {
if (!this.model.default_address) {
throw new Error("Default address not found");
}
const transaction = await this.getDefaultAddress()!.faucet(assetId);
const transaction = (await this.getDefaultAddress()).faucet(assetId);
return transaction!;
}

Expand All @@ -751,11 +730,7 @@ export class Wallet {
* @throws {APIError} if the API request to broadcast a Transfer fails.
*/
public async createTransfer(options: CreateTransferOptions): Promise<Transfer> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}

return await this.getDefaultAddress()!.createTransfer(options);
return (await this.getDefaultAddress()).createTransfer(options);
}

/**
Expand All @@ -767,11 +742,7 @@ export class Wallet {
* @throws {Error} if the default address is not found.
*/
public async createPayloadSignature(unsignedPayload: string): Promise<PayloadSignature> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}

return await this.getDefaultAddress()!.createPayloadSignature(unsignedPayload);
return (await this.getDefaultAddress()).createPayloadSignature(unsignedPayload);
}

/**
Expand All @@ -789,11 +760,7 @@ export class Wallet {
public async invokeContract(
options: CreateContractInvocationOptions,
): Promise<ContractInvocation> {
if (!this.getDefaultAddress()) {
throw new Error("Default address not found");
}

return await this.getDefaultAddress()!.invokeContract(options);
return (await this.getDefaultAddress()).invokeContract(options);
}

/**
Expand Down
7 changes: 3 additions & 4 deletions src/tests/e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,13 @@ describe("Coinbase SDK E2E Test", () => {
console.log(`Second address balances: ${secondBalance}`);

console.log("Fetching address transactions...");
const result = await unhydratedWallet.getDefaultAddress()?.listTransactions({ limit: 1 });
const result = await (await unhydratedWallet.getDefaultAddress()).listTransactions({ limit: 1 });
expect(result?.transactions.length).toBeGreaterThan(0);
console.log(`Fetched transactions: ${result?.transactions[0].toString()}`);

console.log("Fetching address historical balances...");
const balance_result = await unhydratedWallet
.getDefaultAddress()
?.listHistoricalBalances({ assetId: Coinbase.assets.Eth, limit: 2 });
const balance_result = await (await unhydratedWallet
.getDefaultAddress()).listHistoricalBalances({ assetId: Coinbase.assets.Eth, limit: 2 });
expect(balance_result?.historicalBalances.length).toBeGreaterThan(0);
console.log(
`First eth historical balance: ${balance_result?.historicalBalances[0].amount.toString()}`,
Expand Down
Loading