@ethersproject/contracts#ContractTransaction TypeScript Examples
The following examples show how to use
@ethersproject/contracts#ContractTransaction.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ISwapRouter.d.ts From hardhat-v3-deploy with MIT License | 6 votes |
'exactInput(tuple)'(
params: {
path: BytesLike
recipient: string
deadline: BigNumberish
amountIn: BigNumberish
amountOutMinimum: BigNumberish
},
overrides?: PayableOverrides
): Promise<ContractTransaction>
Example #2
Source File: IERC721Receiver.d.ts From nft-marketplace with European Union Public License 1.2 | 6 votes |
functions: {
onERC721Received(
operator: string,
from: string,
tokenId: BigNumberish,
data: BytesLike,
overrides?: Overrides
): Promise<ContractTransaction>;
"onERC721Received(address,address,uint256,bytes)"(
operator: string,
from: string,
tokenId: BigNumberish,
data: BytesLike,
overrides?: Overrides
): Promise<ContractTransaction>;
};
Example #3
Source File: utils.ts From sdk with ISC License | 6 votes |
export function executePopulatedTransaction(
populatedTxn: Resolveable<PopulatedTransaction>,
signer: Signer,
): Promise<ContractTransaction> {
return Promise.resolve(populatedTxn)
.then(txn => signer.sendTransaction(txn))
.catch(rejectPromise)
}
Example #4
Source File: Ownable.d.ts From nft-marketplace with European Union Public License 1.2 | 6 votes |
functions: {
owner(overrides?: CallOverrides): Promise<[string]>;
"owner()"(overrides?: CallOverrides): Promise<[string]>;
renounceOwnership(overrides?: Overrides): Promise<ContractTransaction>;
"renounceOwnership()"(overrides?: Overrides): Promise<ContractTransaction>;
transferOwnership(
newOwner: string,
overrides?: Overrides
): Promise<ContractTransaction>;
"transferOwnership(address)"(
newOwner: string,
overrides?: Overrides
): Promise<ContractTransaction>;
};
Example #5
Source File: ISwapRouter.d.ts From hardhat-v3-deploy with MIT License | 6 votes |
exactInput(
params: {
path: BytesLike
recipient: string
deadline: BigNumberish
amountIn: BigNumberish
amountOutMinimum: BigNumberish
},
overrides?: PayableOverrides
): Promise<ContractTransaction>
Example #6
Source File: IERC721Enumerable.d.ts From nft-marketplace with European Union Public License 1.2 | 5 votes |
approve(
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
Example #7
Source File: IWETH9.d.ts From hardhat-v3-deploy with MIT License | 5 votes |
withdraw(arg0: BigNumberish, overrides?: Overrides): Promise<ContractTransaction>
Example #8
Source File: multisig.ts From aavegotchi-contracts with MIT License | 5 votes |
export async function sendToMultisig(
multisigAddress: string,
signer: Signer,
transaction: PopulatedTransaction,
ethers: any
) {
const abi = [
"function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId)",
];
const multisigContract = await ethers.getContractAt(
abi,
multisigAddress,
signer
);
console.log("Sending transaction to multisig:", multisigAddress);
console.log("signer:", await signer.getAddress());
console.log("data:", transaction.data);
//@ts-ignore
const feeData: FeeData = await signer.provider?.getFeeData();
console.log("feedata:", feeData);
let tx: ContractTransaction = await multisigContract.submitTransaction(
transaction.to,
0,
transaction.data,
{ gasPrice: feeData.gasPrice.mul(5).div(2) }
);
console.log("tx:", tx.data);
let receipt = await tx.wait();
if (!receipt.status) {
throw Error(`Failed to send transaction to multisig: ${tx.hash}`);
}
console.log("Completed sending transaction to multisig:", tx.hash);
return tx;
}
Example #9
Source File: IWETH9.d.ts From hardhat-v3-deploy with MIT License | 5 votes |
transferFrom(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>
Example #10
Source File: batchDeposit.ts From aavegotchi-contracts with MIT License | 5 votes |
task(
"batchDeposit",
"Allows the batch deposit of ERC1155 to multiple ERC721 tokens"
)
.addParam("gotchiIds", "String array of Gotchi IDs")
.addParam(
"quantity",
"The amount of ERC1155 tokens to deposit into each ERC721 token"
)
.addParam("itemId", "The item to deposit")
.setAction(async (taskArgs: TaskArgs, hre: HardhatRuntimeEnvironment) => {
const gotchiIDs: string[] = taskArgs.gotchiIds.split(",");
const quantity: number = Number(taskArgs.quantity);
const itemId: number = Number(taskArgs.itemId);
//assuming all item drops are in the data/airdrops/itemdrops folder
// const { gotchis } = require(`../data/airdrops/itemdrops/${filename}.ts`);
const diamondAddress = maticDiamondAddress;
const itemManager = "0xa370f2ADd2A9Fba8759147995d6A0641F8d7C119";
let signer: Signer;
const testing = ["hardhat", "localhost"].includes(hre.network.name);
if (testing) {
await hre.network.provider.request({
method: "hardhat_impersonateAccount",
params: [itemManager],
});
signer = await hre.ethers.provider.getSigner(itemManager);
} else if (hre.network.name === "matic") {
signer = new LedgerSigner(hre.ethers.provider, "hid", "m/44'/60'/2'/0/0");
} else {
throw Error("Incorrect network selected");
}
const itemsTransfer = (
await hre.ethers.getContractAt("ItemsTransferFacet", diamondAddress)
).connect(signer) as ItemsTransferFacet;
const uniqueIds: string[] = removeDuplicates(gotchiIDs);
console.log(
"Batch Depositing",
quantity,
"items of itemId",
itemId,
"to",
uniqueIds.length,
"gotchis"
);
// let eachGotchi: number[] = Array(1).fill(itemId);
// let eachValue: number[] = Array(1).fill(quantity);
const tx: ContractTransaction =
await itemsTransfer.batchBatchTransferToParent(
itemManager,
diamondAddress,
uniqueIds,
Array(uniqueIds.length).fill([itemId]),
Array(uniqueIds.length).fill([quantity]),
{ gasPrice: gasPrice }
);
console.log("tx:", tx.hash);
let receipt: ContractReceipt = await tx.wait();
// console.log("Gas used:", strDisplay(receipt.gasUsed.toString()));
if (!receipt.status) {
throw Error(`Error:: ${tx.hash}`);
}
});
Example #11
Source File: IWETH9.d.ts From hardhat-v3-deploy with MIT License | 5 votes |
'transfer(address,uint256)'(
recipient: string,
amount: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>
Example #12
Source File: grantXP_customValues.ts From aavegotchi-contracts with MIT License | 5 votes |
task(
"grantXP_customValues",
"Grants XP to Gotchis by GotchiID, with a custom array"
)
.addParam("filename", "File that contains the airdrop")
.addParam(
"batchSize",
"How many Aavegotchis to send at a time. Default is 500"
)
.setAction(async (taskArgs: TaskArgs, hre: HardhatRuntimeEnvironment) => {
const filename: string = taskArgs.filename;
const batchSize: number = Number(taskArgs.batchSize);
let { tokenIds, amounts } = require(`../data/airdrops/${filename}.ts`);
const diamondAddress = maticDiamondAddress;
const gameManager = "0x8D46fd7160940d89dA026D59B2e819208E714E82";
console.log(gameManager);
let signer: Signer;
const testing = ["hardhat", "localhost"].includes(hre.network.name);
if (testing) {
await hre.network.provider.request({
method: "hardhat_impersonateAccount",
params: [gameManager],
});
signer = await hre.ethers.provider.getSigner(gameManager);
} else if (hre.network.name === "matic") {
const accounts = await hre.ethers.getSigners();
signer = accounts[0];
// signer = new LedgerSigner(hre.ethers.provider, "hid", "m/44'/60'/2'/0/0");
} else throw Error("Incorrect network selected");
const managedSigner = new NonceManager(signer);
const batches = Math.ceil(tokenIds.length / batchSize);
console.log(
`Sending XP to ${tokenIds.length} Aavegotchis in ${tokenIds.length} addresses!`
);
const dao = (
await hre.ethers.getContractAt("DAOFacet", diamondAddress)
).connect(managedSigner) as DAOFacet;
for (let index = 0; index < batches; index++) {
console.log("Current batch id:", index);
const offset = batchSize * index;
const sendTokenIds = tokenIds.slice(offset, offset + batchSize);
const sendAmounts: string[] = amounts.slice(offset, offset + batchSize);
console.log("send token ids:", sendTokenIds);
console.log(
`Sending ${sendAmounts.toString()} XP to ${
sendTokenIds.length
} Aavegotchis `
);
const tx: ContractTransaction = await dao.grantExperience(
sendTokenIds,
sendAmounts,
{ gasPrice: gasPrice }
);
console.log("tx:", tx.hash);
let receipt: ContractReceipt = await tx.wait();
if (!receipt.status) {
throw Error(`Error:: ${tx.hash}`);
}
console.log(
"Airdropped XP to Aaavegotchis. Last tokenID:",
sendTokenIds[sendTokenIds.length - 1]
);
}
});
Example #13
Source File: IWETH9.d.ts From hardhat-v3-deploy with MIT License | 5 votes |
'deposit()'(overrides?: PayableOverrides): Promise<ContractTransaction>
Example #14
Source File: IERC721.d.ts From nft-marketplace with European Union Public License 1.2 | 5 votes |
"transferFrom(address,address,uint256)"(
from: string,
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
Example #15
Source File: IWETH9.d.ts From hardhat-v3-deploy with MIT License | 5 votes |
deposit(overrides?: PayableOverrides): Promise<ContractTransaction>
Example #16
Source File: ERC721.d.ts From nft-marketplace with European Union Public License 1.2 | 5 votes |
approve(
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
Example #17
Source File: ISwapRouter.d.ts From hardhat-v3-deploy with MIT License | 5 votes |
uniswapV3SwapCallback(
amount0Delta: BigNumberish,
amount1Delta: BigNumberish,
data: BytesLike,
overrides?: Overrides
): Promise<ContractTransaction>
Example #18
Source File: ERC721.d.ts From nft-marketplace with European Union Public License 1.2 | 5 votes |
"transferFrom(address,address,uint256)"(
from: string,
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
Example #19
Source File: ISwapRouter.d.ts From hardhat-v3-deploy with MIT License | 5 votes |
'uniswapV3SwapCallback(int256,int256,bytes)'(
amount0Delta: BigNumberish,
amount1Delta: BigNumberish,
data: BytesLike,
overrides?: Overrides
): Promise<ContractTransaction>
Example #20
Source File: ERC721.d.ts From nft-marketplace with European Union Public License 1.2 | 5 votes |
transferFrom(
from: string,
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
Example #21
Source File: ISwapRouter.d.ts From hardhat-v3-deploy with MIT License | 4 votes |
functions: {
exactInput(
params: {
path: BytesLike
recipient: string
deadline: BigNumberish
amountIn: BigNumberish
amountOutMinimum: BigNumberish
},
overrides?: PayableOverrides
): Promise<ContractTransaction>
'exactInput(tuple)'(
params: {
path: BytesLike
recipient: string
deadline: BigNumberish
amountIn: BigNumberish
amountOutMinimum: BigNumberish
},
overrides?: PayableOverrides
): Promise<ContractTransaction>
exactInputSingle(
params: {
tokenIn: string
tokenOut: string
fee: BigNumberish
recipient: string
deadline: BigNumberish
amountIn: BigNumberish
amountOutMinimum: BigNumberish
sqrtPriceLimitX96: BigNumberish
},
overrides?: PayableOverrides
): Promise<ContractTransaction>
'exactInputSingle(tuple)'(
params: {
tokenIn: string
tokenOut: string
fee: BigNumberish
recipient: string
deadline: BigNumberish
amountIn: BigNumberish
amountOutMinimum: BigNumberish
sqrtPriceLimitX96: BigNumberish
},
overrides?: PayableOverrides
): Promise<ContractTransaction>
exactOutput(
params: {
path: BytesLike
recipient: string
deadline: BigNumberish
amountOut: BigNumberish
amountInMaximum: BigNumberish
},
overrides?: PayableOverrides
): Promise<ContractTransaction>
'exactOutput(tuple)'(
params: {
path: BytesLike
recipient: string
deadline: BigNumberish
amountOut: BigNumberish
amountInMaximum: BigNumberish
},
overrides?: PayableOverrides
): Promise<ContractTransaction>
exactOutputSingle(
params: {
tokenIn: string
tokenOut: string
fee: BigNumberish
recipient: string
deadline: BigNumberish
amountOut: BigNumberish
amountInMaximum: BigNumberish
sqrtPriceLimitX96: BigNumberish
},
overrides?: PayableOverrides
): Promise<ContractTransaction>
'exactOutputSingle(tuple)'(
params: {
tokenIn: string
tokenOut: string
fee: BigNumberish
recipient: string
deadline: BigNumberish
amountOut: BigNumberish
amountInMaximum: BigNumberish
sqrtPriceLimitX96: BigNumberish
},
overrides?: PayableOverrides
): Promise<ContractTransaction>
uniswapV3SwapCallback(
amount0Delta: BigNumberish,
amount1Delta: BigNumberish,
data: BytesLike,
overrides?: Overrides
): Promise<ContractTransaction>
'uniswapV3SwapCallback(int256,int256,bytes)'(
amount0Delta: BigNumberish,
amount1Delta: BigNumberish,
data: BytesLike,
overrides?: Overrides
): Promise<ContractTransaction>
}
Example #22
Source File: mintBaadgeSvgs.ts From aavegotchi-contracts with MIT License | 4 votes |
task("mintBaadgeSvgs", "Adds itemTypes and SVGs")
.addParam("itemManager", "Address of the item manager", "0")
.addParam("itemFile", "File name of the items to add")
.addFlag("uploadItemTypes", "Upload itemTypes")
.addFlag("sendToItemManager", "Mint and send the items to itemManager")
.setAction(
async (taskArgs: MintBaadgeTaskArgs, hre: HardhatRuntimeEnvironment) => {
console.log("item manager:", taskArgs.itemManager);
if (taskArgs.itemManager !== itemManagerAlt) {
throw new Error("Wrong item manager");
}
const itemFile: string = taskArgs.itemFile;
const itemManager = taskArgs.itemManager;
const sendToItemManager = taskArgs.sendToItemManager;
const uploadItemTypes = taskArgs.uploadItemTypes;
const {
itemTypes: currentItemTypes,
} = require(`../scripts/addItemTypes/itemTypes/${itemFile}.ts`);
const itemTypesArray: ItemTypeOutput[] =
getBaadgeItemTypes(currentItemTypes);
let signer: Signer;
let owner = itemManager;
const testing = ["hardhat", "localhost"].includes(hre.network.name);
if (testing) {
await hre.network.provider.request({
method: "hardhat_impersonateAccount",
params: [owner],
});
signer = await hre.ethers.provider.getSigner(owner);
} else if (hre.network.name === "matic") {
signer = await (await hre.ethers.getSigners())[0];
// signer = new LedgerSigner(
// hre.ethers.provider,
// "hid",
// "m/44'/60'/2'/0/0"
// );
} else {
throw Error("Incorrect network selected");
}
console.log("signer:", await signer.getAddress());
let tx: ContractTransaction;
let receipt: ContractReceipt;
let daoFacet = (await hre.ethers.getContractAt(
"DAOFacet",
maticDiamondAddress,
signer
)) as DAOFacet;
if (uploadItemTypes) {
console.log("Adding items", 0, "to", currentItemTypes.length);
tx = await daoFacet.addItemTypes(itemTypesArray, {
gasPrice: gasPrice,
});
console.log("tx hash:", tx.hash);
receipt = await tx.wait();
if (!receipt.status) {
throw Error(`Error:: ${tx.hash}`);
}
console.log("Items were added:", tx.hash);
}
if (sendToItemManager) {
const itemIds: BigNumberish[] = [];
const quantities: BigNumberish[] = [];
currentItemTypes.forEach((itemType: ItemTypeOutput) => {
itemIds.push(itemType.svgId);
quantities.push(itemType.maxQuantity);
});
console.log("final quantities:", itemIds, quantities);
console.log(`Mint prize items to Item Manager ${itemManager}`);
tx = await daoFacet.mintItems(itemManager, itemIds, quantities, {
gasPrice: gasPrice,
});
receipt = await tx.wait();
if (!receipt.status) {
throw Error(`Error:: ${tx.hash}`);
}
console.log("Prize items minted:", tx.hash);
}
}
);
Example #23
Source File: UnchainedCryptoMarket.d.ts From nft-marketplace with European Union Public License 1.2 | 4 votes |
functions: {
approve(
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
"approve(address,uint256)"(
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
balanceOf(owner: string, overrides?: CallOverrides): Promise<[BigNumber]>;
"balanceOf(address)"(
owner: string,
overrides?: CallOverrides
): Promise<[BigNumber]>;
baseURI(overrides?: CallOverrides): Promise<[string]>;
"baseURI()"(overrides?: CallOverrides): Promise<[string]>;
contentHashes(
arg0: BytesLike,
overrides?: CallOverrides
): Promise<[boolean]>;
"contentHashes(bytes32)"(
arg0: BytesLike,
overrides?: CallOverrides
): Promise<[boolean]>;
getApproved(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string]>;
"getApproved(uint256)"(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string]>;
hashToTokenId(
arg0: BytesLike,
overrides?: CallOverrides
): Promise<[BigNumber]>;
"hashToTokenId(bytes32)"(
arg0: BytesLike,
overrides?: CallOverrides
): Promise<[BigNumber]>;
isApprovedForAll(
owner: string,
operator: string,
overrides?: CallOverrides
): Promise<[boolean]>;
"isApprovedForAll(address,address)"(
owner: string,
operator: string,
overrides?: CallOverrides
): Promise<[boolean]>;
mintAndBuy(
to: string,
contentHash: BytesLike,
overrides?: PayableOverrides
): Promise<ContractTransaction>;
"mintAndBuy(address,bytes32)"(
to: string,
contentHash: BytesLike,
overrides?: PayableOverrides
): Promise<ContractTransaction>;
name(overrides?: CallOverrides): Promise<[string]>;
"name()"(overrides?: CallOverrides): Promise<[string]>;
owner(overrides?: CallOverrides): Promise<[string]>;
"owner()"(overrides?: CallOverrides): Promise<[string]>;
ownerOf(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string]>;
"ownerOf(uint256)"(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string]>;
pricePerToken(overrides?: CallOverrides): Promise<[BigNumber]>;
"pricePerToken()"(overrides?: CallOverrides): Promise<[BigNumber]>;
renounceOwnership(overrides?: Overrides): Promise<ContractTransaction>;
"renounceOwnership()"(overrides?: Overrides): Promise<ContractTransaction>;
"safeTransferFrom(address,address,uint256)"(
from: string,
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
"safeTransferFrom(address,address,uint256,bytes)"(
from: string,
to: string,
tokenId: BigNumberish,
_data: BytesLike,
overrides?: Overrides
): Promise<ContractTransaction>;
setApprovalForAll(
operator: string,
approved: boolean,
overrides?: Overrides
): Promise<ContractTransaction>;
"setApprovalForAll(address,bool)"(
operator: string,
approved: boolean,
overrides?: Overrides
): Promise<ContractTransaction>;
supportsInterface(
interfaceId: BytesLike,
overrides?: CallOverrides
): Promise<[boolean]>;
"supportsInterface(bytes4)"(
interfaceId: BytesLike,
overrides?: CallOverrides
): Promise<[boolean]>;
symbol(overrides?: CallOverrides): Promise<[string]>;
"symbol()"(overrides?: CallOverrides): Promise<[string]>;
tokenByIndex(
index: BigNumberish,
overrides?: CallOverrides
): Promise<[BigNumber]>;
"tokenByIndex(uint256)"(
index: BigNumberish,
overrides?: CallOverrides
): Promise<[BigNumber]>;
tokenContentHashes(
arg0: BigNumberish,
overrides?: CallOverrides
): Promise<[string]>;
"tokenContentHashes(uint256)"(
arg0: BigNumberish,
overrides?: CallOverrides
): Promise<[string]>;
tokenOfOwnerByIndex(
owner: string,
index: BigNumberish,
overrides?: CallOverrides
): Promise<[BigNumber]>;
"tokenOfOwnerByIndex(address,uint256)"(
owner: string,
index: BigNumberish,
overrides?: CallOverrides
): Promise<[BigNumber]>;
tokenURI(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string]>;
"tokenURI(uint256)"(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string]>;
totalSupply(overrides?: CallOverrides): Promise<[BigNumber]>;
"totalSupply()"(overrides?: CallOverrides): Promise<[BigNumber]>;
transferFrom(
from: string,
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
"transferFrom(address,address,uint256)"(
from: string,
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
transferOwnership(
newOwner: string,
overrides?: Overrides
): Promise<ContractTransaction>;
"transferOwnership(address)"(
newOwner: string,
overrides?: Overrides
): Promise<ContractTransaction>;
withdraw(overrides?: Overrides): Promise<ContractTransaction>;
"withdraw()"(overrides?: Overrides): Promise<ContractTransaction>;
};
Example #24
Source File: IWETH9.d.ts From hardhat-v3-deploy with MIT License | 4 votes |
functions: {
allowance(
owner: string,
spender: string,
overrides?: CallOverrides
): Promise<{
0: BigNumber
}>
'allowance(address,address)'(
owner: string,
spender: string,
overrides?: CallOverrides
): Promise<{
0: BigNumber
}>
approve(spender: string, amount: BigNumberish, overrides?: Overrides): Promise<ContractTransaction>
'approve(address,uint256)'(
spender: string,
amount: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>
balanceOf(
account: string,
overrides?: CallOverrides
): Promise<{
0: BigNumber
}>
'balanceOf(address)'(
account: string,
overrides?: CallOverrides
): Promise<{
0: BigNumber
}>
deposit(overrides?: PayableOverrides): Promise<ContractTransaction>
'deposit()'(overrides?: PayableOverrides): Promise<ContractTransaction>
totalSupply(
overrides?: CallOverrides
): Promise<{
0: BigNumber
}>
'totalSupply()'(
overrides?: CallOverrides
): Promise<{
0: BigNumber
}>
transfer(recipient: string, amount: BigNumberish, overrides?: Overrides): Promise<ContractTransaction>
'transfer(address,uint256)'(
recipient: string,
amount: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>
transferFrom(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>
'transferFrom(address,address,uint256)'(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>
withdraw(arg0: BigNumberish, overrides?: Overrides): Promise<ContractTransaction>
'withdraw(uint256)'(arg0: BigNumberish, overrides?: Overrides): Promise<ContractTransaction>
}
Example #25
Source File: addItemTypes.ts From aavegotchi-contracts with MIT License | 4 votes |
task("addItemTypes", "Adds itemTypes and SVGs ")
.addParam("itemManager", "Address of the item manager", "0")
.addParam("diamondAddress", "Address of the Diamond to upgrade")
.addParam("itemFile", "File name of the items to add")
.addParam("svgFile", "File name of the itemType SVGs")
.addParam("sleeveStartId", "ID of the sleeve to start at")
.addFlag("uploadItemTypes", "Upload itemTypes")
.addFlag("uploadWearableSvgs", "Upload the SVGs")
.addFlag("uploadSleeveSvgs", "Upload sleeve svgs")
.addFlag("associateSleeves", "Associate the sleeves")
.addFlag("sendToItemManager", "Mint and send the items to itemManager")
.addFlag("replaceWearableSvgs", "Replace wearable SVGs instead of uploading")
.addFlag("replaceSleeveSvgs", "Replace sleeve SVGs instead of uploading")
.setAction(
async (taskArgs: AddItemTypesTaskArgs, hre: HardhatRuntimeEnvironment) => {
const itemFile: string = taskArgs.itemFile;
const diamondAddress: string = taskArgs.diamondAddress;
const svgFile: string = taskArgs.svgFile;
const sleeveStartId: string = taskArgs.sleeveStartId;
const itemManager = taskArgs.itemManager;
const sendToItemManager = taskArgs.sendToItemManager;
const uploadItemTypes = taskArgs.uploadItemTypes;
const uploadWearableSvgs = taskArgs.uploadWearableSvgs;
const associateSleeves = taskArgs.associateSleeves;
const uploadSleeveSvgs = taskArgs.uploadSleeveSvgs;
const replaceWearableSvgs = taskArgs.replaceWearableSvgs;
const replaceSleeveSvgs = taskArgs.replaceSleeveSvgs;
const {
itemTypes: currentItemTypes,
} = require(`../data/itemTypes/${itemFile}.ts`);
const { getWearables } = require(`../svgs/${svgFile}.ts`);
const { sleeves, wearables } = getWearables();
const itemTypesArray: ItemTypeOutput[] = getItemTypes(
currentItemTypes,
hre.ethers
);
const svgsArray: string[] = wearables;
const sleeveSvgsArray: SleeveObject[] = sleeves;
let signer: Signer;
let owner = itemManager;
const testing = ["hardhat", "localhost"].includes(hre.network.name);
if (testing) {
await hre.network.provider.request({
method: "hardhat_impersonateAccount",
params: [owner],
});
signer = await hre.ethers.provider.getSigner(owner);
} else if (hre.network.name === "matic") {
signer = new LedgerSigner(
hre.ethers.provider,
"hid",
"m/44'/60'/2'/0/0"
);
} else {
throw Error("Incorrect network selected");
}
let tx: ContractTransaction;
let receipt: ContractReceipt;
let daoFacet = (await hre.ethers.getContractAt(
"DAOFacet",
diamondAddress,
signer
)) as DAOFacet;
let svgFacet = (await hre.ethers.getContractAt(
"SvgFacet",
diamondAddress,
signer
)) as SvgFacet;
if (uploadItemTypes) {
console.log("Adding items", 0, "to", currentItemTypes.length);
tx = await daoFacet.addItemTypes(itemTypesArray, {
gasPrice: gasPrice,
});
receipt = await tx.wait();
if (!receipt.status) {
throw Error(`Error:: ${tx.hash}`);
}
console.log("Items were added:", tx.hash);
}
if (uploadWearableSvgs) {
console.log("Upload SVGs");
await uploadSvgs(svgFacet, svgsArray, "wearables", hre.ethers);
}
if (replaceWearableSvgs) {
await updateSvgs(
svgsArray,
"wearables",
itemTypesArray.map((value) => Number(value.svgId)),
svgFacet,
hre
);
}
if (uploadSleeveSvgs) {
console.log("Uploading Sleeves");
await uploadSvgs(
svgFacet,
sleeveSvgsArray.map((value) => value.svg),
"sleeves",
hre.ethers
);
}
if (replaceSleeveSvgs) {
await updateSvgs(
sleeveSvgsArray.map((value) => value.svg),
"sleeves",
sleeveSvgsArray.map((_, index) => Number(sleeveStartId) + index),
svgFacet,
hre
);
}
if (associateSleeves) {
interface SleeveInput {
sleeveId: BigNumberish;
wearableId: BigNumberish;
}
let sleevesSvgId: number = Number(sleeveStartId);
let sleevesInput: SleeveInput[] = [];
for (const sleeve of sleeveSvgsArray) {
sleevesInput.push({
sleeveId: sleevesSvgId,
wearableId: sleeve.id,
});
sleevesSvgId++;
}
console.log("sleeves input:", sleevesInput);
console.log("Associating sleeves svgs with body wearable svgs.");
tx = await svgFacet.setSleeves(sleevesInput, { gasPrice: gasPrice });
receipt = await tx.wait();
if (!receipt.status) {
throw Error(`Error:: ${tx.hash}`);
}
console.log("Sleeves associated:", tx.hash);
}
if (sendToItemManager) {
const itemIds: BigNumberish[] = [];
const quantities: BigNumberish[] = [];
itemTypesArray.forEach((itemType: ItemTypeOutput) => {
itemIds.push(itemType.svgId);
quantities.push(itemType.maxQuantity);
});
console.log("final quantities:", itemIds, quantities);
console.log(`Mint prize items to Item Manager ${itemManager}`);
tx = await daoFacet.mintItems(itemManager, itemIds, quantities, {
gasPrice: gasPrice,
});
receipt = await tx.wait();
if (!receipt.status) {
throw Error(`Error:: ${tx.hash}`);
}
console.log("Prize items minted:", tx.hash);
}
}
);
Example #26
Source File: deployUpgrade.ts From ghst-staking with MIT License | 4 votes |
task(
"deployUpgrade",
"Deploys a Diamond Cut, given an address, facets and addSelectors, and removeSelectors"
)
.addParam("diamondUpgrader", "Address of the multisig signer")
.addParam("diamondAddress", "Address of the Diamond to upgrade")
.addParam(
"facetsAndAddSelectors",
"Stringified array of facet names to upgrade, along with an array of add Selectors"
)
.addOptionalParam("initAddress", "The facet address to call init function on")
.addOptionalParam("initCalldata", "The calldata for init function")
.addFlag(
"useMultisig",
"Set to true if multisig should be used for deploying"
)
.addFlag("useLedger", "Set to true if Ledger should be used for signing")
// .addFlag("verifyFacets","Set to true if facets should be verified after deployment")
.setAction(
async (taskArgs: DeployUpgradeTaskArgs, hre: HardhatRuntimeEnvironment) => {
const facets: string = taskArgs.facetsAndAddSelectors;
const facetsAndAddSelectors: FacetsAndAddSelectors[] =
convertStringToFacetAndSelectors(facets);
const diamondUpgrader: string = taskArgs.diamondUpgrader;
const diamondAddress: string = taskArgs.diamondAddress;
const useMultisig = taskArgs.useMultisig;
const useLedger = taskArgs.useLedger;
const initAddress = taskArgs.initAddress;
const initCalldata = taskArgs.initCalldata;
//Instantiate the Signer
let signer: Signer;
const owner = await (
(await hre.ethers.getContractAt(
"OwnershipFacet",
diamondAddress
)) as OwnershipFacet
).owner();
const testing = ["hardhat", "localhost"].includes(hre.network.name);
if (testing) {
await hre.network.provider.request({
method: "hardhat_impersonateAccount",
params: [owner],
});
signer = await hre.ethers.getSigner(owner);
} else if (hre.network.name === "matic") {
if (useLedger) {
signer = new LedgerSigner(hre.ethers.provider);
} else signer = (await hre.ethers.getSigners())[0];
} else {
throw Error("Incorrect network selected");
}
//Create the cut
const deployedFacets = [];
const cut: Cut[] = [];
for (let index = 0; index < facetsAndAddSelectors.length; index++) {
const facet = facetsAndAddSelectors[index];
const factory = (await hre.ethers.getContractFactory(
facet.facetName
)) as ContractFactory;
const deployedFacet: Contract = await factory.deploy({
gasPrice: gasPrice,
});
await deployedFacet.deployed();
console.log(
`Deployed Facet Address for ${facet.facetName}:`,
deployedFacet.address
);
deployedFacets.push(deployedFacet);
//Verify
if (hre.network.name === "matic") {
// await hre.run("verify:verify", {
// address: deployedFacet.address,
// constructorArguments: [],
// });
}
const newSelectors = getSighashes(facet.addSelectors, hre.ethers);
const removeSelectors = getSighashes(facet.removeSelectors, hre.ethers);
let existingFuncs = getSelectors(deployedFacet);
console.log("existing funcs:", existingFuncs);
for (const selector of newSelectors) {
if (!existingFuncs.includes(selector)) {
const index = newSelectors.findIndex((val) => val == selector);
throw Error(
`Selector ${selector} (${facet.addSelectors[index]}) not found`
);
}
}
// console.log("funcs:", existingFuncs.length);
let existingSelectors = getSelectors(deployedFacet);
existingSelectors = existingSelectors.filter(
(selector) => !newSelectors.includes(selector)
);
// console.log("existing selectors:", existingSelectors);
// console.log("funcs:", existingSelectors.length);
if (newSelectors.length > 0) {
cut.push({
facetAddress: deployedFacet.address,
action: FacetCutAction.Add,
functionSelectors: newSelectors,
});
}
//Always replace the existing selectors to prevent duplications
//remove extra selectors
// existingSelectors = existingSelectors.filter(
// (selector) => !extra.includes(selector)
// );
if (existingSelectors.length > 0)
cut.push({
facetAddress: deployedFacet.address,
action: FacetCutAction.Replace,
functionSelectors: existingSelectors,
});
if (removeSelectors.length > 0) {
cut.push({
facetAddress: hre.ethers.constants.AddressZero,
action: FacetCutAction.Remove,
functionSelectors: removeSelectors,
});
}
}
console.log(cut);
//Execute the Cut
const diamondCut = (await hre.ethers.getContractAt(
"IDiamondCut",
diamondAddress,
signer
)) as IDiamondCut;
if (testing) {
console.log("Diamond cut");
const tx: ContractTransaction = await diamondCut.diamondCut(
cut,
initAddress ? initAddress : hre.ethers.constants.AddressZero,
initCalldata ? initCalldata : "0x",
{ gasLimit: 8000000 }
);
console.log("Diamond cut tx:", tx.hash);
const receipt: ContractReceipt = await tx.wait();
if (!receipt.status) {
throw Error(`Diamond upgrade failed: ${tx.hash}`);
}
console.log("Completed diamond cut: ", tx.hash);
} else {
//Choose to use a multisig or a simple deploy address
if (useMultisig) {
console.log("Diamond cut");
const tx: PopulatedTransaction =
await diamondCut.populateTransaction.diamondCut(
cut,
initAddress ? initAddress : hre.ethers.constants.AddressZero,
initCalldata ? initCalldata : "0x",
{ gasLimit: 800000 }
);
await sendToMultisig(diamondUpgrader, signer, tx, hre.ethers);
} else {
const tx: ContractTransaction = await diamondCut.diamondCut(
cut,
initAddress ? initAddress : hre.ethers.constants.AddressZero,
initCalldata ? initCalldata : "0x",
{ gasLimit: 800000, gasPrice: gasPrice }
);
const receipt: ContractReceipt = await tx.wait();
if (!receipt.status) {
throw Error(`Diamond upgrade failed: ${tx.hash}`);
}
console.log("Completed diamond cut: ", tx.hash);
}
}
}
);
Example #27
Source File: Concentrated.ts From trident with GNU General Public License v3.0 | 4 votes |
export async function swapViaRouter(params: {
pool: ConcentratedLiquidityPool;
zeroForOne: boolean; // true => we are moving left
inAmount: BigNumber;
recipient: string;
unwrapBento: boolean;
}): Promise<{ output: BigNumber; tx: ContractTransaction }> {
const { pool, zeroForOne, inAmount, recipient, unwrapBento } = params;
const immutables = await pool.getImmutables();
const nearest = (await pool.getPriceAndNearestTicks())._nearestTick;
const oldSplData = await pool.getSecondsGrowthAndLastObservation();
let nextTickToCross = zeroForOne ? nearest : (await pool.ticks(nearest)).nextTick;
let currentPrice = (await pool.getPriceAndNearestTicks())._price;
let currentLiquidity = await pool.liquidity();
let input = inAmount;
let output = BigNumber.from(0);
let feeGrowthGlobalIncrease = BigNumber.from(0);
let crossCount = 0;
let totalFees = BigNumber.from(0);
let protocolFeeIncrease = BigNumber.from(0);
const oldPrice = currentPrice;
const tokens = [immutables._token0, immutables._token1];
const swapFee = immutables._swapFee;
const tickSpacing = immutables._tickSpacing;
const barFee = await pool.barFee();
const feeGrowthGlobalOld = await (zeroForOne ? pool.feeGrowthGlobal1() : pool.feeGrowthGlobal0());
const _oldProtocolFees = await pool.getTokenProtocolFees();
const oldProtocolFees = zeroForOne ? _oldProtocolFees._token1ProtocolFee : _oldProtocolFees._token0ProtocolFee;
const oldPoolBalances = await Trident.Instance.getTokenBalance(tokens, pool.address, false);
const reserve = await pool.getReserves();
const oldReserve0 = reserve._reserve0;
const oldReserve1 = reserve._reserve1;
const startingLiquidity = currentLiquidity;
while (input.gt(0)) {
const nextTickPrice = await getTickPrice(nextTickToCross);
let cross = false;
let stepOutput;
let newPrice;
if (zeroForOne) {
const maxDx = await getDx(currentLiquidity, nextTickPrice, currentPrice, false);
if (input.lte(maxDx)) {
const liquidityPadded = currentLiquidity.mul(TWO_POW_96);
newPrice = divRoundingUp(liquidityPadded.mul(currentPrice), liquidityPadded.add(currentPrice.mul(input)));
stepOutput = getDy(currentLiquidity, newPrice, currentPrice, false);
currentPrice = newPrice;
input = BigNumber.from(0);
} else {
stepOutput = getDy(currentLiquidity, nextTickPrice, currentPrice, false);
currentPrice = nextTickPrice;
input = input.sub(maxDx);
cross = true;
}
} else {
// (price) numba' go up
const maxDy = await getDy(currentLiquidity, currentPrice, nextTickPrice, false);
if (input.lte(maxDy)) {
newPrice = currentPrice.add(input.mul(TWO_POW_96).div(currentLiquidity));
stepOutput = getDx(currentLiquidity, currentPrice, newPrice, false);
currentPrice = newPrice;
input = BigNumber.from(0);
} else {
stepOutput = getDx(currentLiquidity, currentPrice, nextTickPrice, false);
currentPrice = nextTickPrice;
input = input.sub(maxDy);
cross = true;
}
}
if (currentLiquidity.gt(0)) {
const feeAmount = divRoundingUp(stepOutput.mul(swapFee), BigNumber.from(1e6));
totalFees = totalFees.add(feeAmount);
const protocolFee = divRoundingUp(feeAmount.mul(barFee), BigNumber.from(1e4));
protocolFeeIncrease = protocolFeeIncrease.add(protocolFee);
feeGrowthGlobalIncrease = feeGrowthGlobalIncrease.add(
feeAmount.sub(protocolFee).mul(TWO_POW_128).div(currentLiquidity)
);
output = output.add(stepOutput.sub(feeAmount));
}
if (cross) {
crossCount++;
const liquidityChange = (await pool.ticks(nextTickToCross)).liquidity;
const tickInfo = await pool.ticks(nextTickToCross);
// TODO if we run out of liquidity (tick == min | tick =0 max tick) we need to throw an error here
if (zeroForOne) {
if ((nextTickToCross / tickSpacing) % 2 == 0) {
currentLiquidity = currentLiquidity.sub(liquidityChange);
} else {
currentLiquidity = currentLiquidity.add(liquidityChange);
}
nextTickToCross = tickInfo.previousTick;
} else {
if ((nextTickToCross / tickSpacing) % 2 == 0) {
currentLiquidity = currentLiquidity.add(liquidityChange);
} else {
currentLiquidity = currentLiquidity.sub(liquidityChange);
}
nextTickToCross = tickInfo.nextTick;
}
}
}
const swapData = getSwapData({ zeroForOne, inAmount, recipient, unwrapBento });
const routerData = {
amountIn: inAmount,
amountOutMinimum: output,
pool: pool.address,
tokenIn: zeroForOne ? tokens[0] : tokens[1],
data: swapData,
};
const tx = await Trident.Instance.router.exactInputSingle(routerData);
const newSplData = await pool.getSecondsGrowthAndLastObservation();
const block = await ethers.provider.getBlock(tx.blockNumber as number);
const timeDiff = block.timestamp - oldSplData._lastObservation;
const splIncrease = TWO_POW_128.mul(timeDiff).div(startingLiquidity);
expect(newSplData._secondsGrowthGlobal.toString()).to.be.eq(
oldSplData._secondsGrowthGlobal.add(splIncrease).toString(),
"Didn't correctly update global spl counter"
);
expect(newSplData._lastObservation).to.be.eq(block.timestamp);
const feeGrowthGlobalnew = await (zeroForOne ? pool.feeGrowthGlobal1() : pool.feeGrowthGlobal0());
const _newProtocolFees = await pool.getTokenProtocolFees();
const protocolFeesNew = zeroForOne ? _newProtocolFees._token1ProtocolFee : _newProtocolFees._token0ProtocolFee;
const newPrice = (await pool.getPriceAndNearestTicks())._price;
const newPoolBalances = await Trident.Instance.getTokenBalance(tokens, pool.address, false);
const [newReserve0, newReserve1] = await pool.getReserves();
let nextNearest = nearest;
for (let i = 0; i < crossCount; i++) {
nextNearest = (await pool.ticks(nextNearest))[zeroForOne ? "previousTick" : "nextTick"];
}
expect(newPoolBalances[0].toString()).to.be.eq(
oldPoolBalances[0].add(zeroForOne ? inAmount : output.mul(-1)).toString(),
"didn't transfer the correct token 0 amount"
);
expect(newPoolBalances[1].toString()).to.be.eq(
oldPoolBalances[1].add(zeroForOne ? output.mul(-1) : inAmount).toString(),
"didn't transfer the correct token 1 amount"
);
expect(newReserve0.toString()).to.be.eq(
oldReserve0.add(zeroForOne ? inAmount : output.mul(-1)),
"Didn't update reserve0 correctly"
);
expect(newReserve1.toString()).to.be.eq(
oldReserve1.add(zeroForOne ? output.mul(-1) : inAmount),
"Didn't update reserve1 correctly"
);
expect((await pool.liquidity()).toString()).to.be.eq(
currentLiquidity.toString(),
"didn't set correct liquidity value"
);
expect(await (await pool.getPriceAndNearestTicks())._nearestTick).to.be.eq(
nextNearest,
"didn't update nearest tick pointer"
);
expect(oldPrice.lt(newPrice) !== zeroForOne, "Price didn't move in the right direction");
expect(protocolFeesNew.toString()).to.be.eq(
oldProtocolFees.add(protocolFeeIncrease).toString(),
"Didn't update protocol fee counter correctly"
);
expect(feeGrowthGlobalnew.toString()).to.be.eq(
feeGrowthGlobalOld.add(feeGrowthGlobalIncrease).toString(),
"Didn't update the global fee tracker"
);
return { output, tx };
}
Example #28
Source File: IERC721Metadata.d.ts From nft-marketplace with European Union Public License 1.2 | 4 votes |
functions: {
approve(
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
"approve(address,uint256)"(
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
balanceOf(
owner: string,
overrides?: CallOverrides
): Promise<[BigNumber] & { balance: BigNumber }>;
"balanceOf(address)"(
owner: string,
overrides?: CallOverrides
): Promise<[BigNumber] & { balance: BigNumber }>;
getApproved(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string] & { operator: string }>;
"getApproved(uint256)"(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string] & { operator: string }>;
isApprovedForAll(
owner: string,
operator: string,
overrides?: CallOverrides
): Promise<[boolean]>;
"isApprovedForAll(address,address)"(
owner: string,
operator: string,
overrides?: CallOverrides
): Promise<[boolean]>;
name(overrides?: CallOverrides): Promise<[string]>;
"name()"(overrides?: CallOverrides): Promise<[string]>;
ownerOf(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string] & { owner: string }>;
"ownerOf(uint256)"(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string] & { owner: string }>;
"safeTransferFrom(address,address,uint256)"(
from: string,
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
"safeTransferFrom(address,address,uint256,bytes)"(
from: string,
to: string,
tokenId: BigNumberish,
data: BytesLike,
overrides?: Overrides
): Promise<ContractTransaction>;
setApprovalForAll(
operator: string,
_approved: boolean,
overrides?: Overrides
): Promise<ContractTransaction>;
"setApprovalForAll(address,bool)"(
operator: string,
_approved: boolean,
overrides?: Overrides
): Promise<ContractTransaction>;
supportsInterface(
interfaceId: BytesLike,
overrides?: CallOverrides
): Promise<[boolean]>;
"supportsInterface(bytes4)"(
interfaceId: BytesLike,
overrides?: CallOverrides
): Promise<[boolean]>;
symbol(overrides?: CallOverrides): Promise<[string]>;
"symbol()"(overrides?: CallOverrides): Promise<[string]>;
tokenURI(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string]>;
"tokenURI(uint256)"(
tokenId: BigNumberish,
overrides?: CallOverrides
): Promise<[string]>;
transferFrom(
from: string,
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
"transferFrom(address,address,uint256)"(
from: string,
to: string,
tokenId: BigNumberish,
overrides?: Overrides
): Promise<ContractTransaction>;
};
Example #29
Source File: ContractWrapperFunctions-test.ts From sdk with ISC License | 4 votes |
describe("SynapseBridge - Contract Wrapper Functions tests", function(this: Mocha.Suite) {
const ALL_CHAIN_IDS = supportedChainIds();
describe(".bridgeVersion()", function(this: Mocha.Suite) {
const expected = 6;
ALL_CHAIN_IDS.forEach(network => {
const
provider = rpcProviderForChain(network),
bridgeInstance = new Bridge.SynapseBridge({ network, provider}),
testTitle: string = `Should return ${expected.toString()} on Chain ID ${network}`;
it(testTitle, async function(this: Mocha.Context) {
this.timeout(DEFAULT_TEST_TIMEOUT);
let prom = bridgeInstance.bridgeVersion();
return wrapExpectAsync(expectBnEqual(await prom, expected), prom)
})
})
})
describe(".WETH_ADDRESS", function(this: Mocha.Suite) {
ALL_CHAIN_IDS.forEach(network => {
const
provider = rpcProviderForChain(network),
bridgeInstance = new Bridge.SynapseBridge({ network, provider }),
expected: string = ((): string => {
switch (network) {
case ChainId.ETH:
return "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
case ChainId.OPTIMISM:
return "0x121ab82b49B2BC4c7901CA46B8277962b4350204"
case ChainId.BOBA:
return "0xd203De32170130082896b4111eDF825a4774c18E"
case ChainId.ARBITRUM:
return "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"
default:
return "0x0000000000000000000000000000000000000000"
}})(),
testTitle: string = `Should return ${expected} for Chain ID ${network}`;
it(testTitle, async function(this: Mocha.Context) {
this.timeout(DEFAULT_TEST_TIMEOUT);
let prom = bridgeInstance.WETH_ADDRESS();
return wrapExpectAsync(expectEqual(await prom, expected), prom)
})
})
})
describe(".getAllowanceForAddress", function(this: Mocha.Suite) {
interface TestCase {
provider: Provider,
chainId: number,
address: string,
token: Token,
want: BigNumber,
isInfinite: boolean,
}
const
addr1: string = "0x7145a092158c215ff10cce4ddcb84b3a090bdd4e",
// addr2: string = "0x41fe2231639268f01383b86cc8b64fbf24b5e156",
addr3: string = "0x89a2a295174d899c6d68dfc03535993ee15ff72e",
addr4: string = "0x39c46cFD4711d1B4D7141d87f057C89C9D2d7019",
addr5: string = "0xDF681Fe10B2fb7B5605107098EA3867187851DCe",
infiniteCheckAmt: BigNumber = MaxUint256.div(2);
const makeTestCase = (c: number, t: Token, a: string, n: BigNumberish): TestCase => {
return {
provider: rpcProviderForChain(c),
chainId: c,
token: t,
address: a,
want: BigNumber.from(n),
isInfinite: MaxUint256.eq(n),
}
}
function runTestCase(tc: TestCase) {
const
{provider, chainId: network} = tc,
chainName: string = Networks.fromChainId(network).name,
wantNum: string = parseUnits(tc.want.toString(), tc.token.decimals(network)).toString();
const
spendAllowanceTitle: string = `should have a spend allowance of ${tc.isInfinite ? "unlimited" : wantNum} wei`,
title: string = `SynapseBridge on chain ${chainName} ${spendAllowanceTitle} for ${tc.token.name} holdings of ${tc.address}`;
it(title, async function (this: Mocha.Context) {
this.timeout(DEFAULT_TEST_TIMEOUT);
let bridgeInstance = new Bridge.SynapseBridge({network, provider});
const
{address, token} = tc,
decimals = token.decimals(network),
checkAmt: BigNumber = tc.isInfinite ? infiniteCheckAmt : tc.want;
let prom = bridgeInstance
.getAllowanceForAddress({address, token})
.then(res => getActualWei(res, decimals));
try {
const res = await prom;
return tc.isInfinite
? expect(res).to.be.gte(checkAmt)
: expect(res).to.be.eq(checkAmt)
} catch (err) {
return (await expectFulfilled(prom))
}
})
}
describe("- infinite approval", function(this: Mocha.Suite) {
step("Ensure infinite approval test address has infinite approval", async function(this: Mocha.Context) {
this.timeout(EXECUTORS_TEST_TIMEOUT);
dotenv.config();
const bscZapAddr: string = contractAddressFor(ChainId.BSC, "bridgeZap");
const tokenParams = {tokenAddress: Tokens.BUSD.address(ChainId.BSC), chainId: ChainId.BSC};
try {
const allowance = await ERC20.allowanceOf(
infiniteApprovalsPrivkey.address,
bscZapAddr,
tokenParams
);
if (allowance.lte(infiniteCheckAmt)) {
const wallet = new Wallet(
infiniteApprovalsPrivkey.privkey,
rpcProviderForChain(ChainId.BSC)
);
const approveArgs = {spender: bscZapAddr};
let txn: ContractTransaction = (await ERC20.approve(
approveArgs,
tokenParams,
wallet
)) as ContractTransaction;
await txn.wait(1);
const newAllowance = await ERC20.allowanceOf(
infiniteApprovalsPrivkey.address,
bscZapAddr,
tokenParams
);
expect(newAllowance).to.be.gte(infiniteCheckAmt);
}
return
} catch (err) {
const e: Error = err instanceof Error ? err : new Error(err);
expect(e.message).to.eq("");
}
})
runTestCase(makeTestCase(
ChainId.BSC,
Tokens.BUSD,
infiniteApprovalsPrivkey.address,
MaxUint256
));
})
describe("- zero approval", function(this: Mocha.Suite) {
[
makeTestCase(ChainId.AURORA, Tokens.DAI, addr4, Zero),
makeTestCase(ChainId.BOBA, Tokens.NUSD, addr3, Zero),
makeTestCase(ChainId.MOONRIVER, Tokens.SYN, addr1, Zero),
makeTestCase(ChainId.HARMONY, Tokens.NUSD, addr5, Zero),
].forEach(runTestCase);
})
})
})