@rango-dev/signer-evm 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/dist/signer.d.ts +3 -3
- package/dist/signer.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/signer.ts +72 -39
package/CHANGELOG.md
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var O=Object.defineProperty;var E=(n,e)=>O(n,"name",{value:e,configurable:!0});import{providers as I}from"ethers";import{RPCErrorCode as C,SignerError as R,SignerErrorCode as f}from"rango-types";import{getMessageFromCode as T}from"eth-rpc-errors";import{RPCErrorCode as p,SignerError as c,SignerErrorCode as d}from"rango-types";var u={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901}};var g=E(n=>{if(!n)return new c(d.SEND_TX_ERROR);if(c.isSignerError(n))return n;let e=Object.prototype.hasOwnProperty.call(n,"message"),i=Object.prototype.hasOwnProperty.call(n,"code");if(e&&i){let{message:s,code:r}=n;if("ACTION_REJECTED"===r||u.provider.userRejectedRequest===r)return new c(d.REJECTED_BY_USER,void 0,n,p.REJECTION,n);if(typeof r=="number"){if(Object.values(u.provider).includes(r)){let t=T(r);return new c(d.SEND_TX_ERROR,void 0,t,p.UNKNOWN_ERROR,n)}else if(Object.values(u.rpc).includes(r)){if(r===u.rpc.internal&&(s?.includes("underpriced")||s?.includes("replacement fee too low")))return new c(d.SEND_TX_ERROR,void 0,"Transaction is underpriced.",p.UNDER_PRICED,n);if(s?.includes("intrinsic gas too low")||s?.includes("out of gas"))return new c(d.SEND_TX_ERROR,void 0,"Gas limit is low.",p.OUT_OF_GAS,n);let t=T(r);return new c(d.SEND_TX_ERROR,void 0,t??n,p.UNKNOWN_ERROR,n)}}switch(r){case"INVALID_ARGUMENT":{let t=(n.reason||n.message)??n;return new c(d.SEND_TX_ERROR,void 0,t,p.UNKNOWN_ERROR,n)}}}return new c(d.SEND_TX_ERROR,void 0,n,p.UNKNOWN_ERROR,n)},"cleanEvmError");async function _(n,e){if(!n||!e)return;let i=parseInt(n);try{let s=`https://api.tenderly.co/api/v1/public-contract/${i}/tx/${e}`,r=await fetch(s,{method:"GET"});return r.ok?(await r.json())?.error_message:void 0}catch{return}}E(_,"getTenderlyError");var l=E(async n=>new Promise(e=>setTimeout(e,n)),"waitMs");var S=E(async(n,e,i,s)=>{let t=!1;return await Promise.race([(async()=>{await e.wait(s),t=!0})(),(async()=>{for(;!t;){if(await l(3e3),t)return null;try{if(!await n.getTransaction(i))return null}catch(o){return console.log({error:o}),null}}return null})()])},"waitWithMempoolCheck"),h=class n{static{E(this,"DefaultEvmSigner")}signer;provider;constructor(e){this.provider=new I.Web3Provider(e),this.signer=this.provider.getSigner()}static buildTx(e,i=!1){let r={};return e.from&&(r={...r,from:e.from}),e.to&&(r={...r,to:e.to}),e.data&&(r={...r,data:e.data}),e.value&&(r={...r,value:e.value}),e.nonce&&(r={...r,nonce:e.nonce}),e.gasLimit&&(r={...r,gasLimit:e.gasLimit}),!i&&e.maxFeePerGas&&e.maxPriorityFeePerGas?r={...r,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas}:e.gasPrice&&(r={...r,gasPrice:"0x"+parseInt(e.gasPrice).toString(16)}),r}async signMessage(e){try{return await this.signer.signMessage(e)}catch(i){throw new R(f.SIGN_TX_ERROR,void 0,i)}}async signAndSendTx(e,i,s){try{this.signer=this.provider.getSigner(e.from??void 0);let r=n.buildTx(e),t=await this.signer.getChainId(),o=await this.signer.getAddress();if(s&&t&&t!==parseInt(s))throw new R(f.UNEXPECTED_BEHAVIOUR,void 0,`Signer chainId: '${t}' doesn't match with required chainId: '${s}' for tx.`);if(o&&i&&o.toLowerCase()!==i.toLowerCase())throw new R(f.UNEXPECTED_BEHAVIOUR,void 0,`Signer address: '${o.toLowerCase()}' doesn't match with required address: '${i.toLowerCase()}' for tx.`);try{let a=await this.signer.sendTransaction(r);return{hash:a.hash,response:a}}catch(a){if(a?.message&&typeof a.message=="string"&&a.message.indexOf("EIP-1559")!==-1){console.log("retrying EIP-1559 error without v2 fields ...");let N=n.buildTx(e,!0),m=await this.signer.sendTransaction(N);return{hash:m.hash,response:m}}throw a}}catch(r){throw g(r)}}async wait(e,i,s,r){try{if(s)return await s?.wait(r),{hash:e};if(!this.provider)return{hash:e};if(this.signer=this.provider.getSigner(),!i)return{hash:e};let t=await this.signer.getChainId();if(!t||parseInt(i)!=t)return{hash:e};let o=await this.provider.getTransaction(e);if(!o)throw Error(`Transaction hash '${e}' not found in blockchain.`);return await S(this.provider,o,e,r),{hash:e}}catch(t){let o=t;if(o?.code==="TRANSACTION_REPLACED"&&o?.replacement)return{hash:o?.replacement?.hash,response:o?.replacement};if(o?.code==="CALL_EXCEPTION"){let a=await _(i,e);if(a)throw new R(f.TX_FAILED_IN_BLOCKCHAIN,"Trannsaction failed in blockchain",a,C.CALL_EXCEPTION,o);return{hash:e}}throw g(o)}}};export{h as DefaultEvmSigner,g as cleanEvmError,l as waitMs};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/signer.ts", "../src/helper.ts", "../src/types.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n TransactionRequest,\n TransactionResponse,\n} from '@ethersproject/abstract-provider';\nimport type { GenericSigner } from 'rango-types';\nimport { EvmTransaction } from 'rango-types/lib/api/main';\nimport { providers } from 'ethers';\nimport { cleanEvmError, getTenderlyError, waitMs } from './helper';\nimport {\n RPCErrorCode as RangoRPCErrorCode,\n SignerError,\n SignerErrorCode,\n} from 'rango-types';\nimport { RPCErrorCode } from './types';\n\ntype ProviderType = ConstructorParameters<typeof providers.Web3Provider>[0];\n\nconst waitWithMempoolCheck = async (\n provider: providers.Web3Provider,\n tx: TransactionResponse,\n txHash: string,\n confirmations?: number\n) => {\n let finished = false;\n return await Promise.race([\n (async () => {\n await tx.wait(confirmations);\n finished = true;\n })(),\n (async () => {\n while (!finished) {\n await waitMs(3_000);\n if (finished) return null;\n try {\n const mempoolTx = await provider.getTransaction(txHash);\n if (!mempoolTx) return null;\n } catch (error) {\n console.log({ error });\n return null;\n }\n }\n return null;\n })(),\n ]);\n};\n\nexport class DefaultEvmSigner implements GenericSigner<EvmTransaction> {\n private signer: providers.JsonRpcSigner;\n private provider: providers.Web3Provider;\n\n constructor(provider: ProviderType) {\n this.provider = new providers.Web3Provider(provider);\n this.signer = this.provider.getSigner();\n }\n\n async signMessage(msg: string): Promise<string> {\n try {\n return await this.signer.signMessage(msg);\n } catch (error) {\n throw new SignerError(SignerErrorCode.SIGN_TX_ERROR, undefined, error);\n }\n }\n\n async signAndSendTx(\n tx: EvmTransaction,\n address: string,\n chainId: string | null\n ): Promise<{ hash: string; response: TransactionResponse }> {\n try {\n this.signer = this.provider.getSigner(tx.from ?? undefined);\n\n const transaction = DefaultEvmSigner.buildTx(tx);\n\n const signerChainId = await this.signer.getChainId();\n const signerAddress = await this.signer.getAddress();\n if (!!chainId && !!signerChainId && signerChainId !== parseInt(chainId)) {\n throw new SignerError(\n SignerErrorCode.UNEXPECTED_BEHAVIOUR,\n undefined,\n `Signer chainId: '${signerChainId}' doesn't match with required chainId: '${chainId}' for tx.`\n );\n }\n if (\n !!signerAddress &&\n !!address &&\n signerAddress.toLowerCase() !== address.toLowerCase()\n ) {\n throw new SignerError(\n SignerErrorCode.UNEXPECTED_BEHAVIOUR,\n undefined,\n `Signer address: '${signerAddress.toLowerCase()}' doesn't match with required address: '${address.toLowerCase()}' for tx.`\n );\n }\n try {\n const response = await this.signer.sendTransaction(transaction);\n return { hash: response.hash, response };\n } catch (error: any) {\n // retrying EIP-1559 without v2 related fields\n if (\n !!error?.message &&\n typeof error.message === 'string' &&\n error.message.indexOf('EIP-1559') !== -1\n ) {\n console.log('retrying EIP-1559 error without v2 fields ...');\n const transaction = DefaultEvmSigner.buildTx(tx, true);\n const response = await this.signer.sendTransaction(transaction);\n return { hash: response.hash, response };\n } else {\n throw error;\n }\n }\n } catch (error) {\n throw cleanEvmError(error);\n }\n }\n\n async wait(\n txHash: string,\n chainId?: string,\n txResponse?: TransactionResponse,\n confirmations?: number\n ): Promise<{ hash: string; response?: TransactionResponse }> {\n try {\n // if we have transaction response, use that to wait\n // otherwise, try to get tx response from the wallet provider\n if (txResponse) {\n // if we use waitWithMempoolCheck here, we can't detect replaced tx anymore\n await txResponse?.wait(confirmations);\n return { hash: txHash };\n }\n\n // ignore wait if wallet not connected yet\n if (!this.provider) return { hash: txHash };\n this.signer = this.provider.getSigner();\n\n // don't proceed if signer chain changed or chain id is not specified\n // because if user change the wallet network, we receive null on getTransaction\n if (!chainId) return { hash: txHash };\n const signerChainId = await this.signer.getChainId();\n if (!signerChainId || parseInt(chainId) != signerChainId)\n return { hash: txHash };\n\n const tx = await this.provider.getTransaction(txHash);\n if (!tx)\n throw Error(`Transaction hash '${txHash}' not found in blockchain.`);\n\n await waitWithMempoolCheck(this.provider, tx, txHash, confirmations);\n return { hash: txHash };\n } catch (err) {\n const error = err as any; // TODO find a proper type\n if (\n error?.code === RPCErrorCode.TRANSACTION_REPLACED &&\n error?.replacement\n )\n return { hash: error?.replacement?.hash, response: error?.replacement };\n else if (error?.code === RPCErrorCode.CALL_EXCEPTION) {\n const tError = await getTenderlyError(chainId, txHash);\n if (!!tError) {\n throw new SignerError(\n SignerErrorCode.TX_FAILED_IN_BLOCKCHAIN,\n 'Trannsaction failed in blockchain',\n tError,\n RangoRPCErrorCode.CALL_EXCEPTION,\n error\n );\n } else {\n /**\n * In cases where the is no error returen from tenderly, we could ignore\n * the error and proceed with check status flow.\n * */\n return { hash: txHash };\n }\n }\n throw cleanEvmError(error);\n }\n }\n\n static buildTx(evmTx: EvmTransaction, disableV2 = false): TransactionRequest {\n let tx: TransactionRequest = {};\n if (evmTx.from) tx = { ...tx, from: evmTx.from };\n if (evmTx.to) tx = { ...tx, to: evmTx.to };\n if (evmTx.data) tx = { ...tx, data: evmTx.data };\n if (evmTx.value) tx = { ...tx, value: evmTx.value };\n if (evmTx.nonce) tx = { ...tx, nonce: evmTx.nonce };\n if (evmTx.gasLimit) tx = { ...tx, gasLimit: evmTx.gasLimit };\n if (evmTx.gasPrice)\n tx = {\n ...tx,\n gasPrice: '0x' + parseInt(evmTx.gasPrice).toString(16),\n };\n if (evmTx.maxFeePerGas && !disableV2)\n tx = { ...tx, maxFeePerGas: evmTx.maxFeePerGas };\n if (evmTx.maxPriorityFeePerGas && !disableV2)\n tx = { ...tx, maxPriorityFeePerGas: evmTx.maxPriorityFeePerGas };\n return tx;\n }\n}\n", "import type { SignerError as SignerErrorType } from 'rango-types';\n\nimport { getMessageFromCode } from 'eth-rpc-errors';\nimport {\n RPCErrorCode as RangoRPCErrorCode,\n SignerError,\n SignerErrorCode,\n} from 'rango-types';\n\nimport { MetamaskErrorCodes, RPCErrorCode, RPCErrorMessage } from './types';\n\nexport const cleanEvmError = (error: any): SignerErrorType => {\n if (!error) {\n return new SignerError(SignerErrorCode.SEND_TX_ERROR);\n }\n if (SignerError.isSignerError(error)) {\n return error;\n }\n const hasMessage = Object.prototype.hasOwnProperty.call(error, 'message');\n const hasCode = Object.prototype.hasOwnProperty.call(error, 'code');\n if (hasMessage && hasCode) {\n const { message: errorMessage, code: errorCode } = error;\n // rejection error\n if (\n RPCErrorCode.ACTION_REJECTED === errorCode ||\n MetamaskErrorCodes.provider.userRejectedRequest === errorCode\n ) {\n return new SignerError(\n SignerErrorCode.REJECTED_BY_USER,\n undefined,\n error,\n RangoRPCErrorCode.REJECTION,\n error\n );\n }\n if (typeof errorCode === 'number') {\n // provider errors\n if (Object.values(MetamaskErrorCodes.provider).includes(errorCode)) {\n const msg = getMessageFromCode(errorCode);\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n msg,\n RangoRPCErrorCode.UNKNOWN_ERROR,\n error\n );\n }\n // rpc errors\n else if (Object.values(MetamaskErrorCodes.rpc).includes(errorCode)) {\n // underpriced errors are sent as internal errors\n if (\n errorCode === MetamaskErrorCodes.rpc.internal &&\n (errorMessage?.includes(RPCErrorMessage.UNDER_PRICED) ||\n errorMessage?.includes(RPCErrorMessage.REPLACEMENT_FEE_TOO_LOW))\n ) {\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n 'Transaction is underpriced.',\n RangoRPCErrorCode.UNDER_PRICED,\n error\n );\n }\n // gas limit errors are sent as internal errors\n if (\n errorMessage?.includes(RPCErrorMessage.INTRINSIC_GAS_TOO_LOW) ||\n errorMessage?.includes(RPCErrorMessage.OUT_OF_GAS)\n ) {\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n 'Gas limit is low.',\n RangoRPCErrorCode.OUT_OF_GAS,\n error\n );\n }\n\n const msg = getMessageFromCode(errorCode);\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n msg ?? error,\n RangoRPCErrorCode.UNKNOWN_ERROR,\n error\n );\n }\n }\n switch (errorCode) {\n case RPCErrorCode.INVALID_ARGUMENT: {\n const msg = (error.reason || error.message) ?? error;\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n msg,\n RangoRPCErrorCode.UNKNOWN_ERROR,\n error\n );\n }\n }\n }\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n error,\n RangoRPCErrorCode.UNKNOWN_ERROR,\n error\n );\n};\n\ninterface TenderlyResponse {\n error_message: string;\n}\n\nexport async function getTenderlyError(\n chainId: string | undefined,\n txHash: string\n): Promise<string | undefined> {\n if (!chainId || !txHash) {\n return;\n }\n const chainIdInt = parseInt(chainId);\n try {\n const url = `https://api.tenderly.co/api/v1/public-contract/${chainIdInt}/tx/${txHash}`;\n const response = await fetch(url, {\n method: 'GET',\n });\n if (!response.ok) {\n return;\n }\n const data: TenderlyResponse = await response.json();\n return data?.error_message;\n } catch (error) {\n return;\n }\n}\n\nexport const waitMs = async (ms: number) =>\n new Promise((resolve) => setTimeout(resolve, ms));\n", "export const MetamaskErrorCodes = {\n rpc: {\n invalidInput: -32000,\n resourceNotFound: -32001,\n resourceUnavailable: -32002,\n transactionRejected: -32003,\n methodNotSupported: -32004,\n limitExceeded: -32005,\n parse: -32700,\n invalidRequest: -32600,\n methodNotFound: -32601,\n invalidParams: -32602,\n internal: -32603,\n },\n provider: {\n userRejectedRequest: 4001,\n unauthorized: 4100,\n unsupportedMethod: 4200,\n disconnected: 4900,\n chainDisconnected: 4901,\n },\n};\n\nexport enum RPCErrorCode {\n ACTION_REJECTED = 'ACTION_REJECTED',\n INVALID_ARGUMENT = 'INVALID_ARGUMENT',\n CALL_EXCEPTION = 'CALL_EXCEPTION',\n INSUFFICIENT_FUNDS = 'INSUFFICIENT_FUNDS',\n TRANSACTION_REPLACED = 'TRANSACTION_REPLACED',\n}\n\nexport enum RPCErrorMessage {\n UNDER_PRICED = 'underpriced',\n REPLACEMENT_FEE_TOO_LOW = 'replacement fee too low',\n INTRINSIC_GAS_TOO_LOW = 'intrinsic gas too low',\n OUT_OF_GAS = 'out of gas',\n INTERNAL_ERROR = 'Internal JSON-RPC error',\n}\n"],
|
|
5
|
-
"mappings": "+
|
|
6
|
-
"names": ["providers", "getMessageFromCode", "RangoRPCErrorCode", "SignerError", "SignerErrorCode", "MetamaskErrorCodes", "cleanEvmError", "__name", "error", "SignerError", "SignerErrorCode", "hasMessage", "hasCode", "errorMessage", "errorCode", "MetamaskErrorCodes", "RangoRPCErrorCode", "msg", "getMessageFromCode", "getTenderlyError", "chainId", "txHash", "chainIdInt", "url", "response", "waitMs", "ms", "resolve", "
|
|
4
|
+
"sourcesContent": ["import type {\n TransactionRequest,\n TransactionResponse,\n} from '@ethersproject/abstract-provider';\nimport type { GenericSigner } from 'rango-types';\nimport type { EvmTransaction } from 'rango-types/lib/api/main';\n\nimport { providers } from 'ethers';\nimport {\n RPCErrorCode as RangoRPCErrorCode,\n SignerError,\n SignerErrorCode,\n} from 'rango-types';\n\nimport { cleanEvmError, getTenderlyError, waitMs } from './helper';\nimport { RPCErrorCode } from './types';\n\ntype ProviderType = ConstructorParameters<typeof providers.Web3Provider>[0];\n\nconst waitWithMempoolCheck = async (\n provider: providers.Web3Provider,\n tx: TransactionResponse,\n txHash: string,\n confirmations?: number\n) => {\n const TIMEOUT = 3_000;\n let finished = false;\n return await Promise.race([\n (async () => {\n await tx.wait(confirmations);\n finished = true;\n })(),\n (async () => {\n while (!finished) {\n await waitMs(TIMEOUT);\n if (finished) {\n return null;\n }\n try {\n const mempoolTx = await provider.getTransaction(txHash);\n if (!mempoolTx) {\n return null;\n }\n } catch (error) {\n console.log({ error });\n return null;\n }\n }\n return null;\n })(),\n ]);\n};\n\nexport class DefaultEvmSigner implements GenericSigner<EvmTransaction> {\n private signer: providers.JsonRpcSigner;\n private provider: providers.Web3Provider;\n\n constructor(provider: ProviderType) {\n this.provider = new providers.Web3Provider(provider);\n this.signer = this.provider.getSigner();\n }\n\n static buildTx(evmTx: EvmTransaction, disableV2 = false): TransactionRequest {\n const TO_STRING_BASE = 16;\n let tx: TransactionRequest = {};\n if (evmTx.from) {\n tx = { ...tx, from: evmTx.from };\n }\n if (evmTx.to) {\n tx = { ...tx, to: evmTx.to };\n }\n if (evmTx.data) {\n tx = { ...tx, data: evmTx.data };\n }\n if (evmTx.value) {\n tx = { ...tx, value: evmTx.value };\n }\n if (evmTx.nonce) {\n tx = { ...tx, nonce: evmTx.nonce };\n }\n if (evmTx.gasLimit) {\n tx = { ...tx, gasLimit: evmTx.gasLimit };\n }\n if (!disableV2 && evmTx.maxFeePerGas && evmTx.maxPriorityFeePerGas) {\n tx = {\n ...tx,\n maxFeePerGas: evmTx.maxFeePerGas,\n maxPriorityFeePerGas: evmTx.maxPriorityFeePerGas,\n };\n } else if (evmTx.gasPrice) {\n tx = {\n ...tx,\n gasPrice: '0x' + parseInt(evmTx.gasPrice).toString(TO_STRING_BASE),\n };\n }\n return tx;\n }\n\n async signMessage(msg: string): Promise<string> {\n try {\n return await this.signer.signMessage(msg);\n } catch (error) {\n throw new SignerError(SignerErrorCode.SIGN_TX_ERROR, undefined, error);\n }\n }\n\n async signAndSendTx(\n tx: EvmTransaction,\n address: string,\n chainId: string | null\n ): Promise<{ hash: string; response: TransactionResponse }> {\n try {\n this.signer = this.provider.getSigner(tx.from ?? undefined);\n\n const transaction = DefaultEvmSigner.buildTx(tx);\n\n const signerChainId = await this.signer.getChainId();\n const signerAddress = await this.signer.getAddress();\n if (!!chainId && !!signerChainId && signerChainId !== parseInt(chainId)) {\n throw new SignerError(\n SignerErrorCode.UNEXPECTED_BEHAVIOUR,\n undefined,\n `Signer chainId: '${signerChainId}' doesn't match with required chainId: '${chainId}' for tx.`\n );\n }\n if (\n !!signerAddress &&\n !!address &&\n signerAddress.toLowerCase() !== address.toLowerCase()\n ) {\n throw new SignerError(\n SignerErrorCode.UNEXPECTED_BEHAVIOUR,\n undefined,\n `Signer address: '${signerAddress.toLowerCase()}' doesn't match with required address: '${address.toLowerCase()}' for tx.`\n );\n }\n try {\n const response = await this.signer.sendTransaction(transaction);\n return { hash: response.hash, response };\n } catch (error: any) {\n // retrying EIP-1559 without v2 related fields\n if (\n !!error?.message &&\n typeof error.message === 'string' &&\n error.message.indexOf('EIP-1559') !== -1\n ) {\n console.log('retrying EIP-1559 error without v2 fields ...');\n const transaction = DefaultEvmSigner.buildTx(tx, true);\n const response = await this.signer.sendTransaction(transaction);\n return { hash: response.hash, response };\n }\n throw error;\n }\n } catch (error) {\n throw cleanEvmError(error);\n }\n }\n\n async wait(\n txHash: string,\n chainId?: string,\n txResponse?: TransactionResponse,\n confirmations?: number\n ): Promise<{ hash: string; response?: TransactionResponse }> {\n try {\n /*\n * if we have transaction response, use that to wait\n * otherwise, try to get tx response from the wallet provider\n */\n if (txResponse) {\n // if we use waitWithMempoolCheck here, we can't detect replaced tx anymore\n await txResponse?.wait(confirmations);\n return { hash: txHash };\n }\n\n // ignore wait if wallet not connected yet\n if (!this.provider) {\n return { hash: txHash };\n }\n this.signer = this.provider.getSigner();\n\n /*\n * don't proceed if signer chain changed or chain id is not specified\n * because if user change the wallet network, we receive null on getTransaction\n */\n if (!chainId) {\n return { hash: txHash };\n }\n const signerChainId = await this.signer.getChainId();\n if (!signerChainId || parseInt(chainId) != signerChainId) {\n return { hash: txHash };\n }\n\n const tx = await this.provider.getTransaction(txHash);\n if (!tx) {\n throw Error(`Transaction hash '${txHash}' not found in blockchain.`);\n }\n\n await waitWithMempoolCheck(this.provider, tx, txHash, confirmations);\n return { hash: txHash };\n } catch (err) {\n const error = err as any; // TODO find a proper type\n if (\n error?.code === RPCErrorCode.TRANSACTION_REPLACED &&\n error?.replacement\n ) {\n return { hash: error?.replacement?.hash, response: error?.replacement };\n } else if (error?.code === RPCErrorCode.CALL_EXCEPTION) {\n const tError = await getTenderlyError(chainId, txHash);\n if (!!tError) {\n throw new SignerError(\n SignerErrorCode.TX_FAILED_IN_BLOCKCHAIN,\n 'Trannsaction failed in blockchain',\n tError,\n RangoRPCErrorCode.CALL_EXCEPTION,\n error\n );\n } else {\n /**\n * In cases where the is no error returen from tenderly, we could ignore\n * the error and proceed with check status flow.\n *\n */\n return { hash: txHash };\n }\n }\n throw cleanEvmError(error);\n }\n }\n}\n", "import type { SignerError as SignerErrorType } from 'rango-types';\n\nimport { getMessageFromCode } from 'eth-rpc-errors';\nimport {\n RPCErrorCode as RangoRPCErrorCode,\n SignerError,\n SignerErrorCode,\n} from 'rango-types';\n\nimport { MetamaskErrorCodes, RPCErrorCode, RPCErrorMessage } from './types';\n\nexport const cleanEvmError = (error: any): SignerErrorType => {\n if (!error) {\n return new SignerError(SignerErrorCode.SEND_TX_ERROR);\n }\n if (SignerError.isSignerError(error)) {\n return error;\n }\n const hasMessage = Object.prototype.hasOwnProperty.call(error, 'message');\n const hasCode = Object.prototype.hasOwnProperty.call(error, 'code');\n if (hasMessage && hasCode) {\n const { message: errorMessage, code: errorCode } = error;\n // rejection error\n if (\n RPCErrorCode.ACTION_REJECTED === errorCode ||\n MetamaskErrorCodes.provider.userRejectedRequest === errorCode\n ) {\n return new SignerError(\n SignerErrorCode.REJECTED_BY_USER,\n undefined,\n error,\n RangoRPCErrorCode.REJECTION,\n error\n );\n }\n if (typeof errorCode === 'number') {\n // provider errors\n if (Object.values(MetamaskErrorCodes.provider).includes(errorCode)) {\n const msg = getMessageFromCode(errorCode);\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n msg,\n RangoRPCErrorCode.UNKNOWN_ERROR,\n error\n );\n }\n // rpc errors\n else if (Object.values(MetamaskErrorCodes.rpc).includes(errorCode)) {\n // underpriced errors are sent as internal errors\n if (\n errorCode === MetamaskErrorCodes.rpc.internal &&\n (errorMessage?.includes(RPCErrorMessage.UNDER_PRICED) ||\n errorMessage?.includes(RPCErrorMessage.REPLACEMENT_FEE_TOO_LOW))\n ) {\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n 'Transaction is underpriced.',\n RangoRPCErrorCode.UNDER_PRICED,\n error\n );\n }\n // gas limit errors are sent as internal errors\n if (\n errorMessage?.includes(RPCErrorMessage.INTRINSIC_GAS_TOO_LOW) ||\n errorMessage?.includes(RPCErrorMessage.OUT_OF_GAS)\n ) {\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n 'Gas limit is low.',\n RangoRPCErrorCode.OUT_OF_GAS,\n error\n );\n }\n\n const msg = getMessageFromCode(errorCode);\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n msg ?? error,\n RangoRPCErrorCode.UNKNOWN_ERROR,\n error\n );\n }\n }\n switch (errorCode) {\n case RPCErrorCode.INVALID_ARGUMENT: {\n const msg = (error.reason || error.message) ?? error;\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n msg,\n RangoRPCErrorCode.UNKNOWN_ERROR,\n error\n );\n }\n }\n }\n return new SignerError(\n SignerErrorCode.SEND_TX_ERROR,\n undefined,\n error,\n RangoRPCErrorCode.UNKNOWN_ERROR,\n error\n );\n};\n\ninterface TenderlyResponse {\n error_message: string;\n}\n\nexport async function getTenderlyError(\n chainId: string | undefined,\n txHash: string\n): Promise<string | undefined> {\n if (!chainId || !txHash) {\n return;\n }\n const chainIdInt = parseInt(chainId);\n try {\n const url = `https://api.tenderly.co/api/v1/public-contract/${chainIdInt}/tx/${txHash}`;\n const response = await fetch(url, {\n method: 'GET',\n });\n if (!response.ok) {\n return;\n }\n const data: TenderlyResponse = await response.json();\n return data?.error_message;\n } catch (error) {\n return;\n }\n}\n\nexport const waitMs = async (ms: number) =>\n new Promise((resolve) => setTimeout(resolve, ms));\n", "export const MetamaskErrorCodes = {\n rpc: {\n invalidInput: -32000,\n resourceNotFound: -32001,\n resourceUnavailable: -32002,\n transactionRejected: -32003,\n methodNotSupported: -32004,\n limitExceeded: -32005,\n parse: -32700,\n invalidRequest: -32600,\n methodNotFound: -32601,\n invalidParams: -32602,\n internal: -32603,\n },\n provider: {\n userRejectedRequest: 4001,\n unauthorized: 4100,\n unsupportedMethod: 4200,\n disconnected: 4900,\n chainDisconnected: 4901,\n },\n};\n\nexport enum RPCErrorCode {\n ACTION_REJECTED = 'ACTION_REJECTED',\n INVALID_ARGUMENT = 'INVALID_ARGUMENT',\n CALL_EXCEPTION = 'CALL_EXCEPTION',\n INSUFFICIENT_FUNDS = 'INSUFFICIENT_FUNDS',\n TRANSACTION_REPLACED = 'TRANSACTION_REPLACED',\n}\n\nexport enum RPCErrorMessage {\n UNDER_PRICED = 'underpriced',\n REPLACEMENT_FEE_TOO_LOW = 'replacement fee too low',\n INTRINSIC_GAS_TOO_LOW = 'intrinsic gas too low',\n OUT_OF_GAS = 'out of gas',\n INTERNAL_ERROR = 'Internal JSON-RPC error',\n}\n"],
|
|
5
|
+
"mappings": "+EAOA,OAAS,aAAAA,MAAiB,SAC1B,OACE,gBAAgBC,EAChB,eAAAC,EACA,mBAAAC,MACK,cCVP,OAAS,sBAAAC,MAA0B,iBACnC,OACE,gBAAgBC,EAChB,eAAAC,EACA,mBAAAC,MACK,cCPA,IAAMC,EAAqB,CAChC,IAAK,CACH,aAAc,MACd,iBAAkB,OAClB,oBAAqB,OACrB,oBAAqB,OACrB,mBAAoB,OACpB,cAAe,OACf,MAAO,OACP,eAAgB,OAChB,eAAgB,OAChB,cAAe,OACf,SAAU,MACZ,EACA,SAAU,CACR,oBAAqB,KACrB,aAAc,KACd,kBAAmB,KACnB,aAAc,KACd,kBAAmB,IACrB,CACF,EDVO,IAAMC,EAAgBC,EAACC,GAAgC,CAC5D,GAAI,CAACA,EACH,OAAO,IAAIC,EAAYC,EAAgB,aAAa,EAEtD,GAAID,EAAY,cAAcD,CAAK,EACjC,OAAOA,EAET,IAAMG,EAAa,OAAO,UAAU,eAAe,KAAKH,EAAO,SAAS,EAClEI,EAAU,OAAO,UAAU,eAAe,KAAKJ,EAAO,MAAM,EAClE,GAAIG,GAAcC,EAAS,CACzB,GAAM,CAAE,QAASC,EAAc,KAAMC,CAAU,EAAIN,EAEnD,uBACmCM,GACjCC,EAAmB,SAAS,sBAAwBD,EAEpD,OAAO,IAAIL,EACTC,EAAgB,iBAChB,OACAF,EACAQ,EAAkB,UAClBR,CACF,EAEF,GAAI,OAAOM,GAAc,UAEvB,GAAI,OAAO,OAAOC,EAAmB,QAAQ,EAAE,SAASD,CAAS,EAAG,CAClE,IAAMG,EAAMC,EAAmBJ,CAAS,EACxC,OAAO,IAAIL,EACTC,EAAgB,cAChB,OACAO,EACAD,EAAkB,cAClBR,CACF,CACF,SAES,OAAO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AAa,EAC7B,CAAE,KAAMD,CAAO,EAIxB,GAAI,CAAC,KAAK,SACR,MAAO,CAAE,KAAMA,CAAO,EAQxB,GANA,KAAK,OAAS,KAAK,SAAS,UAAU,EAMlC,CAACc,EACH,MAAO,CAAE,KAAMd,CAAO,EAExB,IAAMgB,EAAgB,MAAM,KAAK,OAAO,WAAW,EACnD,GAAI,CAACA,GAAiB,SAASF,CAAO,GAAKE,EACzC,MAAO,CAAE,KAAMhB,CAAO,EAGxB,IAAMD,EAAK,MAAM,KAAK,SAAS,eAAeC,CAAM,EACpD,GAAI,CAACD,EACH,MAAM,MAAM,qBAAqBC,CAAM,4BAA4B,EAGrE,aAAMJ,EAAqB,KAAK,SAAUG,EAAIC,EAAQC,CAAa,EAC5D,CAAE,KAAMD,CAAO,CACxB,OAASqB,EAAK,CACZ,IAAMjB,EAAQiB,EACd,GACEjB,GAAO,+BACPA,GAAO,YAEP,MAAO,CAAE,KAAMA,GAAO,aAAa,KAAM,SAAUA,GAAO,WAAY,EACjE,GAAIA,GAAO,wBAAsC,CACtD,IAAMkB,EAAS,MAAMC,EAAiBT,EAASd,CAAM,EACrD,GAAMsB,EACJ,MAAM,IAAIX,EACRC,EAAgB,wBAChB,oCACAU,EACAE,EAAkB,eAClBpB,CACF,EAOA,MAAO,CAAE,KAAMJ,CAAO,CAE1B,CACA,MAAMmB,EAAcf,CAAK,CAC3B,CACF,CACF",
|
|
6
|
+
"names": ["providers", "RangoRPCErrorCode", "SignerError", "SignerErrorCode", "getMessageFromCode", "RangoRPCErrorCode", "SignerError", "SignerErrorCode", "MetamaskErrorCodes", "cleanEvmError", "__name", "error", "SignerError", "SignerErrorCode", "hasMessage", "hasCode", "errorMessage", "errorCode", "MetamaskErrorCodes", "RangoRPCErrorCode", "msg", "getMessageFromCode", "getTenderlyError", "chainId", "txHash", "chainIdInt", "url", "response", "waitMs", "ms", "resolve", "waitWithMempoolCheck", "__name", "provider", "tx", "txHash", "confirmations", "finished", "waitMs", "error", "DefaultEvmSigner", "_DefaultEvmSigner", "providers", "evmTx", "disableV2", "msg", "SignerError", "SignerErrorCode", "address", "chainId", "transaction", "signerChainId", "signerAddress", "response", "cleanEvmError", "txResponse", "err", "tError", "getTenderlyError", "RangoRPCErrorCode"]
|
|
7
7
|
}
|
package/dist/signer.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { TransactionRequest, TransactionResponse } from '@ethersproject/abstract-provider';
|
|
1
|
+
import type { TransactionRequest, TransactionResponse } from '@ethersproject/abstract-provider';
|
|
2
2
|
import type { GenericSigner } from 'rango-types';
|
|
3
|
-
import { EvmTransaction } from 'rango-types/lib/api/main';
|
|
3
|
+
import type { EvmTransaction } from 'rango-types/lib/api/main';
|
|
4
4
|
import { providers } from 'ethers';
|
|
5
5
|
type ProviderType = ConstructorParameters<typeof providers.Web3Provider>[0];
|
|
6
6
|
export declare class DefaultEvmSigner implements GenericSigner<EvmTransaction> {
|
|
7
7
|
private signer;
|
|
8
8
|
private provider;
|
|
9
9
|
constructor(provider: ProviderType);
|
|
10
|
+
static buildTx(evmTx: EvmTransaction, disableV2?: boolean): TransactionRequest;
|
|
10
11
|
signMessage(msg: string): Promise<string>;
|
|
11
12
|
signAndSendTx(tx: EvmTransaction, address: string, chainId: string | null): Promise<{
|
|
12
13
|
hash: string;
|
|
@@ -16,7 +17,6 @@ export declare class DefaultEvmSigner implements GenericSigner<EvmTransaction> {
|
|
|
16
17
|
hash: string;
|
|
17
18
|
response?: TransactionResponse;
|
|
18
19
|
}>;
|
|
19
|
-
static buildTx(evmTx: EvmTransaction, disableV2?: boolean): TransactionRequest;
|
|
20
20
|
}
|
|
21
21
|
export {};
|
|
22
22
|
//# sourceMappingURL=signer.d.ts.map
|
package/dist/signer.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signer.d.ts","sourceRoot":"","sources":["../src/signer.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"signer.d.ts","sourceRoot":"","sources":["../src/signer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,kBAAkB,EAClB,mBAAmB,EACpB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE/D,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAUnC,KAAK,YAAY,GAAG,qBAAqB,CAAC,OAAO,SAAS,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;AAoC5E,qBAAa,gBAAiB,YAAW,aAAa,CAAC,cAAc,CAAC;IACpE,OAAO,CAAC,MAAM,CAA0B;IACxC,OAAO,CAAC,QAAQ,CAAyB;gBAE7B,QAAQ,EAAE,YAAY;IAKlC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,cAAc,EAAE,SAAS,UAAQ,GAAG,kBAAkB;IAoCtE,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAQzC,aAAa,CACjB,EAAE,EAAE,cAAc,EAClB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,GAAG,IAAI,GACrB,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,mBAAmB,CAAA;KAAE,CAAC;IAgDrD,IAAI,CACR,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,MAAM,EAChB,UAAU,CAAC,EAAE,mBAAmB,EAChC,aAAa,CAAC,EAAE,MAAM,GACrB,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,mBAAmB,CAAA;KAAE,CAAC;CAkE7D"}
|
package/package.json
CHANGED
package/src/signer.ts
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type {
|
|
2
2
|
TransactionRequest,
|
|
3
3
|
TransactionResponse,
|
|
4
4
|
} from '@ethersproject/abstract-provider';
|
|
5
5
|
import type { GenericSigner } from 'rango-types';
|
|
6
|
-
import { EvmTransaction } from 'rango-types/lib/api/main';
|
|
6
|
+
import type { EvmTransaction } from 'rango-types/lib/api/main';
|
|
7
|
+
|
|
7
8
|
import { providers } from 'ethers';
|
|
8
|
-
import { cleanEvmError, getTenderlyError, waitMs } from './helper';
|
|
9
9
|
import {
|
|
10
10
|
RPCErrorCode as RangoRPCErrorCode,
|
|
11
11
|
SignerError,
|
|
12
12
|
SignerErrorCode,
|
|
13
13
|
} from 'rango-types';
|
|
14
|
+
|
|
15
|
+
import { cleanEvmError, getTenderlyError, waitMs } from './helper';
|
|
14
16
|
import { RPCErrorCode } from './types';
|
|
15
17
|
|
|
16
18
|
type ProviderType = ConstructorParameters<typeof providers.Web3Provider>[0];
|
|
@@ -21,6 +23,7 @@ const waitWithMempoolCheck = async (
|
|
|
21
23
|
txHash: string,
|
|
22
24
|
confirmations?: number
|
|
23
25
|
) => {
|
|
26
|
+
const TIMEOUT = 3_000;
|
|
24
27
|
let finished = false;
|
|
25
28
|
return await Promise.race([
|
|
26
29
|
(async () => {
|
|
@@ -29,11 +32,15 @@ const waitWithMempoolCheck = async (
|
|
|
29
32
|
})(),
|
|
30
33
|
(async () => {
|
|
31
34
|
while (!finished) {
|
|
32
|
-
await waitMs(
|
|
33
|
-
if (finished)
|
|
35
|
+
await waitMs(TIMEOUT);
|
|
36
|
+
if (finished) {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
34
39
|
try {
|
|
35
40
|
const mempoolTx = await provider.getTransaction(txHash);
|
|
36
|
-
if (!mempoolTx)
|
|
41
|
+
if (!mempoolTx) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
37
44
|
} catch (error) {
|
|
38
45
|
console.log({ error });
|
|
39
46
|
return null;
|
|
@@ -53,6 +60,42 @@ export class DefaultEvmSigner implements GenericSigner<EvmTransaction> {
|
|
|
53
60
|
this.signer = this.provider.getSigner();
|
|
54
61
|
}
|
|
55
62
|
|
|
63
|
+
static buildTx(evmTx: EvmTransaction, disableV2 = false): TransactionRequest {
|
|
64
|
+
const TO_STRING_BASE = 16;
|
|
65
|
+
let tx: TransactionRequest = {};
|
|
66
|
+
if (evmTx.from) {
|
|
67
|
+
tx = { ...tx, from: evmTx.from };
|
|
68
|
+
}
|
|
69
|
+
if (evmTx.to) {
|
|
70
|
+
tx = { ...tx, to: evmTx.to };
|
|
71
|
+
}
|
|
72
|
+
if (evmTx.data) {
|
|
73
|
+
tx = { ...tx, data: evmTx.data };
|
|
74
|
+
}
|
|
75
|
+
if (evmTx.value) {
|
|
76
|
+
tx = { ...tx, value: evmTx.value };
|
|
77
|
+
}
|
|
78
|
+
if (evmTx.nonce) {
|
|
79
|
+
tx = { ...tx, nonce: evmTx.nonce };
|
|
80
|
+
}
|
|
81
|
+
if (evmTx.gasLimit) {
|
|
82
|
+
tx = { ...tx, gasLimit: evmTx.gasLimit };
|
|
83
|
+
}
|
|
84
|
+
if (!disableV2 && evmTx.maxFeePerGas && evmTx.maxPriorityFeePerGas) {
|
|
85
|
+
tx = {
|
|
86
|
+
...tx,
|
|
87
|
+
maxFeePerGas: evmTx.maxFeePerGas,
|
|
88
|
+
maxPriorityFeePerGas: evmTx.maxPriorityFeePerGas,
|
|
89
|
+
};
|
|
90
|
+
} else if (evmTx.gasPrice) {
|
|
91
|
+
tx = {
|
|
92
|
+
...tx,
|
|
93
|
+
gasPrice: '0x' + parseInt(evmTx.gasPrice).toString(TO_STRING_BASE),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
return tx;
|
|
97
|
+
}
|
|
98
|
+
|
|
56
99
|
async signMessage(msg: string): Promise<string> {
|
|
57
100
|
try {
|
|
58
101
|
return await this.signer.signMessage(msg);
|
|
@@ -105,9 +148,8 @@ export class DefaultEvmSigner implements GenericSigner<EvmTransaction> {
|
|
|
105
148
|
const transaction = DefaultEvmSigner.buildTx(tx, true);
|
|
106
149
|
const response = await this.signer.sendTransaction(transaction);
|
|
107
150
|
return { hash: response.hash, response };
|
|
108
|
-
} else {
|
|
109
|
-
throw error;
|
|
110
151
|
}
|
|
152
|
+
throw error;
|
|
111
153
|
}
|
|
112
154
|
} catch (error) {
|
|
113
155
|
throw cleanEvmError(error);
|
|
@@ -121,8 +163,10 @@ export class DefaultEvmSigner implements GenericSigner<EvmTransaction> {
|
|
|
121
163
|
confirmations?: number
|
|
122
164
|
): Promise<{ hash: string; response?: TransactionResponse }> {
|
|
123
165
|
try {
|
|
124
|
-
|
|
125
|
-
|
|
166
|
+
/*
|
|
167
|
+
* if we have transaction response, use that to wait
|
|
168
|
+
* otherwise, try to get tx response from the wallet provider
|
|
169
|
+
*/
|
|
126
170
|
if (txResponse) {
|
|
127
171
|
// if we use waitWithMempoolCheck here, we can't detect replaced tx anymore
|
|
128
172
|
await txResponse?.wait(confirmations);
|
|
@@ -130,19 +174,27 @@ export class DefaultEvmSigner implements GenericSigner<EvmTransaction> {
|
|
|
130
174
|
}
|
|
131
175
|
|
|
132
176
|
// ignore wait if wallet not connected yet
|
|
133
|
-
if (!this.provider)
|
|
177
|
+
if (!this.provider) {
|
|
178
|
+
return { hash: txHash };
|
|
179
|
+
}
|
|
134
180
|
this.signer = this.provider.getSigner();
|
|
135
181
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
182
|
+
/*
|
|
183
|
+
* don't proceed if signer chain changed or chain id is not specified
|
|
184
|
+
* because if user change the wallet network, we receive null on getTransaction
|
|
185
|
+
*/
|
|
186
|
+
if (!chainId) {
|
|
187
|
+
return { hash: txHash };
|
|
188
|
+
}
|
|
139
189
|
const signerChainId = await this.signer.getChainId();
|
|
140
|
-
if (!signerChainId || parseInt(chainId) != signerChainId)
|
|
190
|
+
if (!signerChainId || parseInt(chainId) != signerChainId) {
|
|
141
191
|
return { hash: txHash };
|
|
192
|
+
}
|
|
142
193
|
|
|
143
194
|
const tx = await this.provider.getTransaction(txHash);
|
|
144
|
-
if (!tx)
|
|
195
|
+
if (!tx) {
|
|
145
196
|
throw Error(`Transaction hash '${txHash}' not found in blockchain.`);
|
|
197
|
+
}
|
|
146
198
|
|
|
147
199
|
await waitWithMempoolCheck(this.provider, tx, txHash, confirmations);
|
|
148
200
|
return { hash: txHash };
|
|
@@ -151,9 +203,9 @@ export class DefaultEvmSigner implements GenericSigner<EvmTransaction> {
|
|
|
151
203
|
if (
|
|
152
204
|
error?.code === RPCErrorCode.TRANSACTION_REPLACED &&
|
|
153
205
|
error?.replacement
|
|
154
|
-
)
|
|
206
|
+
) {
|
|
155
207
|
return { hash: error?.replacement?.hash, response: error?.replacement };
|
|
156
|
-
else if (error?.code === RPCErrorCode.CALL_EXCEPTION) {
|
|
208
|
+
} else if (error?.code === RPCErrorCode.CALL_EXCEPTION) {
|
|
157
209
|
const tError = await getTenderlyError(chainId, txHash);
|
|
158
210
|
if (!!tError) {
|
|
159
211
|
throw new SignerError(
|
|
@@ -167,31 +219,12 @@ export class DefaultEvmSigner implements GenericSigner<EvmTransaction> {
|
|
|
167
219
|
/**
|
|
168
220
|
* In cases where the is no error returen from tenderly, we could ignore
|
|
169
221
|
* the error and proceed with check status flow.
|
|
170
|
-
*
|
|
222
|
+
*
|
|
223
|
+
*/
|
|
171
224
|
return { hash: txHash };
|
|
172
225
|
}
|
|
173
226
|
}
|
|
174
227
|
throw cleanEvmError(error);
|
|
175
228
|
}
|
|
176
229
|
}
|
|
177
|
-
|
|
178
|
-
static buildTx(evmTx: EvmTransaction, disableV2 = false): TransactionRequest {
|
|
179
|
-
let tx: TransactionRequest = {};
|
|
180
|
-
if (evmTx.from) tx = { ...tx, from: evmTx.from };
|
|
181
|
-
if (evmTx.to) tx = { ...tx, to: evmTx.to };
|
|
182
|
-
if (evmTx.data) tx = { ...tx, data: evmTx.data };
|
|
183
|
-
if (evmTx.value) tx = { ...tx, value: evmTx.value };
|
|
184
|
-
if (evmTx.nonce) tx = { ...tx, nonce: evmTx.nonce };
|
|
185
|
-
if (evmTx.gasLimit) tx = { ...tx, gasLimit: evmTx.gasLimit };
|
|
186
|
-
if (evmTx.gasPrice)
|
|
187
|
-
tx = {
|
|
188
|
-
...tx,
|
|
189
|
-
gasPrice: '0x' + parseInt(evmTx.gasPrice).toString(16),
|
|
190
|
-
};
|
|
191
|
-
if (evmTx.maxFeePerGas && !disableV2)
|
|
192
|
-
tx = { ...tx, maxFeePerGas: evmTx.maxFeePerGas };
|
|
193
|
-
if (evmTx.maxPriorityFeePerGas && !disableV2)
|
|
194
|
-
tx = { ...tx, maxPriorityFeePerGas: evmTx.maxPriorityFeePerGas };
|
|
195
|
-
return tx;
|
|
196
|
-
}
|
|
197
230
|
}
|