Skip to content

Commit

Permalink
Add method getAddressAsync and mark getAddress as deprecated
Browse files Browse the repository at this point in the history
  • Loading branch information
hippocampus-web3 committed Nov 12, 2023
1 parent ad112e6 commit 302d928
Show file tree
Hide file tree
Showing 44 changed files with 409 additions and 301 deletions.
20 changes: 10 additions & 10 deletions packages/xchain-avax/__e2e__/avax-client.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ function delay(ms: number) {
}
describe('xchain-evm (Avax) Integration Tests', () => {
it('should fetch avax balances', async () => {
const address = client.getAddress(0)
const address = await client.getAddressAsync(0)
console.log(address)
const balances = await client.getBalance(address)
balances.forEach((bal: Balance) => {
Expand All @@ -79,9 +79,9 @@ describe('xchain-evm (Avax) Integration Tests', () => {
expect(tx.asset.chain).toBe(AVAXChain)
expect(tx.asset.ticker).toBe(AssetAVAX.ticker)
expect(tx.type).toBe(TxType.Transfer)
expect(tx.from[0].from).toBe(client.getAddress(0))
expect(tx.from[0].from).toBe(await client.getAddressAsync(0))
expect(tx.from[0].amount.amount().toFixed()).toBe(amount.amount().toFixed())
expect(tx.to[0].to).toBe(client.getAddress(1))
expect(tx.to[0].to).toBe(await client.getAddressAsync(1))
expect(tx.to[0].amount.amount().toFixed()).toBe(amount.amount().toFixed())
expect(tx.hash).toBe(txId)
})
Expand All @@ -94,22 +94,22 @@ describe('xchain-evm (Avax) Integration Tests', () => {
expect(tx.asset.ticker).toBe(assetRIP.ticker)
expect(tx.asset.symbol).toBe(assetRIP.symbol)
expect(tx.type).toBe(TxType.Transfer)
expect(tx.from[0].from).toBe(client.getAddress(0))
expect(tx.from[0].from).toBe(await client.getAddressAsync(0))
expect(tx.from[0].amount.amount().toFixed()).toBe(amount.amount().toFixed())
expect(tx.to[0].to).toBe(client.getAddress(1))
expect(tx.to[0].to).toBe(await client.getAddressAsync(1))
expect(tx.to[0].amount.amount().toFixed()).toBe(amount.amount().toFixed())
expect(tx.hash).toBe(txId)
})

it('should transfer 0.01 AVAX between wallet 0 and 1, with a memo', async () => {
const recipient = client.getAddress(1)
const recipient = await client.getAddressAsync(1)
const amount = assetToBase(assetAmount('0.01', 18))
const memo = `=:BNB.BUSD-BD1:bnb1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:100000000000`
const txHash = await client.transfer({ amount, recipient, memo })
console.log(txHash)
})
it('should transfer 0.01 AVAX following EIP1559 because of maxFeePerGas', async () => {
const recipient = client.getAddress(1)
const recipient = await client.getAddressAsync(1)
const amount = assetToBase(assetAmount('0.01', 18))
const txHash = await client.transfer({
amount,
Expand All @@ -119,7 +119,7 @@ describe('xchain-evm (Avax) Integration Tests', () => {
console.log(txHash)
})
it('should transfer 0.01 AVAX following EIP1559 because of maxPriorityFeePerGas', async () => {
const recipient = client.getAddress(1)
const recipient = await client.getAddressAsync(1)
const amount = assetToBase(assetAmount('0.01', 18))
const txHash = await client.transfer({
amount,
Expand All @@ -137,7 +137,7 @@ describe('xchain-evm (Avax) Integration Tests', () => {
console.log(txHash)
})
it('should approve 0.01 RIP(ERC-20) between wallet 0 and 1', async () => {
const recipient = client.getAddress(1)
const recipient = await client.getAddressAsync(1)
const amount = assetToBase(assetAmount('0.01', 6))
//ERC20 address The Crypt (RIP)

Expand Down Expand Up @@ -193,7 +193,7 @@ describe('xchain-evm (Avax) Integration Tests', () => {
console.log(gasEstimate.toString())
expect(gasEstimate.gte(0)).toBe(true)

const recipient = client.getAddress(1)
const recipient = await client.getAddressAsync(1)
const amount = assetToBase(assetAmount('0.01', 18))
const memo = '=:BNB.BUSD-BD1:bnb1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:100000000000'
const gasEstimateWithMemo = await client.estimateFeesWithGasPricesAndLimits({ amount, recipient, memo })
Expand Down
30 changes: 15 additions & 15 deletions packages/xchain-binance/__tests__/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,30 +89,30 @@ describe('BinanceClient Test', () => {

it('should start with empty wallet', async () => {
const bnbClientEmptyMain = new BinanceClient({ phrase, network: 'mainnet' as Network })
const addressMain = bnbClientEmptyMain.getAddress()
const addressMain = await bnbClientEmptyMain.getAddressAsync()
expect(addressMain).toEqual(mainnetaddress_path0)

const bnbClientEmptyTest = new BinanceClient({ phrase, network: Network.Testnet })
const addressTest = bnbClientEmptyTest.getAddress()
const addressTest = await bnbClientEmptyTest.getAddressAsync()
expect(addressTest).toEqual(testnetaddress_path0)
})

it('should support derivation index as string', async () => {
const bnbForTxClientEmptyMain = new BinanceClient({ phrase: phraseForTX, network: Network.Testnet })
const address_path0ForTx = bnbForTxClientEmptyMain.getAddress()
const address_path0ForTx = await bnbForTxClientEmptyMain.getAddressAsync()
expect(address_path0ForTx).toEqual(testnetaddress_path0ForTx)

const bnbClientEmptyMain = new BinanceClient({ phrase, network: 'mainnet' as Network })
const addressMain = bnbClientEmptyMain.getAddress()
const addressMain = await bnbClientEmptyMain.getAddressAsync()
expect(addressMain).toEqual(mainnetaddress_path0)
const bnbClientEmptyMain_path1 = new BinanceClient({ phrase, network: 'mainnet' as Network })
expect(bnbClientEmptyMain_path1.getAddress(1)).toEqual(mainnetaddress_path1)
expect(await bnbClientEmptyMain_path1.getAddressAsync(1)).toEqual(mainnetaddress_path1)

const bnbClientEmptyTest = new BinanceClient({ phrase, network: Network.Testnet })
const addressTest = bnbClientEmptyTest.getAddress()
const addressTest = await bnbClientEmptyTest.getAddressAsync()
expect(addressTest).toEqual(testnetaddress_path0)
const bnbClientEmptyTest_path1 = new BinanceClient({ phrase, network: Network.Testnet })
expect(bnbClientEmptyTest_path1.getAddress(1)).toEqual(testnetaddress_path1)
expect(await bnbClientEmptyTest_path1.getAddressAsync(1)).toEqual(testnetaddress_path1)
})

it('should not throw on a client without a phrase', () => {
Expand All @@ -134,15 +134,15 @@ describe('BinanceClient Test', () => {
})

it('should have right address', async () => {
expect(bnbClient.getAddress()).toEqual(mainnetaddress_path0)
expect(bnbClient.getAddress(1)).toEqual(mainnetaddress_path1)
expect(await bnbClient.getAddressAsync()).toEqual(mainnetaddress_path0)
expect(await bnbClient.getAddressAsync(1)).toEqual(mainnetaddress_path1)
})

it('should update net', () => {
it('should update net', async () => {
const client = new BinanceClient({ phrase, network: 'mainnet' as Network })
client.setNetwork(Network.Testnet)
expect(client.getNetwork()).toEqual('testnet')
expect(client.getAddress()).toEqual(testnetaddress_path0)
expect(await client.getAddressAsync()).toEqual(testnetaddress_path0)
})

it('setPhrase should return address', () => {
Expand Down Expand Up @@ -352,7 +352,7 @@ describe('BinanceClient Test', () => {

it('should broadcast a transfer', async () => {
const client = new BinanceClient({ phrase: phraseForTX, network: Network.Testnet })
expect(client.getAddress()).toEqual(testnetaddress_path0ForTx)
expect(await client.getAddressAsync()).toEqual(testnetaddress_path0ForTx)

mockGetAccount(
testnetClientURL,
Expand Down Expand Up @@ -404,7 +404,7 @@ describe('BinanceClient Test', () => {
sequence: 0,
})

const afterTransfer = await client.getBalance(client.getAddress(0))
const afterTransfer = await client.getBalance(await client.getAddressAsync(0))
expect(afterTransfer.length).toEqual(1)

const expected = beforeTransfer[0].amount
Expand All @@ -416,7 +416,7 @@ describe('BinanceClient Test', () => {

it('should broadcast a multi transfer', async () => {
const client = new BinanceClient({ phrase: phraseForTX, network: Network.Testnet })
expect(client.getAddress()).toEqual(testnetaddress_path0ForTx)
expect(await client.getAddressAsync()).toEqual(testnetaddress_path0ForTx)

mockGetAccount(
testnetClientURL,
Expand Down Expand Up @@ -494,7 +494,7 @@ describe('BinanceClient Test', () => {
sequence: 0,
})

const afterTransfer = await client.getBalance(client.getAddress(0))
const afterTransfer = await client.getBalance(await client.getAddressAsync(0))
expect(afterTransfer.length).toEqual(1)

const expected = beforeTransfer[0].amount
Expand Down
16 changes: 12 additions & 4 deletions packages/xchain-binance/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,13 @@ class Client extends BaseXChainClient implements BinanceClient, XChainClient {
return crypto.getPrivateKeyFromMnemonic(this.phrase, true, index)
}

/**
* @deprecated this function eventually will be removed use getAddressAsync instead
*/
getAddress(index = 0): string {
return crypto.getAddressFromPrivateKey(this.getPrivateKey(index), getPrefix(this.network))
}

/**
* Get the current address.
*
Expand All @@ -218,9 +225,10 @@ class Client extends BaseXChainClient implements BinanceClient, XChainClient {
*
* @throws {Error} Thrown if phrase has not been set before. A phrase is needed to create a wallet and to derive an address from it.
*/
getAddress(index = 0): string {
return crypto.getAddressFromPrivateKey(this.getPrivateKey(index), getPrefix(this.network))
async getAddressAsync(index = 0): Promise<string> {
return this.getAddress(index)
}

/**
* Validate the given address.
*
Expand Down Expand Up @@ -251,7 +259,7 @@ class Client extends BaseXChainClient implements BinanceClient, XChainClient {
* @returns {Account} account details of given address.
*/
async getAccount(address?: Address, index = 0): Promise<Account> {
const accountAddress = address || this.getAddress(index)
const accountAddress = address || (await this.getAddressAsync(index))
const response = await this.bncClient.getAccount(accountAddress)
if (!response || !response.result || !isAccount(response.result))
return Promise.reject(Error(`Could not get account data for address ${accountAddress}`))
Expand Down Expand Up @@ -407,7 +415,7 @@ class Client extends BaseXChainClient implements BinanceClient, XChainClient {
await this.bncClient.setPrivateKey(this.getPrivateKey(walletIndex || 0))

const transferResult = await this.bncClient.transfer(
this.getAddress(walletIndex),
await this.getAddressAsync(walletIndex),
recipient,
baseToAsset(amount).amount().toString(),
asset ? asset.symbol : AssetBNB.symbol,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ describe('Bitcoin Integration Tests for BlockCypher', () => {
it('should send a testnet btc tx via blockcypher', async () => {
try {
// const from = btcClientTestnet.getAddress(0)
const to = btcClientTestnet.getAddress(1)
const to = await btcClientTestnet.getAddressAsync(1)
// console.log(JSON.stringify(to, null, 2))
const amount = assetToBase(assetAmount('0.000011'))
const txid = await btcClientTestnet.transfer({
Expand Down Expand Up @@ -143,8 +143,8 @@ describe('Bitcoin Integration Tests for BlockCypher', () => {
})
it('Try to send max amount', async () => {
try {
const firstAddress = btcClientTestnet.getAddress(0)
const address = btcClientTestnet.getAddress(1)
const firstAddress = await btcClientTestnet.getAddressAsync(0)
const address = await btcClientTestnet.getAddressAsync(1)
console.log('address', address)
const balance = await btcClientTestnet.getBalance(address)
console.log(balance[0].amount.amount().toString())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ describe('Bitcoin Integration Tests for Haskoin', () => {
try {
// const from = btcClientTestnet.getAddress(0)
// console.log(from)
const to = btcClientTestnet.getAddress(1)
const to = await btcClientTestnet.getAddressAsync(1)
const amount = assetToBase(assetAmount('0.00001'))
const txid = await btcClientTestnet.transfer({
asset: AssetBTC,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ describe('Bitcoin Integration Sochain Tests', () => {
it('should send a testnet btc tx via sochain', async () => {
try {
//const from = btcClientTestnet.getAddress(0)
const to = btcClientTestnet.getAddress(1)
const to = await btcClientTestnet.getAddressAsync(1)
console.log(JSON.stringify(to, null, 2))
const amount = assetToBase(assetAmount('0.00001'))
const txid = await btcClientTestnet.transfer({
Expand Down
35 changes: 20 additions & 15 deletions packages/xchain-bitcoin/__tests__/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,10 @@ describe('BitcoinClient Test', () => {
expect(btcClient.setPhrase(phraseOne)).toBeUndefined
})

it('should validate the right address', () => {
it('should validate the right address', async () => {
btcClient.setNetwork(Network.Testnet)
btcClient.setPhrase(phraseOne)
const address = btcClient.getAddress()
const address = await btcClient.getAddressAsync()
const valid = btcClient.validateAddress(address)
expect(address).toEqual(addyOnePath0)
expect(valid).toBeTruthy()
Expand All @@ -106,15 +106,15 @@ describe('BitcoinClient Test', () => {
it('all balances test', async () => {
btcClient.setNetwork(Network.Testnet)
btcClient.setPhrase(phraseOne)
const balance = await btcClient.getBalance(btcClient.getAddress())
const balance = await btcClient.getBalance(await btcClient.getAddressAsync())
expect(balance.length).toEqual(1)
expect(balance[0].amount.amount().toNumber()).toEqual(384776)
})

it('confirmed balances only', async () => {
btcClient.setNetwork(Network.Testnet)
btcClient.setPhrase(phraseOne)
const balance = await btcClient.getBalance(btcClient.getAddress(), undefined, true)
const balance = await btcClient.getBalance(await btcClient.getAddressAsync(), undefined, true)
expect(balance.length).toEqual(1)
expect(balance[0].amount.amount().toNumber()).toEqual(384776)
})
Expand Down Expand Up @@ -201,7 +201,12 @@ describe('BitcoinClient Test', () => {

it('should purge phrase and utxos', async () => {
btcClient.purgeClient()
expect(() => btcClient.getAddress()).toThrow('Phrase must be provided')
try {
const address = await btcClient.getAddressAsync()
expect(address).toBe('')
} catch (e: any) {
expect(e.message).toEqual('Phrase must be provided')
}
})

it('should fail with out of bound fees', async () => {
Expand Down Expand Up @@ -292,7 +297,7 @@ describe('BitcoinClient Test', () => {
expect(estimates.average.amount().toString()).toEqual('1794')
// Estimate with max preccission
const estimatesWithSender = await btcClient.getFees({
sender: btcClient.getAddress(0),
sender: await btcClient.getAddressAsync(0),
})
expect(estimatesWithSender.fast.amount().toString()).toEqual('9476')
expect(estimatesWithSender.fastest.amount().toString()).toEqual('47380')
Expand Down Expand Up @@ -420,25 +425,25 @@ describe('BitcoinClient Test', () => {
)
})

it('should derivate the address correctly', () => {
it('should derivate the address correctly', async () => {
btcClient.setNetwork(Network.Mainnet)

btcClient.setPhrase(phraseOne)
expect(btcClient.getAddress(0)).toEqual(phraseOneMainnet_path0)
expect(btcClient.getAddress(1)).toEqual(phraseOneMainnet_path1)
expect(await btcClient.getAddressAsync(0)).toEqual(phraseOneMainnet_path0)
expect(await btcClient.getAddressAsync(1)).toEqual(phraseOneMainnet_path1)

btcClient.setPhrase(phraseTwo)
expect(btcClient.getAddress(0)).toEqual(phraseTwoMainnet_path0)
expect(btcClient.getAddress(1)).toEqual(phraseTwoMainnet_path1)
expect(await btcClient.getAddressAsync(0)).toEqual(phraseTwoMainnet_path0)
expect(await btcClient.getAddressAsync(1)).toEqual(phraseTwoMainnet_path1)

btcClient.setNetwork(Network.Testnet)

btcClient.setPhrase(phraseOne)
expect(btcClient.getAddress(0)).toEqual(addyOnePath0)
expect(btcClient.getAddress(1)).toEqual(addyOnePath1)
expect(await btcClient.getAddressAsync(0)).toEqual(addyOnePath0)
expect(await btcClient.getAddressAsync(1)).toEqual(addyOnePath1)

btcClient.setPhrase(phraseTwo)
expect(btcClient.getAddress(0)).toEqual(addyThreePath0)
expect(btcClient.getAddress(1)).toEqual(addyThreePath1)
expect(await btcClient.getAddressAsync(0)).toEqual(addyThreePath0)
expect(await btcClient.getAddressAsync(1)).toEqual(addyThreePath1)
})
})
31 changes: 21 additions & 10 deletions packages/xchain-bitcoin/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,7 @@ class Client extends UTXOClient {
}

/**
* Get the current address.
*
* Generates a network-specific key-pair by first converting the buffer to a Wallet-Import-Format (WIF)
* The address is then decoded into type P2WPKH and returned.
*
* @returns {Address} The current address.
*
* @throws {"Phrase must be provided"} Thrown if phrase has not been set before.
* @throws {"Address not defined"} Thrown if failed creating account from phrase.
* @deprecated this function eventually will be removed use getAddressAsync instead
*/
getAddress(index = 0): Address {
if (index < 0) {
Expand All @@ -98,6 +90,21 @@ class Client extends UTXOClient {
throw new Error('Phrase must be provided')
}

/**
* Get the current address.
*
* Generates a network-specific key-pair by first converting the buffer to a Wallet-Import-Format (WIF)
* The address is then decoded into type P2WPKH and returned.
*
* @returns {Address} The current address.
*
* @throws {"Phrase must be provided"} Thrown if phrase has not been set before.
* @throws {"Address not defined"} Thrown if failed creating account from phrase.
*/
async getAddressAsync(index = 0): Promise<string> {
return this.getAddress(index)
}

/**
*
* @returns BTC asset info
Expand Down Expand Up @@ -208,7 +215,11 @@ class Client extends UTXOClient {
checkFeeBounds(this.feeBounds, feeRate)

const fromAddressIndex = params?.walletIndex || 0
const { rawUnsignedTx } = await this.prepareTx({ ...params, sender: this.getAddress(fromAddressIndex), feeRate })
const { rawUnsignedTx } = await this.prepareTx({
...params,
sender: await this.getAddressAsync(fromAddressIndex),
feeRate,
})

const btcKeys = this.getBtcKeys(this.phrase, fromAddressIndex)
const psbt = Bitcoin.Psbt.fromBase64(rawUnsignedTx)
Expand Down
Loading

0 comments on commit 302d928

Please sign in to comment.