diff --git a/example/index.tsx b/example/index.tsx index b52a0df5..bb0a07c7 100644 --- a/example/index.tsx +++ b/example/index.tsx @@ -1,116 +1,138 @@ -import 'react-app-polyfill/ie11'; -import 'regenerator-runtime/runtime'; -import * as React from 'react'; -import * as ReactDOM from 'react-dom'; -import { Magic } from 'magic-sdk'; -import { providers } from 'ethers'; +import "react-app-polyfill/ie11"; +import "regenerator-runtime/runtime"; +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import { Magic } from "magic-sdk"; +import { providers } from "ethers"; +import { ConnextSdk, ERC20Abi } from "@connext/vector-sdk"; +import { ConnextModal } from "@connext/vector-modal"; +const connextSdk = new ConnextSdk(); +const webProvider = new providers.Web3Provider((window as any).ethereum); // Test key defaults to "rinkeby", live key defaults to "mainnet" -import { ConnextModal } from '@connext/vector-modal'; +async function init() { + const network = await webProvider.getNetwork(); + console.log(network); + try { + await connextSdk.init({ + routerPublicIdentifier: "vector7tbbTxQp8ppEQUgPsbGiTrVdapLdU5dH7zTbVuXRf1M4CEBU9Q", // Router Public Identifier + loginProvider: webProvider, // Web3/JsonRPCProvider + senderChainProvider: "https://goerli.infura.io/v3/af2f28bdb95d40edb06226a46106f5f9", // Rpc Provider Link + senderAssetId: "0xbd69fC70FA1c3AED524Bb4E82Adc5fcCFFcD79Fa", // Asset/Token Address on Sender Chain + recipientChainProvider: "https://rpc-mumbai.matic.today", // Rpc Provider Link + recipientAssetId: "0xfe4F5145f6e09952a5ba9e956ED0C25e3Fa4c7F1", // Asset/Token Address on Recipient Chain + }); + } catch (e) { + const message = "Error initalizing"; + console.log(e, message); + throw e; + } +} -type LoginType = 'none' | 'metamask' | 'magic'; -const magic = new Magic('pk_test_D646A81EA4676AB2', { - network: 'rinkeby', // Supports "rinkeby", "ropsten", "kovan" +type LoginType = "none" | "metamask" | "magic"; +const magic = new Magic("pk_test_D646A81EA4676AB2", { + network: "rinkeby", // Supports "rinkeby", "ropsten", "kovan" }); function App() { const [showModal, setShowModal] = React.useState(false); - const [ - loginProvider, - _setLoginProvider, - ] = React.useState(); - const [loginType, setLoginType] = React.useState('none'); + const [loginProvider, _setLoginProvider] = React.useState(); + const [loginType, setLoginType] = React.useState("none"); const [transferAmount, setTransferAmount] = React.useState(); const setLoginProvider = async (loginType: LoginType) => { let provider: providers.Web3Provider | undefined; - if (loginType === 'metamask') { + if (loginType === "metamask") { if (!(window as any).ethereum) { - throw new Error('Web3 not available'); + throw new Error("Web3 not available"); } provider = (window as any).ethereum; - } else if (loginType === 'magic') { + } else if (loginType === "magic") { provider = magic.rpcProvider as any; } _setLoginProvider(provider); }; const handleLoginProvider = async () => { - if (loginType === 'metamask') { + if (loginType === "metamask") { const provider = new providers.Web3Provider(loginProvider as any); - const accounts = await provider.send('eth_requestAccounts', []); - console.log('accounts: ', accounts); - } else if (loginType === 'magic') { - await magic.auth.loginWithMagicLink({ email: 'rksethuram9@gmail.com' }); + const accounts = await provider.send("eth_requestAccounts", []); + console.log("accounts: ", accounts); + } else if (loginType === "magic") { + await magic.auth.loginWithMagicLink({ email: "rksethuram9@gmail.com" }); const provider = new providers.Web3Provider(loginProvider as any); const signer = provider.getSigner(); const address = await signer.getAddress(); - console.log('address: ', address); + console.log("address: ", address); } }; return ( <> -
{ - console.log('event: ', event.target); - setLoginType((event.target as any).value); - await setLoginProvider((event.target as any).value); - }} - > - Metamask - Magic - None +
+

Modal

+
{ + console.log("event: ", event.target); + setLoginType((event.target as any).value); + await setLoginProvider((event.target as any).value); + }} + > + Metamask + Magic + None +
+ setTransferAmount(event.target.value)} /> Transfer + Amount +
+ + setShowModal(false)} + onReady={(params) => console.log("MODAL IS READY =======>", params)} + onFinished={(params) => console.log("On finish ==>", params)} + // onSwap={(params) => { + // console.log('onSwap params: ', params); + // throw new Error(params); + // }} + transferAmount={transferAmount} + withdrawalAddress={"0x75e4DD0587663Fce5B2D9aF7fbED3AC54342d3dB"} + loginProvider={loginProvider} + injectedProvider={loginProvider} + // prod config + routerPublicIdentifier="vector7tbbTxQp8ppEQUgPsbGiTrVdapLdU5dH7zTbVuXRf1M4CEBU9Q" + depositAssetId={"0xbd69fC70FA1c3AED524Bb4E82Adc5fcCFFcD79Fa"} + depositChainProvider="https://goerli.infura.io/v3/af2f28bdb95d40edb06226a46106f5f9" + withdrawAssetId={"0xfe4F5145f6e09952a5ba9e956ED0C25e3Fa4c7F1"} + withdrawChainProvider="https://rpc-mumbai.matic.today" + // local config + // routerPublicIdentifier="vector8Uz1BdpA9hV5uTm6QUv5jj1PsUyCH8m8ciA94voCzsxVmrBRor" + // depositAssetId={'0x9FBDa871d559710256a2502A2517b794B482Db40'} + // depositChainProvider="http://localhost:8545" + // withdrawAssetId={'0x9FBDa871d559710256a2502A2517b794B482Db40'} + // withdrawChainProvider="http://localhost:8546" + /> +
+ +
+

SDK

+
- setTransferAmount(event.target.value)} - />{' '} - Transfer Amount -
- - setShowModal(false)} - onReady={(params) => console.log('MODAL IS READY =======>', params)} - onFinished={(params) => console.log('On finish ==>', params)} - // onSwap={(params) => { - // console.log('onSwap params: ', params); - // throw new Error(params); - // }} - transferAmount={transferAmount} - withdrawalAddress={'0x75e4DD0587663Fce5B2D9aF7fbED3AC54342d3dB'} - loginProvider={loginProvider} - injectedProvider={loginProvider} - // prod config - routerPublicIdentifier="vector7tbbTxQp8ppEQUgPsbGiTrVdapLdU5dH7zTbVuXRf1M4CEBU9Q" - depositAssetId={'0xbd69fC70FA1c3AED524Bb4E82Adc5fcCFFcD79Fa'} - depositChainProvider="https://goerli.infura.io/v3/af2f28bdb95d40edb06226a46106f5f9" - withdrawAssetId={'0xfe4F5145f6e09952a5ba9e956ED0C25e3Fa4c7F1'} - withdrawChainProvider="https://rpc-mumbai.matic.today" - // local config - // routerPublicIdentifier="vector8Uz1BdpA9hV5uTm6QUv5jj1PsUyCH8m8ciA94voCzsxVmrBRor" - // depositAssetId={'0x9FBDa871d559710256a2502A2517b794B482Db40'} - // depositChainProvider="http://localhost:8545" - // withdrawAssetId={'0x9FBDa871d559710256a2502A2517b794B482Db40'} - // withdrawChainProvider="http://localhost:8546" - /> ); } -ReactDOM.render(, document.getElementById('root')); +ReactDOM.render(, document.getElementById("root")); diff --git a/modules/sdk/src/constants/types.ts b/modules/sdk/src/constants/types.ts index df8168f5..572b46b1 100644 --- a/modules/sdk/src/constants/types.ts +++ b/modules/sdk/src/constants/types.ts @@ -20,19 +20,20 @@ export interface CHAIN_DETAIL { chainId: number; chainProvider: string; rpcProvider: providers.JsonRpcProvider; - assetName: string; - assetId: string; - assetDecimals: number; chainParams: AddEthereumChainParameter; } +export interface ASSET_DETAIL { + name: string; + assetId: string; + decimals: number; +} + export type SetupParamsSchema = { routerPublicIdentifier: string; // "vectorA876de..." loginProvider: any; senderChainProvider: string; - senderAssetId: string; recipientChainProvider: string; - recipientAssetId: string; senderChainId?: number; recipientChainId?: number; iframeSrcOverride?: string; @@ -40,6 +41,12 @@ export type SetupParamsSchema = { export type InitParamsSchema = SetupParamsSchema; +export type preTransferCheckParamsSchema = { + transferAmount: string; + senderAssetId: string; + recipientAssetId: string; +}; + export type CheckPendingTransferResponseSchema = { offChainSenderChainAssetBalanceBn: BigNumber; offChainRecipientChainAssetBalanceBn: BigNumber; @@ -48,6 +55,8 @@ export type CheckPendingTransferResponseSchema = { export type InitResponseSchema = CheckPendingTransferResponseSchema; export type EstimateFeeParamsSchema = { transferAmount: string | undefined; + senderAssetId: string; + recipientAssetId: string; isRecipientAssetInput?: boolean; userBalanceWei?: string; }; @@ -63,6 +72,8 @@ export type EstimateFeeResponseSchema = { export type DepositParamsSchema = { transferAmount: string; webProvider: providers.Web3Provider; + senderAssetId: string; + recipientAssetId: string; preTransferCheck?: boolean; // callback onDeposited?: (txHash: string) => void; @@ -70,6 +81,7 @@ export type DepositParamsSchema = { export type WithdrawParamsSchema = { recipientAddress: string; + recipientAssetId: string; onFinished?: (txHash: string, amountUi?: string, amountBn?: BigNumber) => void; withdrawalCallTo?: string; withdrawalCallData?: string; @@ -78,6 +90,8 @@ export type WithdrawParamsSchema = { export type TransferParamsSchema = { transferQuote?: TransferQuote; + senderAssetId: string; + recipientAssetId: string; // Callbacks onTransferred?: () => void; }; diff --git a/modules/sdk/src/service/index.ts b/modules/sdk/src/service/index.ts index 6a1c7c88..776e7f03 100644 --- a/modules/sdk/src/service/index.ts +++ b/modules/sdk/src/service/index.ts @@ -1,13 +1,15 @@ -import { EngineEvents, FullChannelState, ERC20Abi, TransferQuote } from "@connext/vector-types"; +import { EngineEvents, FullChannelState, ERC20Abi, TransferQuote, ChainInfo } from "@connext/vector-types"; import { BrowserNode } from "@connext/vector-browser-node"; -import { getBalanceForAssetId, getRandomBytes32 } from "@connext/vector-utils"; +import { getBalanceForAssetId, getRandomBytes32, getAssetDecimals, getChainInfo } from "@connext/vector-utils"; import { BigNumber, Contract, constants, utils } from "ethers"; import AwesomeDebouncePromise from "awesome-debounce-promise"; import { CHAIN_DETAIL, + ASSET_DETAIL, SetupParamsSchema, InitParamsSchema, EstimateFeeParamsSchema, + preTransferCheckParamsSchema, EstimateFeeResponseSchema, DepositParamsSchema, TransferParamsSchema, @@ -44,7 +46,9 @@ export class ConnextSdk { public senderChainChannel?: FullChannelState; public recipientChainChannel?: FullChannelState; public senderChain?: CHAIN_DETAIL; + public senderAsset?: ASSET_DETAIL; public recipientChain?: CHAIN_DETAIL; + public recipientAsset?: ASSET_DETAIL; public browserNode: BrowserNode | undefined; private evts?: EvtContainer; @@ -58,9 +62,7 @@ export class ConnextSdk { routerPublicIdentifier: params.routerPublicIdentifier, loginProvider: params.loginProvider, senderChainProvider: params.senderChainProvider, - senderAssetId: params.senderAssetId, recipientChainProvider: params.recipientChainProvider, - recipientAssetId: params.recipientAssetId, senderChainId: params.senderChainId, recipientChainId: params.recipientChainId, iframeSrcOverride: params.iframeSrcOverride, @@ -87,7 +89,7 @@ export class ConnextSdk { let senderChainInfo: CHAIN_DETAIL; try { - senderChainInfo = await getChain(params.senderChainId, params.senderChainProvider, params.senderAssetId); + senderChainInfo = await getChain(params.senderChainId, params.senderChainProvider); this.senderChain = senderChainInfo; } catch (e) { const message = "Failed to fetch sender chain info"; @@ -97,11 +99,7 @@ export class ConnextSdk { let recipientChainInfo: CHAIN_DETAIL; try { - recipientChainInfo = await getChain( - params.recipientChainId, - params.recipientChainProvider, - params.recipientAssetId, - ); + recipientChainInfo = await getChain(params.recipientChainId, params.recipientChainProvider); this.recipientChain = recipientChainInfo; } catch (e) { const message = "Failed to fetch receiver chain info"; @@ -180,24 +178,6 @@ export class ConnextSdk { const recipientChainChannelAddress = recipientChainChannel?.channelAddress!; this.recipientChainChannel = recipientChainChannel; this.recipientChainChannelAddress = recipientChainChannelAddress; - - // Verify router supports... - try { - const swap = await verifyAndGetRouterSupports( - _node, - senderChainInfo.chainId, - senderChainInfo.assetId, - recipientChainInfo.chainId, - recipientChainInfo.assetId, - recipientChainInfo.rpcProvider, - params.routerPublicIdentifier, - ); - this.swapDefinition = swap; - } catch (e) { - const message = "Error in verifyRouterSupports"; - console.log(e, message); - throw e; - } } async checkPendingTransfer(): Promise { @@ -266,37 +246,37 @@ export class ConnextSdk { channelAddress: this.recipientChainChannelAddress, }), ]); - const depositHashlock = depositActive.getValue().filter(t => Object.keys(t.transferState).includes("lockHash")); - const withdrawHashlock = withdrawActive.getValue().filter(t => Object.keys(t.transferState).includes("lockHash")); + const depositHashlock = depositActive.getValue().filter((t) => Object.keys(t.transferState).includes("lockHash")); + const withdrawHashlock = withdrawActive.getValue().filter((t) => Object.keys(t.transferState).includes("lockHash")); console.warn( "deposit active on init", depositHashlock.length, "ids:", - depositHashlock.map(t => t.transferId), + depositHashlock.map((t) => t.transferId), ); console.warn( "withdraw active on init", withdrawHashlock.length, "ids:", - withdrawHashlock.map(t => t.transferId), + withdrawHashlock.map((t) => t.transferId), ); // set a listener to check for transfers that may have been pushed after a refresh after the hanging transfers have already been canceled - this.evts!.CONDITIONAL_TRANSFER_CREATED.pipe(data => { + this.evts!.CONDITIONAL_TRANSFER_CREATED.pipe((data) => { return ( data.transfer.responderIdentifier === this.browserNode!.publicIdentifier && data.transfer.meta.routingId !== this.crossChainTransferId ); - }).attach(async data => { + }).attach(async (data) => { console.warn("Cancelling transfer thats not active"); const senderResolution = this.evts!.CONDITIONAL_TRANSFER_RESOLVED.pipe( - data => + (data) => data.transfer.meta.crossChainTransferId === this.crossChainTransferId && data.channelAddress === this.senderChainChannelAddress, ).waitFor(45_000); const receiverResolution = this.evts!.CONDITIONAL_TRANSFER_RESOLVED.pipe( - data => + (data) => data.transfer.meta.crossChainTransferId === this.crossChainTransferId && data.channelAddress === this.recipientChainChannelAddress, ).waitFor(45_000); @@ -370,7 +350,64 @@ export class ConnextSdk { } async estimateFees(params: EstimateFeeParamsSchema): Promise { - const { transferAmount: _transferAmount, isRecipientAssetInput, userBalanceWei } = params; + const { + transferAmount: _transferAmount, + senderAssetId: _senderAssetId, + recipientAssetId: _recipientAssetId, + isRecipientAssetInput, + userBalanceWei, + } = params; + + const senderAssetId = utils.getAddress(_senderAssetId); + const recipientAssetId = utils.getAddress(_recipientAssetId); + + if (!this.senderAsset && this.senderAsset!.assetId !== senderAssetId) { + // get decimals for deposit asset + const assetDecimals = await getAssetDecimals(senderAssetId, this.senderChain?.rpcProvider!); + const chain: ChainInfo = await getChainInfo(this.senderChain?.chainId!); + + const _senderAsset = { + name: chain.assetId[senderAssetId]?.symbol ?? "Token", + assetId: senderAssetId, + decimals: assetDecimals, + }; + + this.senderAsset = _senderAsset; + } + + if (!this.recipientAsset && this.recipientAsset!.assetId !== recipientAssetId) { + // get decimals for deposit asset + const assetDecimals = await getAssetDecimals(recipientAssetId, this.recipientChain?.rpcProvider!); + const chain: ChainInfo = await getChainInfo(this.recipientChain?.chainId!); + + const _recipientAsset = { + name: chain.assetId[recipientAssetId]?.symbol ?? "Token", + assetId: recipientAssetId, + decimals: assetDecimals, + }; + + this.recipientAsset = _recipientAsset; + } + + // Verify router supports... + if (!this.swapDefinition) { + try { + const swap = await verifyAndGetRouterSupports( + this.browserNode!, + this.senderChain?.chainId!, + this.senderAsset?.assetId!, + this.recipientChain?.chainId!, + this.recipientAsset?.assetId!, + this.recipientChain?.rpcProvider!, + this.routerPublicIdentifier, + ); + this.swapDefinition = swap; + } catch (e) { + const message = "Error in verifyRouterSupports"; + console.log(e, message); + throw e; + } + } const transferAmount = _transferAmount ? _transferAmount.trim() : undefined; let err: string | undefined = undefined; @@ -394,7 +431,7 @@ export class ConnextSdk { const transferAmountBn = BigNumber.from( utils.parseUnits( transferAmount, - isRecipientAssetInput ? this.recipientChain?.assetDecimals! : this.senderChain?.assetDecimals!, + isRecipientAssetInput ? this.recipientAsset?.decimals! : this.senderAsset?.decimals!, ), ); @@ -423,11 +460,11 @@ export class ConnextSdk { this.routerPublicIdentifier, transferAmountBn, this.senderChain?.chainId!, - this.senderChain?.assetId!, - this.senderChain?.assetDecimals!, + this.senderAsset?.assetId!, + this.senderAsset?.decimals!, this.recipientChain?.chainId!, - this.recipientChain?.assetId!, - this.recipientChain?.assetDecimals!, + this.recipientAsset?.assetId!, + this.recipientAsset?.decimals!, this.swapDefinition!, isRecipientAssetInput, ); @@ -445,7 +482,7 @@ export class ConnextSdk { }; } - totalFee = utils.formatUnits(feeBn, this.senderChain?.assetDecimals!); + totalFee = utils.formatUnits(feeBn, this.senderAsset?.decimals!); console.log("feeUi: ", totalFee); if (BigNumber.from(recipientAmountBn).lte(0)) { @@ -460,15 +497,15 @@ export class ConnextSdk { } if (isRecipientAssetInput) { - senderAmountUi = utils.formatUnits(senderAmountBn, this.senderChain?.assetDecimals!); + senderAmountUi = utils.formatUnits(senderAmountBn, this.senderAsset?.decimals!); console.log("senderUi: ", senderAmountUi); } else { - recipientAmountUi = utils.formatUnits(recipientAmountBn, this.recipientChain?.assetDecimals!); + recipientAmountUi = utils.formatUnits(recipientAmountBn, this.recipientAsset?.decimals!); console.log("receivedUi: ", recipientAmountUi); } if (userBalanceWei) { - const userBalanceBn = BigNumber.from(utils.parseUnits(userBalanceWei, this.senderChain?.assetDecimals!)); + const userBalanceBn = BigNumber.from(utils.parseUnits(userBalanceWei, this.senderAsset?.decimals!)); if (senderAmountBn.gt(userBalanceBn)) { err = "Transfer amount exceeds user balance"; return { @@ -493,15 +530,20 @@ export class ConnextSdk { }; } - async preTransferCheck(transferAmount: string) { + async preTransferCheck(params: preTransferCheckParamsSchema) { + const { transferAmount, senderAssetId: _senderAssetId, recipientAssetId: _recipientAssetId } = params; + + const senderAssetId = utils.getAddress(_senderAssetId); + const recipientAssetId = utils.getAddress(_recipientAssetId); + const senderAssetDecimals = await getAssetDecimals(senderAssetId, this.senderChain?.rpcProvider!); + const recipientAssetDecimals = await getAssetDecimals(recipientAssetId, this.recipientChain?.rpcProvider!); + if (!transferAmount) { const message = "Transfer Amount is undefined"; console.log(message); throw new Error(message); } - const transferAmountBn: BigNumber = BigNumber.from( - utils.parseUnits(transferAmount, this.senderChain?.assetDecimals!), - ); + const transferAmountBn: BigNumber = BigNumber.from(utils.parseUnits(transferAmount, senderAssetDecimals)); if (transferAmountBn.isZero()) { const message = "Transfer amount cannot be 0"; @@ -509,16 +551,36 @@ export class ConnextSdk { throw new Error(message); } + // Verify router supports... + if (!this.swapDefinition) { + try { + const swap = await verifyAndGetRouterSupports( + this.browserNode!, + this.senderChain?.chainId!, + senderAssetId, + this.recipientChain?.chainId!, + recipientAssetId, + this.recipientChain?.rpcProvider!, + this.routerPublicIdentifier, + ); + this.swapDefinition = swap; + } catch (e) { + const message = "Error in verifyRouterSupports"; + console.log(e, message); + throw e; + } + } + console.log("Verify Router Capacity"); try { await verifyRouterCapacityForTransfer( this.recipientChain?.rpcProvider!, - this.recipientChain?.assetId!, - this.recipientChain?.assetDecimals!, + recipientAssetId, + recipientAssetDecimals, this.recipientChainChannel!, transferAmountBn, this.swapDefinition!, - this.senderChain?.assetDecimals!, + senderAssetDecimals, ); } catch (e) { console.log(e); @@ -527,30 +589,41 @@ export class ConnextSdk { } async deposit(params: DepositParamsSchema) { - const { transferAmount, preTransferCheck = true, webProvider, onDeposited } = params; + const { + transferAmount, + senderAssetId: _senderAssetId, + recipientAssetId: _recipientAssetId, + preTransferCheck = true, + webProvider, + onDeposited, + } = params; + + const senderAssetId = utils.getAddress(_senderAssetId); + const recipientAssetId = utils.getAddress(_recipientAssetId); + const senderAssetDecimals = await getAssetDecimals(senderAssetId, this.senderChain?.rpcProvider!); if (preTransferCheck) { try { - await this.preTransferCheck(transferAmount); + await this.preTransferCheck({ transferAmount, senderAssetId, recipientAssetId }); } catch (e) { console.log("Error at preCheck", e); throw e; } } - const transferAmountBn = BigNumber.from(utils.parseUnits(transferAmount, this.senderChain?.assetDecimals!)); + const transferAmountBn = BigNumber.from(utils.parseUnits(transferAmount, senderAssetDecimals)); console.log(transferAmountBn); try { const signer = webProvider.getSigner(); const depositTx = - this.senderChain?.assetId! === constants.AddressZero + senderAssetId === constants.AddressZero ? await signer.sendTransaction({ to: this.senderChainChannelAddress!, value: transferAmountBn, }) - : await new Contract(this.senderChain?.assetId!, ERC20Abi, signer).transfer( + : await new Contract(senderAssetId, ERC20Abi, signer).transfer( this.senderChainChannelAddress!, transferAmountBn, ); @@ -558,7 +631,7 @@ export class ConnextSdk { const receipt = await depositTx.wait(); console.log("deposit mined:", receipt.transactionHash); - this.senderChain?.rpcProvider!.waitForTransaction(depositTx.hash, 2).then(receipt => { + this.senderChain?.rpcProvider!.waitForTransaction(depositTx.hash, 2).then((receipt) => { if (receipt.status === 0) { // tx reverted const message = "Transaction reverted onchain"; @@ -576,27 +649,30 @@ export class ConnextSdk { } async transfer(params: TransferParamsSchema) { - const { transferQuote } = params; + const { transferQuote, senderAssetId: _senderAssetId, recipientAssetId: _recipientAssetId } = params; + + const senderAssetId = utils.getAddress(_senderAssetId); + const recipientAssetId = utils.getAddress(_recipientAssetId); const crossChainTransferId = getRandomBytes32(); const preImage = getRandomBytes32(); this.crossChainTransferId = crossChainTransferId; - console.log(`Calling reconcileDeposit with ${this.senderChainChannelAddress!} and ${this.senderChain?.assetId!}`); - await reconcileDeposit(this.browserNode!, this.senderChainChannelAddress!, this.senderChain?.assetId!); + console.log(`Calling reconcileDeposit with ${this.senderChainChannelAddress!} and ${senderAssetId}`); + await reconcileDeposit(this.browserNode!, this.senderChainChannelAddress!, senderAssetId); try { console.log( - `Calling createFromAssetTransfer ${this.senderChain?.chainId!} ${this.senderChain?.assetId!} ${ + `Calling createFromAssetTransfer ${this.senderChain?.chainId!} ${senderAssetId} ${ this.recipientChain?.chainId - } ${this.recipientChain?.assetId} ${crossChainTransferId}`, + } ${recipientAssetId} ${crossChainTransferId}`, ); const transferDeets = await createFromAssetTransfer( this.browserNode!, this.senderChain?.chainId!, - this.senderChain?.assetId!, + senderAssetId, this.recipientChain?.chainId!, - this.recipientChain?.assetId!, + recipientAssetId, this.routerPublicIdentifier, crossChainTransferId, preImage, @@ -614,7 +690,7 @@ export class ConnextSdk { } // listen for a sender-side cancellation, if it happens, short-circuit and show cancellation - const senderCancel = this.evts![EngineEvents.CONDITIONAL_TRANSFER_RESOLVED].pipe(data => { + const senderCancel = this.evts![EngineEvents.CONDITIONAL_TRANSFER_RESOLVED].pipe((data) => { return ( data.transfer.meta?.routingId === crossChainTransferId && data.transfer.responderIdentifier === this.routerPublicIdentifier && @@ -622,7 +698,7 @@ export class ConnextSdk { ); }).waitFor(500_000); - const receiverCreate = this.evts![EngineEvents.CONDITIONAL_TRANSFER_CREATED].pipe(data => { + const receiverCreate = this.evts![EngineEvents.CONDITIONAL_TRANSFER_CREATED].pipe((data) => { return ( data.transfer.meta?.routingId === crossChainTransferId && data.transfer.initiatorIdentifier === this.routerPublicIdentifier @@ -645,7 +721,7 @@ export class ConnextSdk { throw e; } - const senderResolve = this.evts![EngineEvents.CONDITIONAL_TRANSFER_RESOLVED].pipe(data => { + const senderResolve = this.evts![EngineEvents.CONDITIONAL_TRANSFER_RESOLVED].pipe((data) => { return ( data.transfer.meta?.routingId === crossChainTransferId && data.transfer.responderIdentifier === this.routerPublicIdentifier @@ -674,7 +750,17 @@ export class ConnextSdk { } async withdraw(params: WithdrawParamsSchema) { - const { recipientAddress, onFinished, withdrawalCallTo, withdrawalCallData, generateCallData } = params; + const { + recipientAddress, + recipientAssetId: _recipientAssetId, + onFinished, + withdrawalCallTo, + withdrawalCallData, + generateCallData, + } = params; + + const recipientAssetId = utils.getAddress(_recipientAssetId); + const recipientAssetDecimals = await getAssetDecimals(recipientAssetId, this.recipientChain?.rpcProvider!); // now go to withdrawal screen let result; try { @@ -682,7 +768,7 @@ export class ConnextSdk { this.browserNode!, this.evts![EngineEvents.WITHDRAWAL_RESOLVED], this.recipientChain?.chainId!, - this.recipientChain?.assetId!, + recipientAssetId, recipientAddress, this.routerPublicIdentifier, withdrawalCallTo, @@ -696,8 +782,7 @@ export class ConnextSdk { // display tx hash through explorer -> handles by the event. console.log("crossChainTransfer: ", result); - const successWithdrawalUi = utils.formatUnits(result.withdrawalAmount, this.recipientChain?.assetDecimals!); - + const successWithdrawalUi = utils.formatUnits(result.withdrawalAmount, recipientAssetDecimals); console.log(successWithdrawalUi); if (onFinished) { @@ -705,7 +790,7 @@ export class ConnextSdk { } // check tx receipt for withdrawal tx - this.recipientChain?.rpcProvider.waitForTransaction(result.withdrawalTx).then(receipt => { + this.recipientChain?.rpcProvider.waitForTransaction(result.withdrawalTx).then((receipt) => { if (receipt.status === 0) { // tx reverted const message = "Transaction reverted onchain"; @@ -718,6 +803,8 @@ export class ConnextSdk { async crossChainSwap(params: CrossChainSwapParamsSchema) { const { recipientAddress, + senderAssetId: _senderAssetId, + recipientAssetId: _recipientAssetId, onFinished, transferQuote, withdrawalCallTo, @@ -725,8 +812,11 @@ export class ConnextSdk { generateCallData, } = params; + const senderAssetId = utils.getAddress(_senderAssetId); + const recipientAssetId = utils.getAddress(_recipientAssetId); + try { - await this.transfer({ transferQuote }); + await this.transfer({ transferQuote, senderAssetId, recipientAssetId }); } catch (e) { console.log("Error at Transfer", e); throw e; @@ -734,11 +824,12 @@ export class ConnextSdk { try { await this.withdraw({ - recipientAddress: recipientAddress, - onFinished: onFinished, - withdrawalCallTo: withdrawalCallTo, - withdrawalCallData: withdrawalCallData, - generateCallData: generateCallData, + recipientAddress, + recipientAssetId, + onFinished, + withdrawalCallTo, + withdrawalCallData, + generateCallData, }); } catch (e) { console.log("Error at withdraw", e); diff --git a/modules/sdk/src/utils/helpers.ts b/modules/sdk/src/utils/helpers.ts index a05b7c5d..bb9862ed 100644 --- a/modules/sdk/src/utils/helpers.ts +++ b/modules/sdk/src/utils/helpers.ts @@ -46,9 +46,9 @@ export const retryWithDelay = async (fn: () => Promise, retries = 5) throw error; }; -export const getChain = async (_chainId: number | undefined, chainProvider: string, _assetId: string) => { +export const getChain = async (_chainId: number | undefined, chainProvider: string) => { // Sender Chain Info - const assetId = utils.getAddress(_assetId); + let chainId = _chainId; if (!chainId) { try { @@ -61,12 +61,8 @@ export const getChain = async (_chainId: number | undefined, chainProvider: stri const rpcProvider = new providers.JsonRpcProvider(chainProvider, chainId); - // get decimals for deposit asset - const assetDecimals = await getAssetDecimals(assetId, rpcProvider); - const chain: ChainInfo = await getChainInfo(chainId); const chainName = chain.name; - const assetName = chain.assetId[assetId]?.symbol ?? "Token"; const chainParams: AddEthereumChainParameter = { chainId: utils.hexValue(chain.chainId), @@ -84,9 +80,6 @@ export const getChain = async (_chainId: number | undefined, chainProvider: stri chainId: chainId, chainProvider: chainProvider, rpcProvider: rpcProvider, - assetName: assetName, - assetId: assetId, - assetDecimals: assetDecimals, chainParams: chainParams, };