Skip to content

Commit

Permalink
refactor(rpc-client)!: add notify method
Browse files Browse the repository at this point in the history
BREAKING CHANGE: `sendMessage` of RpcClient is a private method
Use `request` or `notify` instead.

BREAKING CHANGE: `shareWalletInfo` of WalletRpc accepts rpcClientId instead of callback
For example, rewrite
```
const connection = new BrowserRuntimeConnection({ port })
aeSdk.addRpcClient(connection)
aeSdk.shareWalletInfo(port.postMessage.bind(port))
```
to
```
const connection = new BrowserRuntimeConnection({ port })
const rpcClientId = aeSdk.addRpcClient(connection)
aeSdk.shareWalletInfo(rpcClientId)
```
  • Loading branch information
davidyuk committed May 28, 2022
1 parent 4b41b89 commit 9e97a1a
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 68 deletions.
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
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
2 changes: 1 addition & 1 deletion src/utils/aepp-wallet-communication/rpc/aepp-rpc.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export default AccountResolver.compose({
async disconnectWallet (sendDisconnect = true) {
this._ensureConnected()
if (sendDisconnect) {
this.rpcClient.sendMessage({ method: METHODS.closeConnection, params: { reason: 'bye' } }, true)
this.rpcClient.notify(METHODS.closeConnection, { reason: 'bye' })
}
this.rpcClient.disconnect()
this.rpcClient = null
Expand Down
19 changes: 12 additions & 7 deletions src/utils/aepp-wallet-communication/rpc/rpc-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export default stampit({
} catch (error) {
response.error = error instanceof RpcError ? error : new RpcInternalError()
}
if (response.id) this.sendMessage(response, true)
if (response.id) this._sendMessage(response, true)
}

const disconnect = (aepp, connection) => {
Expand Down Expand Up @@ -96,7 +96,7 @@ export default stampit({
}
},
methods: {
sendMessage ({ id, method, params, result, error }, isNotificationOrResponse = false) {
_sendMessage ({ id, method, params, result, error }, isNotificationOrResponse = false) {
if (!isNotificationOrResponse) this._messageId += 1
id = isNotificationOrResponse ? (id ?? null) : this._messageId
const msgData = params
Expand Down Expand Up @@ -185,10 +185,7 @@ export default stampit({
*/
setAccounts (accounts, { forceNotification } = {}) {
this.accounts = accounts
if (!forceNotification) {
// Sent notification about account updates
this.sendMessage({ method: METHODS.updateAddress, params: this.accounts }, true)
}
if (!forceNotification) this.notify(METHODS.updateAddress, this.accounts)
},
/**
* Update subscription
Expand Down Expand Up @@ -218,14 +215,22 @@ export default stampit({
* @return {Promise} Promise which will be resolved after receiving response message
*/
request (name, params) {
const msgId = this.sendMessage({ method: name, params })
const msgId = this._sendMessage({ method: name, params })
if (this.callbacks[msgId] != null) {
throw new DuplicateCallbackError()
}
return new Promise((resolve, reject) => {
this.callbacks[msgId] = { resolve, reject }
})
},
/**
* Make a notification
* @param {String} name Method name
* @param {Object} params Method params
*/
notify (name, params) {
this._sendMessage({ method: name, params }, true)
},
/**
* Process response message
* @function processResponse
Expand Down
21 changes: 7 additions & 14 deletions src/utils/aepp-wallet-communication/rpc/wallet-rpc.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,13 +226,10 @@ export default Ae.compose(AccountMultiple, {
Object.values(this.rpcClients)
.filter(client => client.isConnected())
.forEach(client => {
client.sendMessage({
method: METHODS.updateNetwork,
params: {
networkId: this.getNetworkId(),
...client.info.status === RPC_STATUS.NODE_BINDED && { node: this.selectedNode }
}
}, true)
client.notify(METHODS.updateNetwork, {
networkId: this.getNetworkId(),
...client.info.status === RPC_STATUS.NODE_BINDED && { node: this.selectedNode }
})
})
}
},
Expand Down Expand Up @@ -294,15 +291,11 @@ export default Ae.compose(AccountMultiple, {
* @function shareWalletInfo
* @instance
* @rtype (postFn: Function) => void
* @param {Function} postFn Send message function like `(msg) => void`
* @param {Function} clientId ID of RPC client send message to
* @return {void}
*/
shareWalletInfo (postFn) {
postFn({
jsonrpc: '2.0',
method: METHODS.readyToConnect,
params: this.getWalletInfo()
})
shareWalletInfo (clientId) {
this.rpcClients[clientId].notify(METHODS.readyToConnect, this.getWalletInfo())
},
/**
* Get Wallet info object
Expand Down
47 changes: 17 additions & 30 deletions test/integration/rpc.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,7 @@ describe('Aepp<->Wallet', function () {
onSign () {},
onAskAccounts () {},
onMessageSign () {},
onDisconnect () {
this.shareWalletInfo(
connectionFromWalletToAepp.sendMessage.bind(connectionFromWalletToAepp)
)
}
onDisconnect () {}
})
aepp = await RpcAepp({
name: 'AEPP',
Expand Down Expand Up @@ -101,10 +97,8 @@ describe('Aepp<->Wallet', function () {
})
})

wallet.addRpcClient(connectionFromWalletToAepp)
await wallet.shareWalletInfo(
connectionFromWalletToAepp.sendMessage.bind(connectionFromWalletToAepp)
)
const clientId = wallet.addRpcClient(connectionFromWalletToAepp)
await wallet.shareWalletInfo(clientId)
const is = await isReceived
is.should.be.equal(true)
})
Expand Down Expand Up @@ -404,23 +398,20 @@ describe('Aepp<->Wallet', function () {
})

it('Disconnect from wallet', async () => {
const received = await new Promise((resolve) => {
let received = false
wallet.onDisconnect = (msg, from) => {
msg.reason.should.be.equal('bye')
from.info.status.should.be.equal('DISCONNECTED')
if (received) resolve(true)
received = true
}
aepp.onDisconnect = () => {
if (received) resolve(true)
received = true
}
connectionFromWalletToAepp.sendMessage({
method: METHODS.closeConnection, params: { reason: 'bye' }, jsonrpc: '2.0'
})
const walletDisconnect = new Promise((resolve) => {
wallet.onDisconnect = (...args) => resolve(args)
})
received.should.be.equal(true)
const aeppDisconnect = new Promise((resolve) => {
aepp.onDisconnect = (...args) => resolve(args)
})
connectionFromWalletToAepp.sendMessage({
method: METHODS.closeConnection, params: { reason: 'bye' }, jsonrpc: '2.0'
})
const [[walletMessage, rpcClient], [aeppMessage]] =
await Promise.all([walletDisconnect, aeppDisconnect])
walletMessage.reason.should.be.equal('bye')
rpcClient.info.status.should.be.equal('DISCONNECTED')
aeppMessage.reason.should.be.equal('bye')
})

it('Remove rpc client', async () => {
Expand Down Expand Up @@ -486,11 +477,7 @@ describe('Aepp<->Wallet', function () {
onSign () {},
onAskAccounts () {},
onMessageSign () {},
onDisconnect () {
this.shareWalletInfo(
connectionFromWalletToAepp.sendMessage.bind(connectionFromWalletToAepp)
)
}
onDisconnect () {}
})
aepp = await RpcAepp({
name: 'AEPP',
Expand Down

0 comments on commit 9e97a1a

Please sign in to comment.