Skip to content

Commit

Permalink
add getBalance()
Browse files Browse the repository at this point in the history
  • Loading branch information
alecande11 committed Oct 6, 2022
1 parent 85f5fb2 commit 356a845
Show file tree
Hide file tree
Showing 6 changed files with 172 additions and 14 deletions.
58 changes: 58 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,59 @@
# Bridge SDK

## Basic usage

Connect station:

```js
import { StationWallet, ChainType, BridgeType } from 'bridge-sdk'

const wallet = new StationWallet()

if (!wallet.isSupported()) {
console.log(
`${wallet.description.name} is not supported on your device, please try from a different wallet.`,
)
} else if (!wallet.isInstalled()) {
console.log(`You can install ${wallet.description.name} here: ${wallet.description.installLink}`)
}

wallet
.connect(ChainType.terra)
.then(({ address }) => console.log(address))
```

Get the balance (wallet must be already connected):
```js
wallet
.getBalance('uluna')
.then((res) => {
res.success
? console.log(`Balance: ${res.data} uluna`)
: console.log(`Error: ${res.error}`
})
```
Send tx from station (wallet must be already connected):
```js
wallet
.transfer({
src: ChainType.terra,
dst: ChainType.osmosis,
bridge: BridgeType.ibc,
address: 'osmo1...',
coin: {
amount: 100_000,
denom: 'uluna',
},
})
.then((res) => {
res.success
? console.log(`TX hash: ${res.txhash}`)
: console.log(`Error: ${res.error}`
})
```
> You can use the same functions on the `KeplrWallet` and `MetaMaskWallet` to send a tx from those wallets
>
> You can find more info about the available functions on the [Wallet inteface](/src/wallets/Wallet.ts#25)
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "bridge-sdk",
"version": "1.0.0",
"version": "1.0.0-beta.1",
"description": "",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
Expand Down
13 changes: 13 additions & 0 deletions src/wallets/Wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,23 @@ export type TxResult =
error: string
}

export type QueryResult<T> =
| {
success: true
data: T
}
| {
success: false
error: string
}

export interface Wallet {
isSupported(): boolean
isInstalled(): boolean
connect(chain: ChainType): Promise<{ address: string }>
getBalance(
token: string,
): Promise<QueryResult<number>>
transfer(tx: Tx): Promise<TxResult>

supportedChains: ChainType[]
Expand Down
29 changes: 24 additions & 5 deletions src/wallets/keplr/KeplrWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import { SigningStargateClient } from '@cosmjs/stargate'
import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx.js'
import { BridgeType } from '../../const/bridges'
import { ChainType, chainIDs, ibcChannels } from '../../const/chains'
import { Tx, TxResult, Wallet } from '../Wallet'
import { QueryResult, Tx, TxResult, Wallet } from '../Wallet'
import { getAxelarDepositAddress } from '../../packages/axelar'

type KeplrChain = ChainType.cosmos | ChainType.osmosis

const keplrRpc: Record<KeplrChain, string> = {
[ChainType.cosmos]: 'https://rpc-cosmoshub-ia.notional.ventures/',
[ChainType.osmosis]: '',
[ChainType.cosmos]: 'https://cosmos-mainnet-rpc.allthatnode.com:26657/',
[ChainType.osmosis]: 'https://rpc.osmosis.zone/',
}

declare global {
Expand All @@ -21,6 +21,7 @@ declare global {
export class KeplrWallet implements Wallet {
private address: string = ''
private signer: SigningStargateClient | null = null
private chain: ChainType | null = null

isSupported(): boolean {
// supported on chrome, edge and firefox (only on desktop)
Expand All @@ -46,6 +47,7 @@ export class KeplrWallet implements Wallet {
const accounts = await keplrOfflineSigner.getAccounts()

this.address = accounts[0].address
this.chain = chain
this.signer = await SigningStargateClient.connectWithSigner(
rpc || keplrRpc[chain as KeplrChain],
keplrOfflineSigner,
Expand All @@ -61,17 +63,34 @@ export class KeplrWallet implements Wallet {
return { address: accounts[0].address }
}

async getBalance(
token: string,
): Promise<QueryResult<number>> {
if (!this.signer) {
return {
success: false,
error: `You must connect the wallet before the query`,
}
}

const res = await this.signer.getBalance(this.address, token)
return {
success: true,
data: parseInt(res.amount),
}
}

async transfer(tx: Tx): Promise<TxResult> {
if (!this.address || !this.signer) {
return {
success: false,
error: `You must connect the wallet before the transfer`,
}
}
if (!this.supportedChains.includes(tx.src)) {
if (tx.src !== this.chain) {
return {
success: false,
error: `${tx.src} is not supported by ${this.description.name}`,
error: `You must connect to ${tx.src} before the transfer`,
}
}
if (tx.src === tx.dst) {
Expand Down
22 changes: 21 additions & 1 deletion src/wallets/metamask/MetaMaskWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import MetaMaskOnboarding from '@metamask/onboarding'
import { BridgeType } from '../../const/bridges'
import { chainIDs, ChainType } from '../../const/chains'
import { getAxelarDepositAddress } from '../../packages/axelar'
import { Tx, TxResult, Wallet } from '../Wallet'
import { QueryResult, Tx, TxResult, Wallet } from '../Wallet'
import { ethers } from 'ethers'
import abi from './abi'

Expand All @@ -27,6 +27,26 @@ export class MetaMaskWallet implements Wallet {
return MetaMaskOnboarding.isMetaMaskInstalled()
}

async getBalance(
token: string,
): Promise<QueryResult<number>> {
if (!this.address) {
return {
success: false,
error: `You must connect the wallet before the query`,
}
}

const contract = new ethers.Contract(token, abi, window.ethereum)

const result = await contract.balanceOf(this.address)

return {
success: true,
data: result.toNumber(),
}
}

async connect(chain: ChainType): Promise<{ address: string }> {
if (!this.supportedChains.includes(chain)) {
throw new Error(`${chain} is not supported by ${this.description.name}`)
Expand Down
62 changes: 55 additions & 7 deletions src/wallets/station/StationWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import {
Coin,
CreateTxOptions,
Extension,
LCDClient,
MsgTransfer,
} from '@terra-money/terra.js'
import { BridgeType } from '../../const/bridges'
import { ChainType, ibcChannels } from '../../const/chains'
import { getAxelarDepositAddress } from '../../packages/axelar'
import { Tx, TxResult, Wallet } from '../Wallet'
import { QueryResult, Tx, TxResult, Wallet } from '../Wallet'

const ext = new Extension()

Expand Down Expand Up @@ -37,6 +38,47 @@ export class StationWallet implements Wallet {
return res
}

async getBalance(
token: string,
): Promise<QueryResult<number>> {
if (!this.address) {
return {
success: false,
error: `You must connect the wallet before the query`,
}
}

const lcd = new LCDClient({
URL: 'https://phoenix-lcd.terra.dev',
chainID: 'phoenix-1',
})

if (token.startsWith('terra1')) {
const result = (await lcd.wasm.contractQuery(token, {
balance: {
address: this.address,
},
})) as {
data: {
balance: string
}
}

return {
success: true,
data: parseInt(result.data.balance),
}
} else {
const result = await lcd.bank.balance(this.address)
const coin = result[0].get(token)

return {
success: true,
data: coin?.amount?.toNumber() || 0,
}
}
}

async transfer(tx: Tx): Promise<TxResult> {
if (!this.address) {
return {
Expand Down Expand Up @@ -93,12 +135,18 @@ export class StationWallet implements Wallet {
}

case BridgeType.axelar:
const depositAddress = await getAxelarDepositAddress(tx.address, tx.src, tx.dst, tx.coin.denom)

if(!depositAddress) return {
success: false,
error: 'Can\'t generate the Axelar deposit address'
}
const depositAddress = await getAxelarDepositAddress(
tx.address,
tx.src,
tx.dst,
tx.coin.denom,
)

if (!depositAddress)
return {
success: false,
error: "Can't generate the Axelar deposit address",
}

const axlTx: CreateTxOptions = {
msgs: [
Expand Down

0 comments on commit 356a845

Please sign in to comment.