Skip to content
This repository has been archived by the owner on Apr 11, 2023. It is now read-only.

Commit

Permalink
fix(chain-adapters): switch chain on contract calls (#1132)
Browse files Browse the repository at this point in the history
* fix: switch chain on contract calls

* fix: dev dep

* feat: @0xdef1cafe don't spank me, gotta do what you gotta do until we monorail

* feat: use raw.githack.com url instead of githubusercontent

* chore: package.json things

* fix: ci things

* vernacular: chainId -> ethNetwork

* feat: add Comment On Rails

* feat: explicit return type

* feat: add PartialRecord

* feat: more safu

* feat: rm useless assertion

* feat: more useless type narrowing removal

* feat: another useless type cast goes hasta la vista 👋

* fix: ci

* Revert "feat: another useless type cast goes hasta la vista 👋"

This reverts commit 9d090f1.

Co-authored-by: Apotheosis <[email protected]>
  • Loading branch information
gomesalexandre and 0xApotheosis authored Dec 22, 2022
1 parent 67b2f11 commit 81d8857
Show file tree
Hide file tree
Showing 6 changed files with 127 additions and 17 deletions.
8 changes: 4 additions & 4 deletions packages/chain-adapters/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,16 @@
},
"peerDependencies": {
"@shapeshiftoss/caip": "^8.0.0",
"@shapeshiftoss/hdwallet-core": "^1.36.0",
"@shapeshiftoss/hdwallet-native": "^1.36.0",
"@shapeshiftoss/hdwallet-core": "^1.41.0",
"@shapeshiftoss/hdwallet-native": "^1.41.0",
"@shapeshiftoss/types": "^8.1.0",
"@shapeshiftoss/unchained-client": "^10.0.1",
"bs58check": "^2.0.2"
},
"devDependencies": {
"@shapeshiftoss/caip": "^8.0.0",
"@shapeshiftoss/hdwallet-core": "^1.36.0",
"@shapeshiftoss/hdwallet-native": "^1.36.0",
"@shapeshiftoss/hdwallet-core": "^1.41.0",
"@shapeshiftoss/hdwallet-native": "^1.41.0",
"@shapeshiftoss/types": "^8.1.0",
"@shapeshiftoss/unchained-client": "^10.0.1",
"@types/bs58check": "^2.1.0",
Expand Down
51 changes: 46 additions & 5 deletions packages/chain-adapters/src/evm/EvmBaseAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from '@shapeshiftoss/hdwallet-core'
import { BIP44Params, KnownChainIds } from '@shapeshiftoss/types'
import * as unchained from '@shapeshiftoss/unchained-client'
import { utils } from 'ethers'
import WAValidator from 'multicoin-address-validator'
import { numberToHex } from 'web3-utils'

Expand Down Expand Up @@ -39,7 +40,7 @@ import {
} from '../utils'
import { bnOrZero } from '../utils/bignumber'
import { BuildCustomTxInput, Fees } from './types'
import { getErc20Data } from './utils'
import { getErc20Data, getGeneratedAssetData } from './utils'

export const evmChainIds = [KnownChainIds.EthereumMainnet, KnownChainIds.AvalancheMainnet] as const

Expand Down Expand Up @@ -125,10 +126,24 @@ export abstract class EvmBaseAdapter<T extends EvmChainId> implements IChainAdap
// If there is a mismatch between the current wallet's EVM chain ID and the adapter's chainId?
// Switch the chain on wallet before building/sending the Tx
if (supportsEthSwitchChain(wallet)) {
const walletEvmChainId = await (wallet as ETHWallet).ethGetChainId?.()
const adapterEvmChainId = fromChainId(this.chainId).chainReference
if (!bnOrZero(walletEvmChainId).isEqualTo(adapterEvmChainId)) {
await (wallet as ETHWallet).ethSwitchChain?.(bnOrZero(adapterEvmChainId).toNumber())
const assets = await getGeneratedAssetData()
const feeAsset = assets[this.getFeeAssetId()]

const walletEthNetwork = await wallet.ethGetChainId?.()
const adapterEthNetwork = Number(fromChainId(this.chainId).chainReference)

if (!bnOrZero(walletEthNetwork).isEqualTo(adapterEthNetwork)) {
await wallet.ethSwitchChain?.({
chainId: utils.hexValue(adapterEthNetwork),
chainName: this.getDisplayName(),
nativeCurrency: {
name: feeAsset.name,
symbol: feeAsset.symbol,
decimals: 18,
},
rpcUrls: [this.getRpcUrl()],
blockExplorerUrls: [feeAsset.explorer],
})
}
}
const { erc20ContractAddress, gasPrice, gasLimit, maxFeePerGas, maxPriorityFeePerGas } =
Expand Down Expand Up @@ -276,6 +291,32 @@ export abstract class EvmBaseAdapter<T extends EvmChainId> implements IChainAdap
async signAndBroadcastTransaction(signTxInput: SignTxInput<ETHSignTx>): Promise<string> {
try {
const { txToSign, wallet } = signTxInput
const assets = await getGeneratedAssetData()
const feeAsset = assets[this.getFeeAssetId()]
// If there is a mismatch between the current wallet's EVM chain ID and the adapter's chainId?
// Switch the chain on wallet before building/sending the Tx
if (supportsEthSwitchChain(wallet)) {
const walletEthNetwork = await wallet.ethGetChainId?.()
const adapterEthNetwork = Number(fromChainId(this.chainId).chainReference)

if (typeof walletEthNetwork !== 'number') {
throw new Error('Error getting wallet ethNetwork')
}

if (!(walletEthNetwork === adapterEthNetwork)) {
await (wallet as ETHWallet).ethSwitchChain?.({
chainId: utils.hexValue(adapterEthNetwork),
chainName: this.getDisplayName(),
nativeCurrency: {
name: feeAsset.name,
symbol: feeAsset.symbol,
decimals: 18,
},
rpcUrls: [this.getRpcUrl()],
blockExplorerUrls: [feeAsset.explorer],
})
}
}
const txHash = await (wallet as ETHWallet)?.ethSendTx?.(txToSign)

if (!txHash) throw new Error('Error signing & broadcasting tx')
Expand Down
33 changes: 33 additions & 0 deletions packages/chain-adapters/src/evm/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
import { Contract } from '@ethersproject/contracts'
import { AssetId, ChainId } from '@shapeshiftoss/caip'
import axios from 'axios'

import erc20Abi from './erc20Abi.json'

// TODO(gomes): copied from asset-service which we can't import because of something something circular deps
// remove me after we go Web on MonoRails
type Asset = {
assetId: AssetId
chainId: ChainId
description?: string
symbol: string
name: string
precision: number
color: string
icon: string
explorer: string
explorerTxLink: string
explorerAddressLink: string
}

export const getErc20Data = async (
to: string,
value: string,
Expand All @@ -12,3 +30,18 @@ export const getErc20Data = async (
const { data: callData } = await erc20Contract.populateTransaction.transfer(to, value)
return callData || ''
}

// TODO(gomes): can't use asset-service here because of circular deps, remove me after we go Mono on Rails
let _generatedAssetData: Record<AssetId, Asset> | undefined = undefined
export const getGeneratedAssetData = async (): Promise<Record<AssetId, Asset>> => {
if (_generatedAssetData?.length) return _generatedAssetData

const { data: maybeGeneratedAssetData } = await axios.get<Record<AssetId, Asset>>(
'https://raw.githack.com/shapeshift/lib/main/packages/asset-service/src/service/generatedAssetData.json',
)

if (!maybeGeneratedAssetData) return {}
_generatedAssetData = maybeGeneratedAssetData

return _generatedAssetData
}
4 changes: 2 additions & 2 deletions packages/swapper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@
"@shapeshiftoss/caip": "^8.0.0",
"@shapeshiftoss/chain-adapters": "^10.5.0",
"@shapeshiftoss/errors": "^1.1.2",
"@shapeshiftoss/hdwallet-core": "^1.36.0",
"@shapeshiftoss/hdwallet-core": "^1.41.0",
"@shapeshiftoss/types": "^8.1.0"
},
"devDependencies": {
"@shapeshiftoss/asset-service": "^8.0.1",
"@shapeshiftoss/caip": "^8.0.0",
"@shapeshiftoss/chain-adapters": "^10.5.0",
"@shapeshiftoss/errors": "^1.1.2",
"@shapeshiftoss/hdwallet-core": "^1.36.0",
"@shapeshiftoss/hdwallet-core": "^1.41.0",
"@shapeshiftoss/types": "^8.1.0",
"@types/readline-sync": "^1.4.4",
"readline-sync": "^1.4.10",
Expand Down
3 changes: 3 additions & 0 deletions packages/types/src/utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,6 @@ type UnionMerge<T> = Pick<UnionMapping<T>, keyof T> & Partial<UnionMapping<T>>
export type ChainSpecific<T, M> = UnionMerge<
T extends unknown ? (T extends keyof M ? { chainSpecific: M[T] } : undefined) : never
>

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type PartialRecord<K extends keyof any, V> = Partial<Record<K, V>>
45 changes: 39 additions & 6 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1321,6 +1321,13 @@
"@ethersproject/properties" "^5.6.0"
"@ethersproject/strings" "^5.6.1"

"@findeth/abi@^0.3.0":
version "0.3.1"
resolved "https://registry.yarnpkg.com/@findeth/abi/-/abi-0.3.1.tgz#fe9a25211bc0c840c8bc53f937fd9af7278b9dab"
integrity sha512-T9HUVEjEgM0MzVLY4gs52ffz5AlHeC3CSGFcEzL4ojKMVzMxa3na1GW/XCmunrhnWP2cDh4fE2MhqLxA0CHqTw==
dependencies:
keccak "^3.0.0"

"@fioprotocol/[email protected]":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@fioprotocol/fiojs/-/fiojs-1.0.1.tgz#81779437603741bc4ca1c76d119b64c4157a3874"
Expand Down Expand Up @@ -3131,7 +3138,18 @@
web-encoding "^1.1.0"
wif "^2.0.6"

"@shapeshiftoss/[email protected]", "@shapeshiftoss/hdwallet-core@^1.36.0":
"@shapeshiftoss/[email protected]", "@shapeshiftoss/hdwallet-core@^1.41.0":
version "1.41.0"
resolved "https://registry.yarnpkg.com/@shapeshiftoss/hdwallet-core/-/hdwallet-core-1.41.0.tgz#8230c7284f475c6f8deb268a0a51fc07e6a0fb33"
integrity sha512-4Ke+BvWZBfYx8SYTue1xWyJHAmHtF8oANVayuTW2v0PsSWNcdz+XHmgGN7FJb7r1Ob5W2oY16eSWaXhAHCiLPQ==
dependencies:
eip-712 "^1.0.0"
eventemitter2 "^5.0.1"
lodash "^4.17.21"
rxjs "^6.4.0"
type-assertions "^1.1.0"

"@shapeshiftoss/hdwallet-core@^1.36.0":
version "1.36.0"
resolved "https://registry.yarnpkg.com/@shapeshiftoss/hdwallet-core/-/hdwallet-core-1.36.0.tgz#268be9200445379c971575c1efa77f1fbf9751c4"
integrity sha512-roaKlMH9g2hti1ya6A74iZfIsLq7wL0d8ptYT9jLDEMYB3rSaxCvMsuX921CldiqwWQ+2tFnGpQGJogiMHQs+A==
Expand All @@ -3151,14 +3169,14 @@
rxjs "^6.4.0"
type-assertions "^1.1.0"

"@shapeshiftoss/hdwallet-native@^1.36.0":
version "1.36.0"
resolved "https://registry.yarnpkg.com/@shapeshiftoss/hdwallet-native/-/hdwallet-native-1.36.0.tgz#791e1ce1122341279d20241b413f568971974d61"
integrity sha512-q57whagmFWHZEnF3Nd8zJzGwsfxD21iLUMTNk8+fnbO2BMI8opzv8lTsOCNk1W29rMJ1LnIEGu+dAvdJ64f9pw==
"@shapeshiftoss/hdwallet-native@^1.41.0":
version "1.41.0"
resolved "https://registry.yarnpkg.com/@shapeshiftoss/hdwallet-native/-/hdwallet-native-1.41.0.tgz#3322d4c0998f82064fcab7a60329a9e407b6372b"
integrity sha512-0leYt99AvydCa1GFcufkFkjYw1eZhHPOKBNRkz42/bQTQZsBBBuIN42558iFEZxdpxj2bLCSuqqMx830XD/dBA==
dependencies:
"@shapeshiftoss/bitcoinjs-lib" "5.2.0-shapeshift.2"
"@shapeshiftoss/fiosdk" "1.2.1-shapeshift.6"
"@shapeshiftoss/hdwallet-core" "1.36.0"
"@shapeshiftoss/hdwallet-core" "1.41.0"
"@shapeshiftoss/proto-tx-builder" "^0.4.0"
"@zxing/text-encoding" "^0.9.0"
bchaddrjs "^0.4.9"
Expand All @@ -3167,6 +3185,7 @@
bip39 "^3.0.2"
bnb-javascript-sdk-nobroadcast "^2.16.14"
crypto-js "^4.0.0"
eip-712 "^1.0.0"
ethers "5.6.5"
eventemitter2 "^5.0.1"
funtypes "^3.0.1"
Expand Down Expand Up @@ -5989,6 +6008,15 @@ [email protected]:
resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d"
integrity sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==

eip-712@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/eip-712/-/eip-712-1.0.0.tgz#453b417a1801726f001c22896b46fb84ad445800"
integrity sha512-zVWGCUJQErhTpBH0mfYurP+t7wNdRizBq7PMAFj8M1Hq4/4QvKE7+FfXVcs7kL6b2ypbCnMgsimJQR1B2AfHpg==
dependencies:
"@findeth/abi" "^0.3.0"
"@noble/hashes" "^1.0.0"
superstruct "^0.15.3"

electron-to-chromium@^1.4.17:
version "1.4.38"
resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.38.tgz#10ea58d73d36b13e78d5024f3b74a352d3958d01"
Expand Down Expand Up @@ -12629,6 +12657,11 @@ strong-log-transformer@^2.1.0:
minimist "^1.2.0"
through "^2.3.4"

superstruct@^0.15.3:
version "0.15.5"
resolved "https://registry.yarnpkg.com/superstruct/-/superstruct-0.15.5.tgz#0f0a8d3ce31313f0d84c6096cd4fa1bfdedc9dab"
integrity sha512-4AOeU+P5UuE/4nOUkmcQdW5y7i9ndt1cQd/3iUe+LTz3RxESf/W/5lg4B74HbDMMv8PHnPnGCQFH45kBcrQYoQ==

supports-color@^5.3.0:
version "5.5.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f"
Expand Down

0 comments on commit 81d8857

Please sign in to comment.