Skip to content
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

Refactor RPC and rewrite aepp-rpc to TypeScript #1542

Merged
merged 11 commits into from
May 30, 2022
12 changes: 6 additions & 6 deletions docs/guides/build-wallet.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,10 @@ async function init () {
// create connection
const connection = new BrowserRuntimeConnection({ port })
// add new aepp to wallet
wallet.addRpcClient(connection)
const clientId = aeSdk.addRpcClient(connection)
// share wallet details
wallet.shareWalletInfo(port.postMessage.bind(port))
setTimeout(() => wallet.shareWalletInfo(port.postMessage.bind(port)), 3000)
aeSdk.shareWalletInfo(clientId)
setInterval(() => aeSdk.shareWalletInfo(clientId), 3000)
})
}).catch(err => {
console.error(err)
Expand Down Expand Up @@ -190,10 +190,10 @@ async function init () {
// create connection
const connection = new BrowserRuntimeConnection({ port })
// add new aepp to wallet
wallet.addRpcClient(connection)
const clientId = aeSdk.addRpcClient(connection)
// share wallet details
wallet.shareWalletInfo(port.postMessage.bind(port))
setTimeout(() => wallet.shareWalletInfo(port.postMessage.bind(port)), 3000)
aeSdk.shareWalletInfo(clientId)
setInterval(() => aeSdk.shareWalletInfo(clientId), 3000)
})
}).catch(err => {
console.error(err)
Expand Down
4 changes: 2 additions & 2 deletions docs/guides/connect-aepp-to-wallet.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ Append method for wallet connection

```js
async connect(wallet) {
await this.aeSdk.connectToWallet(wallet.info, wallet.getConnection())
await this.aeSdk.connectToWallet(wallet.getConnection())
this.connectedAccounts = await this.aeSdk.subscribeAddress('subscribe', 'connected')
this.address = await this.aeSdk.address()
this.balance = await this.aeSdk.getBalance(this.address).catch(() => '0')
Expand All @@ -93,7 +93,7 @@ Aepp can request the wallet to share its connected node URLs if any to interact

```js
async connect (wallet) {
await this.aeSdk.connectToWallet(wallet.info, wallet.getConnection(), { connectNode: true, name: 'wallet-node', select: true })
await this.aeSdk.connectToWallet(wallet.getConnection(), { connectNode: true, name: 'wallet-node', select: true })
}
```

Expand Down
11 changes: 10 additions & 1 deletion docs/guides/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ BaseError
│ │ InvalidAensNameError
└───AeppError
│ │ DuplicateCallbackError
│ │ InvalidRpcMessageError
│ │ MissingCallbackError
│ │ UnAuthorizedAccountError
Expand Down Expand Up @@ -98,6 +97,16 @@ BaseError
│ │ AlreadyConnectedError
│ │ NoWalletConnectedError
│ │ RpcConnectionError
└̌───RpcError
│ │ RpcInvalidTransactionError
│ │ RpcBroadcastError
│ │ RpcRejectedByUserError
│ │ RpcUnsupportedProtocolError
│ │ RpcConnectionDenyError
│ │ RpcNotAuthorizeError
│ │ RpcPermissionDenyError
│ │ RpcInternalError
```

## Usage
Expand Down
7 changes: 4 additions & 3 deletions examples/browser/aepp/src/Connect.vue
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,15 @@ export default {
walletConnected: false,
connectPromise: null,
reverseIframe: null,
reverseIframeWalletUrl: 'http://localhost:9000'
reverseIframeWalletUrl: 'http://localhost:9000',
walletInfo: null
}),
computed: {
...mapGetters('aeSdk', ['aeSdk']),
walletName () {
if (!this.aeSdk) return 'SDK is not ready'
if (!this.walletConnected) return 'Wallet is not connected'
return this.aeSdk.rpcClient.info.name
return this.walletInfo.name
}
},
methods: {
Expand All @@ -69,7 +70,7 @@ export default {
console.log('newWallet', newWallet)
stopScan()

await this.aeSdk.connectToWallet(newWallet.info, newWallet.getConnection())
this.walletInfo = await this.aeSdk.connectToWallet(newWallet.getConnection())
this.walletConnected = true
const { address: { current } } = await this.aeSdk.subscribeAddress('subscribe', 'connected')
this.$store.commit('aeSdk/setAddress', Object.keys(current)[0])
Expand Down
14 changes: 7 additions & 7 deletions examples/browser/wallet-iframe/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,17 @@ export default {
}
},
methods: {
async shareWalletInfo (postFn, { interval = 5000, attemps = 5 } = {}) {
this.aeSdk.shareWalletInfo(postFn)
async shareWalletInfo (clientId, { interval = 5000, attemps = 5 } = {}) {
this.aeSdk.shareWalletInfo(clientId)
while (attemps -= 1) {
await new Promise(resolve => setTimeout(resolve, interval))
this.aeSdk.shareWalletInfo(postFn)
this.aeSdk.shareWalletInfo(clientId)
}
console.log('Finish sharing wallet info')
},
disconnect () {
Object.values(this.aeSdk.rpcClients).forEach(client => {
client.sendMessage({ method: METHODS.closeConnection }, true)
client.notify(METHODS.closeConnection)
client.disconnect()
})
},
Expand Down Expand Up @@ -99,16 +99,16 @@ export default {
onMessageSign: genConfirmCallback(() => 'message sign'),
onAskAccounts: genConfirmCallback(() => 'get accounts'),
onDisconnect (message, client) {
this.shareWalletInfo(connection.sendMessage.bind(connection))
this.shareWalletInfo(clientId)
}
})
this.nodeName = this.aeSdk.selectedNode.name
this.address = this.aeSdk.addresses()[0]

const target = this.runningInFrame ? window.parent : this.$refs.aepp.contentWindow
const connection = new BrowserWindowMessageConnection({ target })
this.aeSdk.addRpcClient(connection)
this.shareWalletInfo(connection.sendMessage.bind(connection))
const clientId = this.aeSdk.addRpcClient(connection)
this.shareWalletInfo(clientId)

this.$watch(
({ address, nodeName }) => [address, nodeName],
Expand Down
6 changes: 3 additions & 3 deletions examples/browser/wallet-web-extension/src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ import {
// create connection
const connection = new BrowserRuntimeConnection({ port })
// add new aepp to wallet
aeSdk.addRpcClient(connection)
const clientId = aeSdk.addRpcClient(connection)
// share wallet details
aeSdk.shareWalletInfo(port.postMessage.bind(port))
setInterval(() => aeSdk.shareWalletInfo(port.postMessage.bind(port)), 3000)
aeSdk.shareWalletInfo(clientId)
setInterval(() => aeSdk.shareWalletInfo(clientId), 3000)
})

console.log('Wallet initialized!')
Expand Down
5 changes: 3 additions & 2 deletions src/account/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,12 @@ class _AccountRpc extends _AccountBase {
): Promise<EncodedData<'tx'>> {
if (innerTx != null) throw new NotImplementedError('innerTx option in AccountRpc')
if (networkId !== this._networkId) throw new NotImplementedError('networkId should be equal to current network')
return this._rpcClient.request(METHODS.sign, {
const res = await this._rpcClient.request(METHODS.sign, {
onAccount: this._address,
tx,
returnSigned: true
})
return res.signedTransaction
}

/**
Expand All @@ -60,7 +61,7 @@ class _AccountRpc extends _AccountBase {
async signMessage (
message: string, { returnHex = false }: Parameters<_AccountBase['signMessage']>[1] = {}
): Promise<string | Uint8Array> {
const signature = await this._rpcClient.request(
const { signature } = await this._rpcClient.request(
METHODS.signMessage, { onAccount: this._address, message }
)
return returnHex ? signature : Buffer.from(signature, 'hex')
Expand Down
8 changes: 4 additions & 4 deletions src/ae/aens.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,14 +182,14 @@ async function query (name, opt = {}) {
pointers: o.pointers || [],
update: async (pointers, options = {}) => {
return {
...(await this.aensUpdate(name, pointers, { ...opt, ...options })),
...(await this.aensQuery(name))
...await this.aensUpdate(name, pointers, { ...opt, ...options }),
...await this.aensQuery(name)
}
},
transfer: async (account, options = {}) => {
return {
...(await this.aensTransfer(name, account, { ...opt, ...options })),
...(await this.aensQuery(name))
...await this.aensTransfer(name, account, { ...opt, ...options }),
...await this.aensQuery(name)
}
},
revoke: async (options = {}) => this.aensRevoke(name, { ...opt, ...options }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ export default class BrowserWindowMessageConnection extends BrowserConnection {
sendDirection?: MESSAGE_DIRECTION
receiveDirection: MESSAGE_DIRECTION
listener?: (this: Window, ev: MessageEvent<any>) => void
_target?: Window
_self: Window
#onDisconnect?: () => void
#target?: Window
#self: Window

constructor ({
target,
Expand All @@ -54,8 +55,8 @@ export default class BrowserWindowMessageConnection extends BrowserConnection {
debug?: boolean
} = {}) {
super(options)
this._target = target
this._self = self
this.#target = target
this.#self = self
this.origin = origin
this.sendDirection = sendDirection
this.receiveDirection = receiveDirection
Expand All @@ -73,7 +74,7 @@ export default class BrowserWindowMessageConnection extends BrowserConnection {
this.listener = (message: MessageEvent<any>) => {
if (typeof message.data !== 'object') return
if (this.origin != null && this.origin !== message.origin) return
if (this._target != null && this._target !== message.source) return
if (this.#target != null && this.#target !== message.source) return
this.receiveMessage(message)
let { data } = message
if (data.type != null) {
Expand All @@ -82,20 +83,25 @@ export default class BrowserWindowMessageConnection extends BrowserConnection {
}
onMessage(data, message.origin, message.source)
}
this._self.addEventListener('message', this.listener)
this.#self.addEventListener('message', this.listener)
this.#onDisconnect = onDisconnect
}

disconnect (): void {
super.disconnect()
if (this.listener == null) throw new InternalError('Expected to not happen, required for TS')
this._self.removeEventListener('message', this.listener)
if (this.listener == null || this.#onDisconnect == null) {
throw new InternalError('Expected to not happen, required for TS')
}
this.#self.removeEventListener('message', this.listener)
delete this.listener
this.#onDisconnect()
this.#onDisconnect = undefined
}

sendMessage (msg: MessageEvent): void {
if (this._target == null) throw new RpcConnectionError('Can\'t send messages without target')
if (this.#target == null) throw new RpcConnectionError('Can\'t send messages without target')
const message = this.sendDirection != null ? { type: this.sendDirection, data: msg } : msg
super.sendMessage(message)
this._target.postMessage(message, this.origin ?? '*')
this.#target.postMessage(message, this.origin ?? '*')
}
}
Loading