Skip to content

Commit

Permalink
Merge pull request #328 from blocto/fix/batch-transactions-sendAsync
Browse files Browse the repository at this point in the history
Fix/batch transactions send async
  • Loading branch information
sanyu1225 authored Dec 6, 2023
2 parents 0db7fe7 + 00a3832 commit 6dc4771
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 38 deletions.
11 changes: 11 additions & 0 deletions .changeset/polite-wasps-clean.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@blocto/aptos-wallet-adapter-plugin': patch
'@blocto/connectkit-connector': patch
'@blocto/rainbowkit-connector': patch
'@blocto/web3-react-connector': patch
'@blocto/web3modal-connector': patch
'@blocto/wagmi-connector': patch
'@blocto/sdk': patch
---

sendAsync can send another requests
83 changes: 45 additions & 38 deletions packages/blocto-sdk/src/providers/ethereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export default class EthereumProvider
private get existedSDK() {
return (window as any).ethereum;
}

constructor({ chainId, rpc, walletServer, appId }: EthereumProviderConfig) {
super();
// setup chainId
Expand Down Expand Up @@ -228,38 +228,42 @@ export default class EthereumProvider
> = new Promise((resolve) => {
// web3 v1.x concat batched JSON-RPC requests to an array, handle it here
if (Array.isArray(payload)) {
// collect transactions and send batch with custom method
const transactions = payload
.filter((request) => request.method === 'eth_sendTransaction')
.map((request) => request.params?.[0]);

const idBase = Math.floor(Math.random() * 10000);
const { sendRequests, otherRequests } = payload.reduce(
(
acc: {
sendRequests: JsonRpcResponse[];
otherRequests: Promise<JsonRpcResponse>[];
},
request: JsonRpcRequest
) => {
if (request.method === 'eth_sendTransaction') {
acc.sendRequests.push(request.params?.[0]);
} else {
acc.otherRequests.push(
this.request(request as EIP1193RequestPayload)
);
}
return acc;
},
{ sendRequests: [], otherRequests: [] }
);

const batchedRequestPayload = {
// collect transactions and send batch with custom method
const batchReqPayload = {
method: 'blocto_sendBatchTransaction',
params: transactions,
params: sendRequests,
};
const batchReqPromise = this.request(batchReqPayload);

const batchResponsePromise = this.request(batchedRequestPayload);

const requests = payload.map(({ method, params }, index) =>
method === 'eth_sendTransaction'
? batchResponsePromise
: this.request({
id: idBase + index + 1,
jsonrpc: '2.0',
method,
params,
})
);
const idBase = Math.floor(Math.random() * 10000);

// resolve response when all request are executed
Promise.allSettled(requests)
.then((responses) =>
resolve(
Promise.allSettled([batchReqPromise, ...otherRequests])
.then((responses) => {
return resolve(
<Array<JsonRpcResponse>>responses.map((response, index) => {
return {
id: String(idBase + index + 1),
id: String(payload[index].id || idBase + index + 1),
jsonrpc: '2.0',
method: payload[index].method,
result:
Expand All @@ -272,8 +276,8 @@ export default class EthereumProvider
: undefined,
};
})
)
)
);
})
.catch((error) => {
throw ethErrors.rpc.internal(error?.message);
});
Expand All @@ -283,7 +287,7 @@ export default class EthereumProvider
});

// execute callback or return promise, depdends on callback arg given or not
if (callback) {
if (typeof callback === 'function') {
handleRequest
.then((data) => callback(null, <JsonRpcResponse>(<unknown>data)))
.catch((error) => callback(error));
Expand All @@ -308,11 +312,9 @@ export default class EthereumProvider

async request(payload: EIP1193RequestPayload): Promise<any> {
if (!payload?.method) throw ethErrors.rpc.invalidRequest();


const { blockchainName, switchableNetwork, sessionKey } =
await this.#getBloctoProperties();

if (this.existedSDK?.isBlocto) {
if (payload.method === 'wallet_switchEthereumChain') {
if (!payload?.params?.[0]?.chainId) {
Expand Down Expand Up @@ -349,6 +351,9 @@ export default class EthereumProvider
: 'Request failed';
throw ethErrors.rpc.internal(errorMessage);
}
if (typeof payload?.callback === 'function') {
payload.callback(null, response.result);
}
return response.result;
}
case 'wallet_switchEthereumChain': {
Expand Down Expand Up @@ -392,7 +397,9 @@ export default class EthereumProvider
break;
}
case 'eth_sign':
throw ethErrors.rpc.methodNotFound('Method Not Supported: eth_sign has been disabled');
throw ethErrors.rpc.methodNotFound(
'Method Not Supported: eth_sign has been disabled'
);
case 'eth_sendTransaction':
result = await this.handleSendTransaction(payload);
break;
Expand Down Expand Up @@ -553,7 +560,10 @@ export default class EthereumProvider
}
return new Promise((resolve, reject) =>
// add a small delay to make sure the network has been switched
setTimeout(() => this.existedSDK.enable().then(resolve).catch(reject), 10)
setTimeout(
() => this.existedSDK.enable().then(resolve).catch(reject),
10
)
);
}

Expand Down Expand Up @@ -879,7 +889,6 @@ export default class EthereumProvider
}

async handleDisconnect(): Promise<void> {

if (this.existedSDK?.isBlocto) {
return this.existedSDK.request({ method: 'wallet_disconnect' });
}
Expand Down Expand Up @@ -917,15 +926,13 @@ export default class EthereumProvider
}

override on(event: string, listener: (arg: any) => void): void {
if (this.existedSDK?.isBlocto)
this.existedSDK.on(event, listener);
if (this.existedSDK?.isBlocto) this.existedSDK.on(event, listener);

super.on(event, listener);
}

override removeListener(event: string, listener: (arg: any) => void): void {
if (this.existedSDK?.isBlocto)
this.existedSDK.off(event, listener);
if (this.existedSDK?.isBlocto) this.existedSDK.off(event, listener);

super.removeListener(event, listener);
}
Expand Down
1 change: 1 addition & 0 deletions packages/blocto-sdk/src/providers/types/ethereum.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export interface EIP1193RequestPayload {
jsonrpc?: string;
method: string;
params?: Array<any>;
callback?: JsonRpcCallback;
}

interface SwitchableNetwork {
Expand Down

0 comments on commit 6dc4771

Please sign in to comment.