ethers#Signer TypeScript Examples

The following examples show how to use ethers#Signer. 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: utils.ts    From hypervisor with The Unlicense 7 votes vote down vote up
export async function deployContract(
  name: string,
  factory: ContractFactory,
  signer: Signer,
  args: Array<any> = [],
): Promise<Contract> {
  const contract = await factory.connect(signer).deploy(...args)
  console.log('Deploying', name)
  console.log('  to', contract.address)
  console.log('  in', contract.deployTransaction.hash)
  return contract.deployed()
}
Example #2
Source File: submitting.ts    From safe-tasks with GNU Lesser General Public License v3.0 6 votes vote down vote up
prepareSignatures = async (safe: Contract, tx: SafeTransaction, signaturesCSV: string | undefined, submitter?: Signer, knownSafeTxHash?: string): Promise<SafeSignature[]> => {
    const owners = await safe.getOwners()
    const signatures = new Map<String, SafeSignature>()
    const submitterAddress = submitter && await submitter.getAddress()
    if (signaturesCSV) {
        const chainId = (await safe.provider.getNetwork()).chainId
        const safeTxHash = knownSafeTxHash ?? calculateSafeTransactionHash(safe, tx, chainId)
        for (const signatureString of signaturesCSV.split(",")) {
            const signature = isOwnerSignature(owners, parseSignature(safeTxHash, signatureString))
            if (submitterAddress === signature.signer || signatures.has(signature.signer)) continue
            signatures.set(signature.signer, signature)
        }
    }
    const threshold = (await safe.getThreshold()).toNumber()
    const submitterIsOwner = submitterAddress && owners.indexOf(submitterAddress) >= 0
    const requiredSigntures = submitterIsOwner ? threshold - 1 : threshold
    if (requiredSigntures > signatures.size) throw Error(`Not enough signatures (${signatures.size} of ${threshold})`)
    const signatureArray = []
    if (submitterIsOwner) {
        signatureArray.push(await safeApproveHash(submitter!!, safe, tx, true))
    }
    return signatureArray.concat(Array.from(signatures.values()).slice(0, requiredSigntures))
}
Example #3
Source File: ERC1967UpgradeUpgradeable__factory.ts    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
static connect(
    address: string,
    signerOrProvider: Signer | Provider,
  ): ERC1967UpgradeUpgradeable {
    return new Contract(
      address,
      _abi,
      signerOrProvider,
    ) as ERC1967UpgradeUpgradeable;
  }
Example #4
Source File: main.ts    From pawnft with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns impersonated signer
 * @param {string} account to impersonate
 * @returns {Signer} authenticated as account
 */
async function impersonateSigner(account: string): Promise<Signer> {
  // Impersonate account
  await network.provider.request({
    method: "hardhat_impersonateAccount",
    params: [account],
  });

  // Return ethers signer
  return await ethers.provider.getSigner(account);
}
Example #5
Source File: index.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
constructor(deployerSigner: Signer) {
    this.token = new DeployToken(deployerSigner);
    this.setV2 = new DeploySetV2(deployerSigner);
    this.manager = new DeployManager(deployerSigner);
    this.mocks = new DeployMocks(deployerSigner);
    this.extensions = new DeployExtensions(deployerSigner);
    this.external = new DeployExternalContracts(deployerSigner);
    this.hooks = new DeployHooks(deployerSigner);
    this.staking = new DeployStaking(deployerSigner);
    this.viewers = new DeployViewers(deployerSigner);
    this.keepers = new DeployKeepers(deployerSigner);
  }
Example #6
Source File: dataOrganization.ts    From index-rebalance-utils with Apache License 2.0 6 votes vote down vote up
export async function createStrategyObject(
  setToken: SetToken,
  strategyInfo: StrategyInfo,
  owner: Signer
): Promise<StrategyObject> {
  const strategyObject: StrategyObject = {};

  const currentPositions: any[] = await setToken.getPositions();

  const deployHelper: DeployHelper = new DeployHelper(owner);

  const filteredConstants = _.pick(_.merge(ASSETS, strategyInfo), Object.keys(strategyInfo));
  const keys = Object.keys(filteredConstants);
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];

    const position = currentPositions.filter(obj => obj.component.toLowerCase() == filteredConstants[key].address.toLowerCase())[0];
    if (position) { filteredConstants[key].currentUnit = position.unit; }

    const decimals = await getTokenDecimals(deployHelper, filteredConstants[key].address);

    strategyObject[key] = {} as AssetStrategy;
    strategyObject[key].address = filteredConstants[key].address;
    strategyObject[key].price = filteredConstants[key].price;
    strategyObject[key].maxTradeSize = filteredConstants[key].maxTradeSize.mul(decimals).div(PRECISE_UNIT);
    strategyObject[key].exchange = filteredConstants[key].exchange;
    strategyObject[key].coolOffPeriod = filteredConstants[key].coolOffPeriod;
    strategyObject[key].input = filteredConstants[key].input;
    strategyObject[key].currentUnit = position ? position.unit : ZERO;
    strategyObject[key].decimals = decimals;
  }

  return strategyObject;
}
Example #7
Source File: EchidnaL1NovaExecutionManager__factory.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
static connect(
    address: string,
    signerOrProvider: Signer | Provider
  ): EchidnaL1NovaExecutionManager {
    return new Contract(
      address,
      _abi,
      signerOrProvider
    ) as EchidnaL1NovaExecutionManager;
  }
Example #8
Source File: ContractWrapper.ts    From set.js with Apache License 2.0 6 votes vote down vote up
/**
   * Load Set Token Creator contract
   *
   * @param  setTokenCreatorAddress  Address of the Set Token Creator contract
   * @param  signer                  Caller of the method
   * @return                         The Set Token Creator Contract
   */
  public async loadSetTokenCreatorAsync(
    setTokenCreatorAddress: Address,
    signer: Signer,
  ): Promise<SetTokenCreator> {
    const cacheKey = `SetTokenCreator_${setTokenCreatorAddress}_${await signer.getAddress()}`;

    if (cacheKey in this.cache) {
      return this.cache[cacheKey] as SetTokenCreator;
    } else {
      const setTokenCreator = SetTokenCreator__factory.connect(
        setTokenCreatorAddress,
        signer
      );

      this.cache[cacheKey] = setTokenCreator;
      return setTokenCreator;
    }
  }
Example #9
Source File: usePromiseTransaction.ts    From useDApp with MIT License 6 votes vote down vote up
/**
 * @internal
 */
export async function estimateGasLimit(
  transactionRequest: TransactionRequest | undefined,
  signer: Signer | undefined,
  bufferGasLimitPercentage: number
) {
  if (!signer || !transactionRequest) {
    return undefined
  }
  try {
    const estimatedGas = transactionRequest.gasLimit
      ? BigNumber.from(transactionRequest.gasLimit)
      : await signer.estimateGas(transactionRequest)
    return estimatedGas?.mul(bufferGasLimitPercentage + 100).div(100)
  } catch (err: any) {
    console.error(err)
    return undefined
  }
}
Example #10
Source File: UniswapV3Deployer.ts    From hardhat-v3-deploy with MIT License 6 votes vote down vote up
static async deploy(actor: Signer): Promise<{ [name: string]: Contract }> {
    const deployer = new UniswapV3Deployer(actor);

    const weth9 = await deployer.deployWETH9();
    const factory = await deployer.deployFactory();
    const router = await deployer.deployRouter(factory.address, weth9.address);
    const nftDescriptorLibrary = await deployer.deployNFTDescriptorLibrary();
    const positionDescriptor = await deployer.deployPositionDescriptor(
      nftDescriptorLibrary.address,
      weth9.address
    );
    const positionManager = await deployer.deployNonfungiblePositionManager(
      factory.address,
      weth9.address,
      positionDescriptor.address
    );

    return {
      weth9,
      factory,
      router,
      nftDescriptorLibrary,
      positionDescriptor,
      positionManager,
    };
  }
Example #11
Source File: CrossAnchorBridgeV2__factory.ts    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
connect(signer: Signer): CrossAnchorBridgeV2__factory {
    return super.connect(signer) as CrossAnchorBridgeV2__factory;
  }
Example #12
Source File: CommunityVault.test.ts    From BarnBridge-YieldFarming with Apache License 2.0 5 votes vote down vote up
describe("CommunityVault", function () {
    let bondToken: ERC20Mock;
    let communityVault: CommunityVault;
    let creator: Signer, owner: Signer, user: Signer;
    let creatorAddr: string, ownerAddr: string, userAddr: string;

    const distributedAmount: BigNumber = BigNumber.from(800000).mul(tenPow18);

    let snapshotId: any;

    before(async () => {
        [creator, owner, user] = await ethers.getSigners();
        creatorAddr = await creator.getAddress();
        ownerAddr = await owner.getAddress();
        userAddr = await user.getAddress();

        bondToken = (await deployContract("ERC20Mock")) as ERC20Mock;
        communityVault = (await deployContract("CommunityVault", [bondToken.address])) as CommunityVault;
    });

    beforeEach(async function () {
        snapshotId = await ethers.provider.send("evm_snapshot", []);
    });

    afterEach(async function () {
        await ethers.provider.send("evm_revert", [snapshotId]);
    });

    describe("General Contract checks", function () {
        it("should be deployed", async function () {
            expect(communityVault.address).to.not.equal(0);
            expect(bondToken.address).to.not.equal(0);
        });
    });

    describe("Contract Tests", function () {
        it("Mint bond tokens in community vault address", async function () {
            await bondToken.mint(communityVault.address, distributedAmount);
            expect(await bondToken.balanceOf(communityVault.address)).to.be.equal(distributedAmount);
        });

        it("should fail if no owner tries to set allowance", async function () {
            await expect(communityVault.connect(user).setAllowance(userAddr, distributedAmount)).to.be.revertedWith(
                "Ownable: caller is not the owner"
            );
        });

        it("should set allowance as owner", async function () {
            await bondToken.mint(communityVault.address, distributedAmount);
            await communityVault.connect(creator).setAllowance(userAddr, distributedAmount);
            expect(await bondToken.allowance(communityVault.address, userAddr)).to.be.equal(distributedAmount);
        });

        it("should transfer ownership", async function () {
            expect(await communityVault.owner()).to.be.equal(creatorAddr);
            await expect(communityVault.connect(creator).transferOwnership(ownerAddr)).to.emit(
                communityVault, "OwnershipTransferred");
            expect(await communityVault.owner()).to.be.equal(ownerAddr);
        });
    });

    describe("Events", function () {
        it("setAllowance emits SetAllowance", async function () {
            await bondToken.mint(communityVault.address, distributedAmount);
            await expect(communityVault.connect(creator).setAllowance(userAddr, distributedAmount))
                .to.emit(communityVault, "SetAllowance");
        });
    });
});
Example #13
Source File: deployExtensions.ts    From index-coop-smart-contracts with Apache License 2.0 5 votes vote down vote up
constructor(deployerSigner: Signer) {
    this._deployerSigner = deployerSigner;
  }
Example #14
Source File: validate-index-params.ts    From index-rebalance-utils with Apache License 2.0 5 votes vote down vote up
task("validate-index-params", "Validates on-chain params match generated params")
.addParam("index", "Index having new positions calculated")
.addParam("rebalance", "Rebalance month")
.setAction(async ({index, rebalance}, hre) => {
  const owner: Signer = (await hre.ethers.getSigners())[0];
  const deployHelper: DeployHelper = new DeployHelper(owner);

  const indexInfo: IndexInfo = indices[index];

  const setToken: SetToken = await deployHelper.setV2.getSetToken(indexInfo.address);
  const indexModule: GeneralIndexModule = await deployHelper.setV2.getGeneralIndexModule(GENERAL_INDEX_MODULE);

  const filepath = indexInfo.path + `${rebalance}.json`;
  const expectedParams: RebalanceReport = JSON.parse(fs.readFileSync(filepath, "utf8"));

  // const positionMultiplier: BigNumber = await setToken.positionMultiplier();

  // if (!positionMultiplier.eq(BigNumber.from(expectedParams.rebalanceParams.positionMultiplier))) {
  //   throw Error("Different position multiplier used!")
  // }

  await Promise.all(expectedParams.summary.map(async (obj, i) => {
    const address = indexInfo.strategyInfo[obj.asset].address;

    const info: any = await indexModule.executionInfo(setToken.address, address);

    // if (!BigNumber.from(obj.newUnit.hex).eq(info.targetUnit)) {
    //   throw Error(`Target unit for ${obj.asset} is wrong should be ${BigNumber.from(obj.newUnit.hex).toString()} instead of ${info.targetUnit}`);
    // }

    const scaledMaxTradeSize = preciseMul(indexInfo.strategyInfo[obj.asset].maxTradeSize, await getTokenDecimals(deployHelper, address));
    if (!scaledMaxTradeSize.eq(info.maxSize)) {
      throw Error(
        `Max trade size for ${obj.asset} is wrong should be ${indexInfo.strategyInfo[obj.asset].maxTradeSize.toString()} instead of ${info.maxSize}`
      );
    }

    if (indexInfo.strategyInfo[obj.asset].exchange != info.exchangeName) {
      throw Error(
        `Exchange for ${obj.asset} is wrong should be ${indexInfo.strategyInfo[obj.asset].exchange} instead of ${info.exchange}`
      );
    }

    if (!indexInfo.strategyInfo[obj.asset].coolOffPeriod.eq(info.coolOffPeriod)) {
      throw Error(
        `Cool off period for ${obj.asset} is wrong should be ${indexInfo.strategyInfo[obj.asset].coolOffPeriod.toString()} instead of ${info.coolOffPeriod}`
      );
    }
  }));
  console.log("All parameters verified!");
});
Example #15
Source File: upgrade-proxy.ts    From openzeppelin-upgrades with MIT License 5 votes vote down vote up
export function makeUpgradeProxy(hre: HardhatRuntimeEnvironment): UpgradeFunction {
  return async function upgradeProxy(proxy, ImplFactory, opts: UpgradeProxyOptions = {}) {
    const proxyAddress = getContractAddress(proxy);

    const { impl: nextImpl } = await deployProxyImpl(hre, ImplFactory, opts, proxyAddress);
    // upgrade kind is inferred above
    const upgradeTo = await getUpgrader(proxyAddress, ImplFactory.signer);
    const call = encodeCall(ImplFactory, opts.call);
    const upgradeTx = await upgradeTo(nextImpl, call);

    const inst = ImplFactory.attach(proxyAddress);
    // @ts-ignore Won't be readonly because inst was created through attach.
    inst.deployTransaction = upgradeTx;
    return inst;
  };

  type Upgrader = (nextImpl: string, call?: string) => Promise<ethers.providers.TransactionResponse>;

  async function getUpgrader(proxyAddress: string, signer: Signer): Promise<Upgrader> {
    const { provider } = hre.network;

    const adminAddress = await getAdminAddress(provider, proxyAddress);
    const adminBytecode = await getCode(provider, adminAddress);

    if (adminBytecode === '0x') {
      // No admin contract: use TransparentUpgradeableProxyFactory to get proxiable interface
      const TransparentUpgradeableProxyFactory = await getTransparentUpgradeableProxyFactory(hre, signer);
      const proxy = TransparentUpgradeableProxyFactory.attach(proxyAddress);

      return (nextImpl, call) => (call ? proxy.upgradeToAndCall(nextImpl, call) : proxy.upgradeTo(nextImpl));
    } else {
      // Admin contract: redirect upgrade call through it
      const manifest = await Manifest.forNetwork(provider);
      const AdminFactory = await getProxyAdminFactory(hre, signer);
      const admin = AdminFactory.attach(adminAddress);
      const manifestAdmin = await manifest.getAdmin();

      if (admin.address !== manifestAdmin?.address) {
        throw new Error('Proxy admin is not the one registered in the network manifest');
      }

      return (nextImpl, call) =>
        call ? admin.upgradeAndCall(proxyAddress, nextImpl, call) : admin.upgrade(proxyAddress, nextImpl);
    }
  }
}
Example #16
Source File: BasicToken.d.ts    From panvala with Apache License 2.0 5 votes vote down vote up
connect(signerOrProvider: Signer | Provider | string): BasicToken;
Example #17
Source File: Auth.d.ts    From nova with GNU Affero General Public License v3.0 5 votes vote down vote up
connect(signerOrProvider: Signer | Provider | string): this;