-
Notifications
You must be signed in to change notification settings - Fork 1.5k
feat: add unisat, bitget and binance web3 wallet bitcoin connector #4465
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
danielsimao
wants to merge
3
commits into
reown-com:main
Choose a base branch
from
bob-collective:feat/add-unisat-wallet
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
265 changes: 265 additions & 0 deletions
265
packages/adapters/bitcoin/src/connectors/UnisatConnector.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,265 @@ | ||
/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/require-await */ | ||
import { type CaipNetwork, ConstantsUtil } from '@reown/appkit-common' | ||
import { CoreHelperUtil, type RequestArguments } from '@reown/appkit-controllers' | ||
import { bitcoin, bitcoinTestnet } from '@reown/appkit/networks' | ||
|
||
import { MethodNotSupportedError } from '../errors/MethodNotSupportedError.js' | ||
import type { BitcoinConnector } from '../utils/BitcoinConnector.js' | ||
import { AddressPurpose } from '../utils/BitcoinConnector.js' | ||
import { ProviderEventEmitter } from '../utils/ProviderEventEmitter.js' | ||
import { UnitsUtil } from '../utils/UnitsUtil.js' | ||
|
||
export class UnisatConnector extends ProviderEventEmitter implements BitcoinConnector { | ||
public id: UnisatConnector.Id | ||
public name | ||
public readonly chain = 'bip122' | ||
public readonly type = 'ANNOUNCED' | ||
public readonly imageUrl: string | ||
|
||
public readonly provider = this | ||
|
||
private readonly wallet: UnisatConnector.Wallet | ||
private readonly requestedChains: CaipNetwork[] = [] | ||
private readonly getActiveNetwork: () => CaipNetwork | undefined | ||
|
||
constructor({ | ||
id, | ||
name, | ||
wallet, | ||
requestedChains, | ||
getActiveNetwork, | ||
imageUrl | ||
}: UnisatConnector.ConstructorParams) { | ||
super() | ||
this.id = id | ||
this.name = name | ||
this.wallet = wallet | ||
this.requestedChains = requestedChains | ||
this.getActiveNetwork = getActiveNetwork | ||
this.imageUrl = imageUrl | ||
} | ||
|
||
public get chains() { | ||
if (this.id === 'unisat') { | ||
return this.requestedChains.filter(chain => chain.caipNetworkId === bitcoin.caipNetworkId) | ||
} | ||
|
||
return this.requestedChains.filter( | ||
chain => chain.chainNamespace === ConstantsUtil.CHAIN.BITCOIN | ||
) | ||
} | ||
|
||
public async connect(): Promise<string> { | ||
const [account] = await this.wallet.requestAccounts() | ||
|
||
if (!account) { | ||
throw new Error('No account found') | ||
} | ||
|
||
this.bindEvents() | ||
|
||
this.emit('accountsChanged', [account]) | ||
|
||
return account | ||
} | ||
|
||
public async disconnect(): Promise<void> { | ||
this.unbindEvents() | ||
|
||
return Promise.resolve() | ||
} | ||
|
||
public async getAccountAddresses(): Promise<BitcoinConnector.AccountAddress[]> { | ||
const accounts = await this.wallet.requestAccounts() | ||
|
||
const publicKey = await this.wallet.getPublicKey() | ||
|
||
const accountList = accounts.map(account => ({ | ||
address: account, | ||
purpose: AddressPurpose.Payment, | ||
publicKey | ||
})) | ||
|
||
return accountList | ||
} | ||
|
||
public async signMessage(params: BitcoinConnector.SignMessageParams): Promise<string> { | ||
const protocol = params.protocol === 'bip322' ? 'bip322-simple' : params.protocol | ||
|
||
return this.wallet.signMessage(params.message, protocol) | ||
} | ||
|
||
public async sendTransfer(params: BitcoinConnector.SendTransferParams): Promise<string> { | ||
const network = this.getActiveNetwork() | ||
|
||
if (!network) { | ||
throw new Error('No active network available') | ||
} | ||
|
||
const from = (await this.wallet.getAccounts())[0] | ||
|
||
if (!from) { | ||
throw new Error('No account available') | ||
} | ||
|
||
const result = await this.wallet.sendBitcoin( | ||
params.recipient, | ||
Number(UnitsUtil.parseSatoshis(params.amount, network)) | ||
) | ||
|
||
return result | ||
} | ||
|
||
public async signPSBT( | ||
params: BitcoinConnector.SignPSBTParams | ||
): Promise<BitcoinConnector.SignPSBTResponse> { | ||
const psbtHex = Buffer.from(params.psbt, 'base64').toString('hex') | ||
|
||
const signedPsbtHex = await this.wallet.signPsbt(psbtHex) | ||
|
||
let txid: string | undefined = undefined | ||
if (params.broadcast) { | ||
txid = await this.wallet.pushPsbt(signedPsbtHex) | ||
} | ||
|
||
return { | ||
psbt: Buffer.from(signedPsbtHex, 'hex').toString('base64'), | ||
txid | ||
} | ||
} | ||
|
||
public async switchNetwork(caipNetworkId: string): Promise<void> { | ||
const network = this.getNetwork(caipNetworkId) | ||
|
||
await this.wallet.switchChain(network) | ||
} | ||
|
||
public request<T>(_args: RequestArguments): Promise<T> { | ||
return Promise.reject(new MethodNotSupportedError(this.id, 'request')) | ||
} | ||
|
||
private bindEvents(): void { | ||
this.unbindEvents() | ||
|
||
this.wallet.on('accountsChanged', account => { | ||
if (typeof account === 'object' && account && 'address' in account) { | ||
this.emit('accountsChanged', [account.address]) | ||
} | ||
}) | ||
} | ||
|
||
private unbindEvents(): void { | ||
this.wallet.removeListener('accountsChanged', account => { | ||
if (typeof account === 'object' && account && 'address' in account) { | ||
this.emit('accountsChanged', [account.address]) | ||
} | ||
}) | ||
} | ||
|
||
public static getWallet(params: UnisatConnector.GetWalletParams): UnisatConnector | undefined { | ||
if (!CoreHelperUtil.isClient()) { | ||
return undefined | ||
} | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, init-declarations | ||
let wallet: any | ||
|
||
switch (params.id) { | ||
case 'unisat': | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
wallet = (window as any)?.unisat | ||
break | ||
case 'bitget': | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
wallet = (window as any)?.bitkeep?.unisat | ||
break | ||
case 'binancew3w': | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
wallet = (window as any)?.binancew3w?.bitcoin | ||
break | ||
default: | ||
throw new Error(`Unsupported wallet id: ${params.id}`) | ||
} | ||
|
||
if (wallet) { | ||
return new UnisatConnector({ wallet, imageUrl: '', ...params }) | ||
} | ||
|
||
return undefined | ||
} | ||
|
||
public async getPublicKey(): Promise<string> { | ||
return this.wallet.getPublicKey() | ||
} | ||
|
||
private getNetwork(caipNetwork: string): UnisatConnector.Chain { | ||
switch (caipNetwork) { | ||
case bitcoin.caipNetworkId: | ||
return 'BITCOIN_MAINNET' | ||
case bitcoinTestnet.caipNetworkId: | ||
return 'BITCOIN_TESTNET' | ||
default: | ||
throw new Error('UnisatConnector: unsupported network') | ||
} | ||
} | ||
} | ||
|
||
export namespace UnisatConnector { | ||
export type Chain = 'BITCOIN_MAINNET' | 'BITCOIN_TESTNET' | 'FRACTAL_BITCOIN_MAINNET' | ||
danielsimao marked this conversation as resolved.
Show resolved
Hide resolved
|
||
export type Network = 'livenet' | 'testnet' | ||
danielsimao marked this conversation as resolved.
Show resolved
Hide resolved
|
||
export type Id = 'unisat' | 'bitget' | 'binancew3w' | ||
|
||
export type ConstructorParams = { | ||
id: Id | ||
name: string | ||
wallet: Wallet | ||
requestedChains: CaipNetwork[] | ||
getActiveNetwork: () => CaipNetwork | undefined | ||
imageUrl: string | ||
} | ||
|
||
export type Wallet = { | ||
/* | ||
* This interface doesn't include all available methods | ||
* Reference: https://www.okx.com/web3/build/docs/sdks/chains/bitcoin/provider | ||
*/ | ||
|
||
requestAccounts: () => Promise<string[]> | ||
getPublicKey: () => Promise<string> | ||
sendBitcoin: ( | ||
to: string, | ||
value: number, | ||
options?: { feeRate: number; memo?: string; memos?: string[] } | ||
) => Promise<string> | ||
signPsbt: ( | ||
psbtHex: string, | ||
options?: { | ||
autoFinalized?: boolean | ||
toSignInputs: Array< | ||
| { | ||
index: number | ||
address: string | ||
sighashTypes?: number[] | ||
disableTweakSigner?: boolean | ||
useTweakedSigner?: boolean | ||
} | ||
| { | ||
index: number | ||
publicKey: string | ||
sighashTypes?: number[] | ||
disableTweakSigner?: boolean | ||
useTweakedSigner?: boolean | ||
} | ||
> | ||
} | ||
) => Promise<string> | ||
switchChain(chain: Chain): Promise<{ enum: Chain; name: string; network: Network }> | ||
getAccounts(): Promise<string[]> | ||
signMessage(signStr: string, type?: 'ecdsa' | 'bip322-simple'): Promise<string> | ||
pushPsbt(psbtHex: string): Promise<string> | ||
on(event: string, listener: (param?: unknown) => void): void | ||
removeListener(event: string, listener: (param?: unknown) => void): void | ||
} | ||
|
||
export type GetWalletParams = Omit<ConstructorParams, 'wallet' | 'imageUrl'> | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.