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

ethers v5 --> v6 #131

Closed
wants to merge 17 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,6 @@ playwright/.cache/
# IDE
.vscode
.swp

# Typechain
typechain
2 changes: 1 addition & 1 deletion examples/deployer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"@turnkey/ethers": "workspace:*",
"@turnkey/http": "workspace:*",
"dotenv": "^16.0.3",
"ethers": "^5.7.2",
"ethers": "^6.8.0",
"solc": "0.8.13"
}
}
21 changes: 12 additions & 9 deletions examples/deployer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,20 +35,21 @@ async function main() {
privateKeyId: process.env.PRIVATE_KEY_ID!,
});

// Connect it with a Provider (https://docs.ethers.org/v5/api/providers/)
// Connect it with a Provider (https://docs.ethers.org/v6/api/providers/)
const network = "goerli";
const provider = new ethers.providers.InfuraProvider(network);
const provider = new ethers.InfuraProvider(network);
const connectedSigner = turnkeySigner.connect(provider);

const chainId = await connectedSigner.getChainId();
const connectedNetwork = await turnkeySigner.provider!.getNetwork();
const chainId = connectedNetwork.chainId;
const address = await connectedSigner.getAddress();
const balance = await connectedSigner.getBalance();
const balance = await connectedSigner.provider!.getBalance(address);

print("Network:", `${network} (chain ID ${chainId})`);
print("Address:", address);
print("Balance:", `${ethers.utils.formatEther(balance)} Ether`);
print("Balance:", `${ethers.formatEther(balance)} Ether`);

if (balance.isZero()) {
if (balance === 0n) {
let warningMessage =
"The transaction won't be broadcasted because your account balance is zero.\n";
if (network === "goerli") {
Expand All @@ -70,15 +71,17 @@ async function main() {

// Deploy an instance of the contract
const contract = await factory.deploy();
const contractAddress = await contract.getAddress();
const transaction = await contract.deploymentTransaction();

// The address is available immediately, but the contract is NOT deployed yet
print("Contract address", contract.address);
print("Contract address", contractAddress);

await contract.deployTransaction.wait();
await contract.waitForDeployment();

print(
`Contract has been deployed:`,
`https://${network}.etherscan.io/tx/${contract.deployTransaction.hash}`
`https://${network}.etherscan.io/tx/${transaction?.hash}`
);
}

Expand Down
2 changes: 1 addition & 1 deletion examples/rebalancer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
"@turnkey/ethers": "workspace:*",
"@turnkey/http": "workspace:*",
"dotenv": "^16.0.3",
"ethers": "^5.7.2"
"ethers": "^6.8.0"
}
}
65 changes: 39 additions & 26 deletions examples/rebalancer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ dotenv.config({ path: path.resolve(process.cwd(), ".env.local") });

import { TurnkeyClient } from "@turnkey/http";
import { ApiKeyStamper } from "@turnkey/api-key-stamper";
import { ethers } from "ethers";
import type { FeeData } from "ethers";
import { findPrivateKeys, isKeyOfObject } from "./utils";
import {
createPrivateKey,
Expand Down Expand Up @@ -237,7 +237,7 @@ async function fundImpl() {
provider,
connectedSigner,
ethAddress.address,
ethers.BigNumber.from(120000000000000) // 0.00012 ETH
BigInt(120000000000000) // 0.00012 ETH
);
}
}
Expand Down Expand Up @@ -285,28 +285,34 @@ async function sweepImpl() {
for (const pk of shortTermStoragePrivateKeys!) {
const provider = getProvider();
const connectedSigner = getTurnkeySigner(provider, pk.privateKeyId);
const balance = await connectedSigner.getBalance();
const feeData = await connectedSigner.getFeeData();
const address = await connectedSigner.getAddress();

feeData.maxFeePerGas = feeData.maxFeePerGas!.mul(GAS_MULTIPLIER);
feeData.maxPriorityFeePerGas =
feeData.maxPriorityFeePerGas!.mul(GAS_MULTIPLIER);

const gasRequired = feeData
.maxFeePerGas!.add(feeData.maxPriorityFeePerGas!)
.mul(TRANSFER_GAS_LIMIT); // 21000 is the gas limit for a simple transfer

if (balance.lt(SWEEP_THRESHOLD)) {
const balance = await provider.getBalance(address);
const feeDataResults = await provider.getFeeData();
const newFeeData = {
maxFeePerGas: feeDataResults.maxFeePerGas! * BigInt(GAS_MULTIPLIER),
maxPriorityFeePerGas:
feeDataResults.maxPriorityFeePerGas! * BigInt(GAS_MULTIPLIER),
};

const feeData = {
...feeDataResults,
...newFeeData,
} as FeeData;

const gasRequired =
(feeData.maxFeePerGas! + feeData.maxPriorityFeePerGas!) *
BigInt(TRANSFER_GAS_LIMIT); // 21000 is the gas limit for a simple transfer

if (balance < BigInt(SWEEP_THRESHOLD)) {
console.log(
`Address ${address} has an insufficient balance for sweep. Moving on...`
);
continue;
}

const sweepAmount = balance.sub(gasRequired.mul(2)); // be relatively conservative with sweep amount to prevent overdraft
const sweepAmount = balance - gasRequired * 2n; // be relatively conservative with sweep amount to prevent overdraft

if (sweepAmount.lt(0)) {
if (sweepAmount < 0n) {
console.log(
`Address ${address} has an insufficient balance for sweep. Moving on...`
);
Expand Down Expand Up @@ -367,20 +373,27 @@ async function recycleImpl() {
);
}

const balance = await connectedSigner.getBalance();
const feeData = await connectedSigner.getFeeData();
const sourceAddress = await connectedSigner.getAddress();
const balance = await provider.getBalance(sourceAddress);
const feeDataResults = await provider.getFeeData();
const newFeeData = {
maxFeePerGas: feeDataResults.maxFeePerGas! * BigInt(GAS_MULTIPLIER),
maxPriorityFeePerGas:
feeDataResults.maxPriorityFeePerGas! * BigInt(GAS_MULTIPLIER),
};

feeData.maxFeePerGas = feeData.maxFeePerGas!.mul(GAS_MULTIPLIER);
feeData.maxPriorityFeePerGas =
feeData.maxPriorityFeePerGas!.mul(GAS_MULTIPLIER);
const feeData = {
...feeDataResults,
...newFeeData,
} as FeeData;

const gasRequired = feeData
.maxFeePerGas!.add(feeData.maxPriorityFeePerGas!)
.mul(TRANSFER_GAS_LIMIT); // 21000 is the gas limit for a simple transfer
const gasRequired =
(feeData.maxFeePerGas! + feeData.maxPriorityFeePerGas!) *
BigInt(TRANSFER_GAS_LIMIT); // 21000 is the gas limit for a simple transfer

const recycleAmount = balance.sub(gasRequired.mul(2)); // be relatively conservative with sweep amount to prevent overdraft
const recycleAmount = balance - gasRequired * 2n; // be relatively conservative with sweep amount to prevent overdraft

if (recycleAmount.lte(0)) {
if (recycleAmount <= 0n) {
console.log("Insufficient balance for recycle...");
return;
}
Expand Down
12 changes: 5 additions & 7 deletions examples/rebalancer/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,14 @@ const DEFAULT_ENV = Environment.SEPOLIA;
// Load environment variables from `.env.local`
dotenv.config({ path: path.resolve(process.cwd(), ".env.local") });

let provider = new ethers.providers.InfuraProvider(
let provider = new ethers.InfuraProvider(
DEFAULT_ENV,
process.env.INFURA_KEY || DEFAULT_INFURA_COMMUNITY_KEY
);

export function getProvider(
env = Environment.SEPOLIA
): ethers.providers.Provider {
export function getProvider(env = Environment.SEPOLIA): ethers.Provider {
if (env !== Environment.SEPOLIA) {
provider = new ethers.providers.InfuraProvider(
provider = new ethers.InfuraProvider(
env,
process.env.INFURA_KEY || DEFAULT_INFURA_COMMUNITY_KEY
);
Expand All @@ -31,9 +29,9 @@ export function getProvider(
}

// getTurnkeySigner returns a TurnkeySigner connected to the passed-in Provider
// (https://docs.ethers.org/v5/api/providers/)
// (https://docs.ethers.org/v6/api/providers/)
export function getTurnkeySigner(
provider: ethers.providers.Provider,
provider: ethers.Provider,
privateKeyId: string
): TurnkeySigner {
const turnkeyClient = new TurnkeyClient(
Expand Down
35 changes: 18 additions & 17 deletions examples/rebalancer/src/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { ethers } from "ethers";
import { toReadableAmount, print } from "./utils";

export async function broadcastTx(
provider: ethers.providers.Provider,
provider: ethers.Provider,
signedTx: string,
activityId: string
) {
const network = await provider.getNetwork();
const txHash = ethers.utils.keccak256(signedTx);
const txHash = ethers.keccak256(signedTx);

console.log(
[
Expand All @@ -20,12 +20,14 @@ export async function broadcastTx(
);

const transaction = await provider.getTransaction(txHash);
if (transaction?.confirmations > 0) {
const confirmations = await transaction!.confirmations();

if (confirmations > 0) {
console.log(`Transaction ${txHash} has already been broadcasted\n`);
return;
}

const { hash } = await provider.sendTransaction(signedTx);
const { hash } = await provider.broadcastTransaction(signedTx);

console.log(`Awaiting confirmation for transaction hash ${hash}...\n`);

Expand All @@ -38,20 +40,20 @@ export async function broadcastTx(
}

export async function sendEth(
provider: ethers.providers.Provider,
provider: ethers.Provider,
connectedSigner: ethers.Signer,
destinationAddress: string,
value: ethers.BigNumber,
precalculatedFeeData: ethers.providers.FeeData | undefined = undefined
value: ethers.BigNumberish,
precalculatedFeeData: ethers.FeeData | undefined = undefined
) {
const network = await provider.getNetwork();
const balance = await connectedSigner.getBalance();
const address = await connectedSigner.getAddress();
const network = await provider.getNetwork();
const balance = await provider.getBalance(address);

print("Address:", address);
print("Balance:", `${ethers.utils.formatEther(balance)} Ether`);
print("Balance:", `${ethers.formatEther(balance)} Ether`);

if (balance.isZero()) {
if (balance === 0n) {
let warningMessage =
"The transaction won't be broadcast because your account balance is zero.\n";
if (network.name === "sepolia") {
Expand All @@ -62,13 +64,12 @@ export async function sendEth(
throw new Error(warningMessage);
}

const feeData = precalculatedFeeData || (await connectedSigner.getFeeData());
const gasRequired = feeData
.maxFeePerGas!.add(feeData.maxPriorityFeePerGas!)
.mul(21000);
const totalCost = gasRequired.add(value);
const feeData = precalculatedFeeData || (await provider.getFeeData());
const gasRequired =
(feeData.maxFeePerGas! + feeData.maxPriorityFeePerGas!) * 21000n;
const totalCost = gasRequired + BigInt(value);

if (balance.lt(totalCost)) {
if (balance < totalCost) {
console.error(`Insufficient ETH balance of ${balance}. Needs ${totalCost}`);
}

Expand Down
8 changes: 4 additions & 4 deletions examples/rebalancer/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BigNumber, ethers } from "ethers";
import { BigNumberish, ethers } from "ethers";

// Environment
export enum Environment {
Expand Down Expand Up @@ -27,8 +27,8 @@ export function findPrivateKeys(organization: any, tagName: string) {
export function fromReadableAmount(
amount: number,
decimals: number
): BigNumber {
return ethers.utils.parseUnits(amount.toString(), decimals);
): BigNumberish {
return ethers.parseUnits(amount.toString(), decimals);
}

// toReadableAmount converts atomic amounts to whole amounts
Expand All @@ -37,7 +37,7 @@ export function toReadableAmount(
decimals: number,
maxDecimals = MAX_DECIMALS
): string {
return ethers.utils.formatUnits(rawAmount, decimals).slice(0, maxDecimals);
return ethers.formatUnits(rawAmount, decimals).slice(0, maxDecimals);
}

// isKeyOfObject checks if a key exists within an object
Expand Down
2 changes: 1 addition & 1 deletion examples/sweeper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"@turnkey/api-key-stamper": "workspace:*",
"@uniswap/sdk-core": "^3.1.1",
"dotenv": "^16.0.3",
"ethers": "^5.7.2",
"ethers": "^6.8.0",
"hardhat": "^2.12.7",
"prompts": "^2.4.2"
},
Expand Down
14 changes: 5 additions & 9 deletions examples/sweeper/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,14 @@ const DEFAULT_ENV = Environment.GOERLI;
// Load environment variables from `.env.local`
dotenv.config({ path: path.resolve(process.cwd(), ".env.local") });

let provider = new ethers.providers.InfuraProvider(
let provider = new ethers.InfuraProvider(
DEFAULT_ENV,
process.env.INFURA_KEY || DEFAULT_INFURA_COMMUNITY_KEY
);

export function getProvider(
env = Environment.GOERLI
): ethers.providers.Provider {
export function getProvider(env = Environment.GOERLI): ethers.Provider {
if (env !== Environment.GOERLI) {
provider = new ethers.providers.InfuraProvider(
provider = new ethers.InfuraProvider(
env,
process.env.INFURA_KEY || DEFAULT_INFURA_COMMUNITY_KEY
);
Expand All @@ -31,10 +29,8 @@ export function getProvider(
}

// getTurnkeySigner returns a TurnkeySigner connected to the passed-in Provider
// (https://docs.ethers.org/v5/api/providers/)
export function getTurnkeySigner(
provider: ethers.providers.Provider
): TurnkeySigner {
// (https://docs.ethers.org/v6/api/providers/)
export function getTurnkeySigner(provider: ethers.Provider): TurnkeySigner {
const turnkeyClient = new TurnkeyClient(
{
baseUrl: process.env.BASE_URL!,
Expand Down
Loading
Loading