Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: initialize viem package #565

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions packages/sdk-viem/src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export type ArbitrumParentWalletActions = {
) => Promise<CrossChainTransactionStatus>
}

async function prepareDepositEthTransaction(
export async function prepareDepositEthTransaction(
client: PublicClient,
{ amount, account }: PrepareDepositEthParameters
): Promise<TransactionRequest> {
Expand All @@ -84,13 +84,13 @@ async function prepareDepositEthTransaction(
})

return {
to: request.txRequest.to as `0x${string}`,
to: request.txRequest.to as Address,
value: BigNumber.from(request.txRequest.value).toBigInt(),
data: request.txRequest.data as `0x${string}`,
data: request.txRequest.data as Address,
}
}

async function waitForCrossChainTransaction(
export async function waitForCrossChainTransaction(
parentClient: PublicClient,
childClient: PublicClient,
{
Expand Down Expand Up @@ -150,7 +150,7 @@ async function waitForCrossChainTransaction(
throw new Error('No cross chain message found in transaction')
}

async function sendCrossChainTransaction(
export async function sendCrossChainTransaction(
parentClient: PublicClient,
childClient: PublicClient,
walletClient: WalletClient,
Expand All @@ -173,7 +173,7 @@ async function sendCrossChainTransaction(
})
}

async function depositEth(
export async function depositEth(
parentClient: PublicClient,
childClient: PublicClient,
walletClient: WalletClient,
Expand Down
6 changes: 2 additions & 4 deletions packages/sdk-viem/src/createArbitrumClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ import {
http,
} from 'viem'
import {
ArbitrumDepositActions,
ArbitrumParentWalletActions,
arbitrumParentClientActions,
arbitrumParentWalletActions,
} from './actions'

export type ArbitrumClients = {
parentPublicClient: PublicClient
childPublicClient: PublicClient & ArbitrumDepositActions
childPublicClient: PublicClient
chrstph-dvx marked this conversation as resolved.
Show resolved Hide resolved
parentWalletClient: WalletClient & ArbitrumParentWalletActions
childWalletClient?: WalletClient
}
Expand Down Expand Up @@ -44,7 +42,7 @@ export function createArbitrumClient({
const childPublicClient = createPublicClient({
chain: childChain,
transport: http(childRpcUrl || childChain.rpcUrls.default.http[0]),
}).extend(arbitrumParentClientActions())
})

const extendedParentWalletClient = parentWalletClient.extend(
arbitrumParentWalletActions(parentPublicClient, childPublicClient)
Expand Down
87 changes: 87 additions & 0 deletions packages/sdk-viem/tests/customFeeTokenTestHelpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { ethers } from 'ethers'
import {
Account,
formatUnits,
parseEther,
parseUnits,
type Chain,
type Hex,
type WalletClient,
} from 'viem'

import {
getParentCustomFeeTokenAllowance,
isArbitrumNetworkWithCustomFeeToken,
} from '@arbitrum/sdk/tests/integration/custom-fee-token/customFeeTokenTestHelpers'
import { EthBridger } from '@arbitrum/sdk/src'
import { getNativeTokenDecimals } from '@arbitrum/sdk/src/lib/utils/lib'
import {
testSetup as _testSetup,
config,
getLocalNetworksFromFile,
} from '@arbitrum/sdk/tests/testSetup'
import { StaticJsonRpcProvider } from '@ethersproject/providers'

const ethProvider = () => new StaticJsonRpcProvider(config.ethUrl)
const arbProvider = () => new StaticJsonRpcProvider(config.arbUrl)
const localNetworks = () => getLocalNetworksFromFile()

export async function getAmountInEnvironmentDecimals(
amount: string
): Promise<[bigint, number]> {
if (isArbitrumNetworkWithCustomFeeToken()) {
const tokenDecimals = await getNativeTokenDecimals({
parentProvider: ethProvider(),
childNetwork: localNetworks().l3Network!,
})
return [parseUnits(amount, tokenDecimals), tokenDecimals]
}
return [parseEther(amount), 18] // ETH decimals
}

export function normalizeBalanceDiffByDecimals(
balanceDiff: bigint,
tokenDecimals: number
): bigint {
// Convert to 18 decimals (ETH standard) for comparison
if (tokenDecimals === 18) return balanceDiff

// Convert to decimal string with proper precision
const formattedDiff = formatUnits(balanceDiff, 18)
// Parse back with target decimals
return parseUnits(formattedDiff, tokenDecimals)
}

export async function approveCustomFeeTokenWithViem({
parentAccount,
parentWalletClient,
chain,
}: {
parentAccount: { address: string }
parentWalletClient: WalletClient
chain: Chain
}) {
if (!isArbitrumNetworkWithCustomFeeToken()) return

const networks = localNetworks()
const inbox = networks.l3Network!.ethBridge.inbox

const currentAllowance = await getParentCustomFeeTokenAllowance(
parentAccount.address,
inbox
)

// Only approve if allowance is insufficient
if (currentAllowance.lt(ethers.constants.MaxUint256)) {
const ethBridger = await EthBridger.fromProvider(arbProvider())
const approveRequest = ethBridger.getApproveGasTokenRequest()
await parentWalletClient.sendTransaction({
to: approveRequest.to as Hex,
data: approveRequest.data as Hex,
account: parentAccount as Account,
chain,
value: BigInt(0),
kzg: undefined,
})
}
}
73 changes: 16 additions & 57 deletions packages/sdk-viem/tests/deposit.test.ts
Original file line number Diff line number Diff line change
@@ -1,88 +1,65 @@
import { registerCustomArbitrumNetwork } from '@arbitrum/sdk'
import {
approveCustomFeeTokenWithViem,
approveParentCustomFeeToken,
fundParentCustomFeeToken,
getAmountInEnvironmentDecimals,
isArbitrumNetworkWithCustomFeeToken,
normalizeBalanceDiffByDecimals,
} from '@arbitrum/sdk/tests/integration/custom-fee-token/customFeeTokenTestHelpers'
import { fundParentSigner } from '@arbitrum/sdk/tests/integration/testHelpers'
import { config, testSetup } from '@arbitrum/sdk/tests/testSetup'
import { expect } from 'chai'
import { createWalletClient, http, parseEther, type Chain } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { createArbitrumClient } from '../src/createArbitrumClient'
import { parseEther } from 'viem'
import {
approveCustomFeeTokenWithViem,
getAmountInEnvironmentDecimals,
normalizeBalanceDiffByDecimals,
} from './customFeeTokenTestHelpers'
import { testSetup } from './testSetup'

describe('deposit', function () {
this.timeout(300000)

let localEthChain: Chain
let localArbChain: Chain
let setup: Awaited<ReturnType<typeof testSetup>>

before(async function () {
setup = await testSetup()
localEthChain = setup.localEthChain
localArbChain = setup.localArbChain
registerCustomArbitrumNetwork(setup.childChain)
})

beforeEach(async function () {
const parentAccount = privateKeyToAccount(`0x${config.ethKey}`)
await fundParentSigner(setup.parentSigner)
if (isArbitrumNetworkWithCustomFeeToken()) {
await fundParentCustomFeeToken(parentAccount.address)
await fundParentCustomFeeToken(setup.parentAccount.address)
await approveParentCustomFeeToken(setup.parentSigner)
}
})

it('deposits ETH from parent to child using deposit action', async function () {
const parentAccount = privateKeyToAccount(`0x${config.ethKey}`)
const [depositAmount, tokenDecimals] = await getAmountInEnvironmentDecimals(
'0.01'
)

const baseParentWalletClient = createWalletClient({
account: parentAccount,
chain: localEthChain,
transport: http(config.ethUrl),
})

const baseChildWalletClient = createWalletClient({
account: parentAccount,
chain: localArbChain,
transport: http(config.arbUrl),
})

const { childPublicClient, parentWalletClient } = createArbitrumClient({
parentChain: localEthChain,
childChain: localArbChain,
parentWalletClient: baseParentWalletClient,
childWalletClient: baseChildWalletClient,
})
const { childPublicClient, parentWalletClient } = setup

const initialBalance = await childPublicClient.getBalance({
address: parentAccount.address,
address: setup.parentAccount.address,
})

if (isArbitrumNetworkWithCustomFeeToken()) {
await approveCustomFeeTokenWithViem({
parentAccount,
parentAccount: setup.parentAccount,
parentWalletClient,
chain: localEthChain,
chain: setup.localEthChain,
})
}

const result = await parentWalletClient.depositEth({
amount: depositAmount,
account: parentAccount,
account: setup.parentAccount,
})

expect(result.status).to.equal('success')

const finalBalance = await childPublicClient.getBalance({
address: parentAccount.address,
address: setup.parentAccount.address,
})

const balanceDiff = finalBalance - initialBalance
Expand All @@ -95,32 +72,14 @@ describe('deposit', function () {
})

it('handles deposit failure gracefully', async function () {
const parentAccount = privateKeyToAccount(`0x${config.ethKey}`)
const depositAmount = parseEther('999999999')

const baseParentWalletClient = createWalletClient({
account: parentAccount,
chain: localEthChain,
transport: http(config.ethUrl),
})

const baseChildWalletClient = createWalletClient({
account: parentAccount,
chain: localArbChain,
transport: http(config.arbUrl),
})

const { parentWalletClient } = createArbitrumClient({
parentChain: localEthChain,
childChain: localArbChain,
parentWalletClient: baseParentWalletClient,
childWalletClient: baseChildWalletClient,
})
const { parentWalletClient } = setup

try {
await parentWalletClient.depositEth({
amount: depositAmount,
account: parentAccount,
account: setup.parentAccount,
})
expect.fail('Should have thrown an error')
} catch (error) {
Expand Down
96 changes: 96 additions & 0 deletions packages/sdk-viem/tests/testSetup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import {
config,
testSetup as sdkTestSetup,
} from '@arbitrum/sdk/tests/testSetup'
import { Address, Chain, createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import {
ArbitrumClients,
createArbitrumClient,
} from '../src/createArbitrumClient'

export type ViemTestSetup = {
localEthChain: Chain
localArbChain: Chain
parentAccount: ReturnType<typeof privateKeyToAccount>
childPublicClient: ArbitrumClients['childPublicClient']
parentWalletClient: ArbitrumClients['parentWalletClient']
childChain: Awaited<ReturnType<typeof sdkTestSetup>>['childChain']
parentSigner: Awaited<ReturnType<typeof sdkTestSetup>>['parentSigner']
}

function generateViemChain(
networkData: {
chainId: number
name: string
},
rpcUrl: string
): Chain {
return {
id: networkData.chainId,
name: networkData.name,
nativeCurrency: {
decimals: 18,
name: 'Ether',
symbol: 'ETH',
},
rpcUrls: {
default: { http: [rpcUrl] },
public: { http: [rpcUrl] },
},
} as const
}

export async function testSetup(): Promise<ViemTestSetup> {
const setup = await sdkTestSetup()

const parentPrivateKey = setup.seed._signingKey().privateKey as Address
const parentAccount = privateKeyToAccount(parentPrivateKey)

// Generate Viem chains using the network data we already have
const localEthChain = generateViemChain(
{
chainId: setup.childChain.parentChainId,
name: 'EthLocal',
},
config.ethUrl
)

const localArbChain = generateViemChain(
{
chainId: setup.childChain.chainId,
name: setup.childChain.name,
},
config.arbUrl
)

const baseParentWalletClient = createWalletClient({
account: parentAccount,
chain: localEthChain,
transport: http(config.ethUrl),
})

const baseChildWalletClient = createWalletClient({
account: parentAccount,
chain: localArbChain,
transport: http(config.arbUrl),
})

const { childPublicClient, parentWalletClient } = createArbitrumClient({
parentChain: localEthChain,
childChain: localArbChain,
parentWalletClient: baseParentWalletClient,
childWalletClient: baseChildWalletClient,
})

return {
...setup,
localEthChain,
localArbChain,
parentAccount,
childPublicClient,
parentWalletClient,
}
}

export { config }
Loading
Loading