ethers#Wallet TypeScript Examples

The following examples show how to use ethers#Wallet. 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
signPermission = async (
  method: string,
  vault: Contract,
  owner: Wallet,
  delegateAddress: string,
  tokenAddress: string,
  amount: BigNumberish,
  vaultNonce: BigNumberish,
  chainId?: BigNumberish,
) => {
  // get chainId
  chainId = chainId || (await vault.provider.getNetwork()).chainId
  // craft permission
  const domain = {
    name: 'UniversalVault',
    version: '1.0.0',
    chainId: chainId,
    verifyingContract: vault.address,
  }
  const types = {} as Record<string, TypedDataField[]>
  types[method] = [
    { name: 'delegate', type: 'address' },
    { name: 'token', type: 'address' },
    { name: 'amount', type: 'uint256' },
    { name: 'nonce', type: 'uint256' },
  ]
  const value = {
    delegate: delegateAddress,
    token: tokenAddress,
    amount: amount,
    nonce: vaultNonce,
  }
  // sign permission
  // todo: add fallback if wallet does not support eip 712 rpc
  const signedPermission = await owner._signTypedData(domain, types, value)
  // return
  return signedPermission
}
Example #2
Source File: bid_utils.ts    From shoyu with MIT License 7 votes vote down vote up
export async function bid2(
    exchange: Contract,
    txSigner: Wallet,
    askOrder: AskOrder,
    bidAmount: BigNumberish,
    bidPrice: BigNumberish,
    bidRecipient: string
) {
    await exchange
        .connect(txSigner)
        [
            "bid((address,address,address,uint256,uint256,address,address,address,uint256,bytes,uint8,bytes32,bytes32),uint256,uint256,address,address)"
        ](askOrder, bidAmount, bidPrice, bidRecipient, ethers.constants.AddressZero);
}
Example #3
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
// Event Emitter (ish)
  addEventListener = (eventName: string, listener: Listener, filter?: any): string => {
    const id = Wallet.createRandom().address;
    const eventCallBack = (data: any): void =>
      listener({
        subscription: id,
        result: data
      });

    this._listeners[eventName] = this._listeners[eventName] || [];
    this._listeners[eventName].push({ cb: eventCallBack, filter, id });

    return id;
  };
Example #4
Source File: sniper.ts    From pool-sniper with The Unlicense 6 votes vote down vote up
/**
   * Updates token and purchase details + sets up RPC
   * @param {string} tokenAddress of token to purchase
   * @param {string} factoryAddress of Uniswap V2 Factory
   * @param {string} rpcEndpoint for network
   * @param {string} privateKey of purchasing wallet
   * @param {string} purchaseAmount to swap with (input)
   * @param {string} gasPrice to pay
   * @param {number} slippage for trade execution
   * @param {boolean} testnet true if testnet
   */
  constructor(
    tokenAddress: string,
    factoryAddress: string,
    rpcEndpoint: string,
    privateKey: string,
    purchaseAmount: string,
    gasPrice: string,
    slippage: number,
    testnet: boolean
  ) {
    // Setup networking + wallet
    this.rpc = new providers.JsonRpcProvider(rpcEndpoint);
    this.wallet = new Wallet(privateKey, this.rpc);

    // Setup token details
    this.tokenAddress = utils.getAddress(tokenAddress); // Normalize address
    this.factory = new Contract(factoryAddress, ABI_UniswapV2Factory, this.rpc);
    this.purchaseAmount = purchaseAmount;
    this.gasPrice = utils.parseUnits(gasPrice, "gwei");
    this.slippage = slippage;
    this.testnet = testnet;
  }
Example #5
Source File: fixtures.ts    From apeswap-swap-core with GNU General Public License v3.0 6 votes vote down vote up
export async function pairFixture([wallet]: Wallet[], provider: Web3Provider): Promise<PairFixture> {
  const { factory } = await factoryFixture([wallet], provider)

  const tokenA = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)
  const tokenB = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)

  await factory.createPair(tokenA.address, tokenB.address, overrides)
  const pairAddress = await factory.getPair(tokenA.address, tokenB.address)
  const pair = new Contract(pairAddress, JSON.stringify(ApePair.abi), provider).connect(wallet)

  const token0Address = (await pair.token0()).address
  const token0 = tokenA.address === token0Address ? tokenA : tokenB
  const token1 = tokenA.address === token0Address ? tokenB : tokenA

  return { factory, token0, token1, pair }
}
Example #6
Source File: utils.ts    From panvala with Apache License 2.0 6 votes vote down vote up
export function getWallet() {
  return Wallet.fromMnemonic(mnemonic);
}
Example #7
Source File: ERC20Service.ts    From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
async approve(
        tokenAddr: string,
        spenderAddr: string,
        amount: Big,
        from: Wallet,
        overrides?: Overrides,
    ): Promise<void> {
        const token = this.createErc20Contract(tokenAddr, from)
        const scaledAmount = await this.toScaled(tokenAddr, amount)
        const tx = await token.functions.approve(spenderAddr, scaledAmount, {
            ...overrides,
        })
        const receipt = await tx.wait()
        if (receipt.status !== 1) throw new Error(`transferError:${tx.hash}`)
    }
Example #8
Source File: encoder.test.ts    From useDApp with MIT License 6 votes vote down vote up
describe('Multicall encoder', () => {
  const address = Wallet.createRandom().address

  const calls = [
    ...[...Array(10)].map(() => ethersAbi.encodeFunctionData('getCurrentBlockGasLimit')),
    ...[...Array(10)].map((_, i) => ethersAbi.encodeFunctionData('getBlockHash', [i])),
  ]

  it('Properly encodes', () => {
    const calldata = ethersAbi.encodeFunctionData('aggregate', [calls.map((calldata) => [address, calldata])])

    const manual = encodeAggregate(calls.map((calldata) => [address, calldata]))

    expect(manual).to.eq(calldata)
  })

  it('bench ethers', () => {
    const callsLong = [...Array(20)].flatMap(() => calls)
    formatBench(
      bench(() => {
        ethersAbi.encodeFunctionData('aggregate', [callsLong.map((calldata) => [address, calldata])])
      })
    )
  })

  it('bench manual', () => {
    const callsLong = [...Array(20)].flatMap(() => calls)
    formatBench(
      bench(() => {
        encodeAggregate(callsLong.map((calldata) => [address, calldata]))
      })
    )
  })
})
Example #9
Source File: utils.ts    From hypervisor with The Unlicense 6 votes vote down vote up
signPermitEIP2612 = async (
  owner: Wallet,
  token: Contract,
  spenderAddress: string,
  value: BigNumberish,
  deadline: BigNumberish,
  nonce?: BigNumberish,
) => {
  // get nonce
  nonce = nonce || (await token.nonces(owner.address))
  // get chainId
  const chainId = (await token.provider.getNetwork()).chainId
  // get domain
  const domain = {
    name: 'Uniswap V2',
    version: '1',
    chainId: chainId,
    verifyingContract: token.address,
  }
  // get types
  const types = {} as Record<string, TypedDataField[]>
  types['Permit'] = [
    { name: 'owner', type: 'address' },
    { name: 'spender', type: 'address' },
    { name: 'value', type: 'uint256' },
    { name: 'nonce', type: 'uint256' },
    { name: 'deadline', type: 'uint256' },
  ]
  // get values
  const values = {
    owner: owner.address,
    spender: spenderAddress,
    value: value,
    nonce: nonce,
    deadline: deadline,
  }
  // sign permission
  // todo: add fallback if wallet does not support eip 712 rpc
  const signedPermission = await owner._signTypedData(domain, types, values)
  // split signature
  const sig = splitSignature(signedPermission)
  // return
  return [
    values.owner,
    values.spender,
    values.value,
    values.deadline,
    sig.v,
    sig.r,
    sig.s,
  ]
}
Example #10
Source File: wallet.ts    From noether with Apache License 2.0 6 votes vote down vote up
save = async (wallet: Wallet, filename: string) => {
    // create encrypted structured
    const password = await prompts({
        type: "password",
        name: "value",
        message: "new password",
    });

    const passwordRepeat = await prompts({
        type: "password",
        name: "value",
        message: "re-type password",
    });

    // check if passwords match, raise error if not
    if (password.value !== passwordRepeat.value) {
        throw new Error("passwords don't match");
    }

    const json = await wallet.encrypt(password.value);

    // save key V3
    log.info(`saving encrypted wallet to ${filename}`);
    fs.writeFileSync(filename, json);
}
Example #11
Source File: manager.ts    From celo-web-wallet with MIT License 6 votes vote down vote up
function* loadLocalAccount(account: StoredAccountData, password?: string) {
  logger.debug('Loading a local account')
  if (!password) {
    const cachedPassword = getPasswordCache()
    if (cachedPassword) password = cachedPassword.password
    else throw new Error('Must unlock account with password before importing')
  }

  const { encryptedMnemonic, derivationPath } = account
  if (!password) throw new Error('Password required for local accounts')
  if (!encryptedMnemonic) throw new Error('Expected local account to have mnemonic')
  const mnemonic = yield* call(decryptMnemonic, encryptedMnemonic, password)

  const wallet = Wallet.fromMnemonic(mnemonic, derivationPath)
  if (!areAddressesEqual(wallet.address, account.address))
    throw new Error('Address from mnemonic does not match desired address')

  if (!hasPasswordCached()) setPasswordCache(password)
  yield* call(activateLocalAccount, wallet)
}
Example #12
Source File: Blockchain.ts    From client with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Loads the game contract, which is responsible for updating the state of the game.
 */
export async function loadDiamondContract<T extends Contract>(
  address: string,
  provider: providers.JsonRpcProvider,
  signer?: Wallet
): Promise<T> {
  const abi = await fetch(diamondContractAbiUrl).then((r) => r.json());

  return createContract<T>(address, abi, provider, signer);
}
Example #13
Source File: setup.ts    From integration-tests with MIT License 6 votes vote down vote up
getEnvironment = async (): Promise<{
  l1Provider: JsonRpcProvider
  l2Provider: JsonRpcProvider
  l1Wallet: Wallet
  l2Wallet: Wallet
  AddressManager: Contract
  watcher: Watcher
}> => {
  const l1Provider = new JsonRpcProvider(Config.L1NodeUrlWithPort())
  const l2Provider = getl2Provider()
  const l1Wallet = new Wallet(Config.DeployerPrivateKey(), l1Provider)
  const l2Wallet = new Wallet(Config.DeployerPrivateKey(), l2Provider)

  const addressManagerAddress = Config.AddressResolverAddress()
  const addressManagerInterface = getContractInterface('Lib_AddressManager')
  const AddressManager = new Contract(
    addressManagerAddress,
    addressManagerInterface,
    l1Provider
  )

  const watcher = await initWatcher(l1Provider, l2Provider, AddressManager)

  return {
    l1Provider,
    l2Provider,
    l1Wallet,
    l2Wallet,
    AddressManager,
    watcher,
  }
}
Example #14
Source File: 12-exchange.ts    From etherspot-sdk with MIT License 6 votes vote down vote up
async function main(): Promise<void> {
  const wallet = Wallet.createRandom();
  const sdk = new Sdk(wallet, {
    env: EnvNames.MainNets,
    networkName: NetworkNames.Mainnet,
  });

  const exchangeSupportedAssets = await sdk.getExchangeSupportedAssets({ page: 1, limit: 100 });
  logger.log('found exchange supported assets', exchangeSupportedAssets.items.length);

  // NOTE: use ethers.constants.AddressZero for ETH
  // const fromTokenAddress = '0xD71eCFF9342A5Ced620049e616c5035F1dB98620'; // sEUR
  // const toTokenAddress = '0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb'; // sETH
  const fromTokenAddress = '0xe3818504c1b32bf1557b16c238b2e01fd3149c17'; // PLR
  const toTokenAddress = constants.AddressZero; // ETH
  const fromAmount = '5000000000000000000000';

  logger.log(
    'exchange offers',
    await sdk.getExchangeOffers({
      fromTokenAddress,
      toTokenAddress,
      fromAmount: BigNumber.from(fromAmount),
    }),
  );
}
Example #15
Source File: index.ts    From forta-bot-sdk with MIT License 6 votes vote down vote up
export default function provideDisable(
  appendToFile: AppendToFile,
  getCredentials: GetCredentials,
  agentRegistry: AgentRegistry,
  agentId: string,
): CommandHandler {
  assertExists(appendToFile, 'appendToFile')
  assertExists(getCredentials, 'getCredentials')
  assertExists(agentRegistry, 'agentRegistry')
  assertIsNonEmptyString(agentId, 'agentId')

  return async function disable() {
    const agentExists = await agentRegistry.agentExists(agentId)
    if (!agentExists) {
      throw new Error(`agent id ${agentId} does not exist`)
    }

    const isAgentEnabled = await agentRegistry.isEnabled(agentId)
    if (!isAgentEnabled) {
      console.log(`agent id ${agentId} is already disabled`)
      return
    }

    const { privateKey } = await getCredentials()

    console.log('disabling agent...')
    const fromWallet = new Wallet(privateKey)
    await agentRegistry.disableAgent(fromWallet, agentId)

    const logMessage = `successfully disabled agent id ${agentId}`
    console.log(logMessage)
    appendToFile(`${new Date().toUTCString()}: ${logMessage}`, 'publish.log')
  }
}
Example #16
Source File: fixtures.ts    From pancake-swap-testnet with MIT License 6 votes vote down vote up
export async function pairFixture(provider: Web3Provider, [wallet]: Wallet[]): Promise<PairFixture> {
  const { factory } = await factoryFixture(provider, [wallet])

  const tokenA = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)
  const tokenB = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)

  await factory.createPair(tokenA.address, tokenB.address, overrides)
  const pairAddress = await factory.getPair(tokenA.address, tokenB.address)
  const pair = new Contract(pairAddress, JSON.stringify(PancakePair.abi), provider).connect(wallet)

  const token0Address = (await pair.token0()).address
  const token0 = tokenA.address === token0Address ? tokenA : tokenB
  const token1 = tokenA.address === token0Address ? tokenB : tokenA

  return { factory, token0, token1, pair }
}
Example #17
Source File: utils.ts    From core with GNU General Public License v3.0 6 votes vote down vote up
export async function approveCurrency(
  currency: string,
  spender: string,
  owner: Wallet
) {
  await BaseErc20Factory.connect(currency, owner).approve(spender, MaxUint256);
}
Example #18
Source File: currency.ts    From zora-v1-subgraph with MIT License 6 votes vote down vote up
export async function deployCurrency(
  wallet: Wallet,
  name: string = 'DAI',
  symbol: string = 'DAI'
): Promise<string> {
  const bidCurrencyDeployTx = await new BaseErc20Factory(wallet).deploy(
    name,
    symbol,
    BigNumber.from(18)
  )
  await bidCurrencyDeployTx.deployed()
  return bidCurrencyDeployTx.address
}
Example #19
Source File: fixtures.ts    From staking-factory with MIT License 6 votes vote down vote up
export async function stakingRewardsFixture([wallet]: Wallet[]): Promise<StakingRewardsFixture> {
  const rewardsDistribution = wallet.address
  const rewardsToken = await deployContract(wallet, TestERC20, [expandTo18Decimals(1000000)])
  const stakingToken = await deployContract(wallet, UniswapV2ERC20, [expandTo18Decimals(1000000)])

  const stakingRewards = await deployContract(wallet, StakingRewards, [
    rewardsDistribution,
    rewardsToken.address,
    stakingToken.address,
  ])

  return { stakingRewards, rewardsToken, stakingToken }
}
Example #20
Source File: bid_utils.ts    From shoyu with MIT License 6 votes vote down vote up
export async function bid1(exchange: Contract, txSigner: Wallet, askOrder: AskOrder, bidOrder: BidOrder) {
    await exchange
        .connect(txSigner)
        [
            "bid((address,address,address,uint256,uint256,address,address,address,uint256,bytes,uint8,bytes32,bytes32),(bytes32,address,uint256,uint256,address,address,uint8,bytes32,bytes32))"
        ](askOrder, bidOrder);
}
Example #21
Source File: factory.ts    From hubble-contracts with MIT License 6 votes vote down vote up
static new(options: GroupOptions) {
        const initialStateID = options.initialStateID || 0;
        const initialPubkeyID = options.initialPubkeyID || 0;
        const stateProvider = options.stateProvider || nullProvider;
        const mnemonic = options.mnemonic ?? DEFAULT_MNEMONIC;
        const users: User[] = [];
        for (let i = 0; i < options.n; i++) {
            const wallet = Wallet.fromMnemonic(mnemonic, `m/44'/60'/0'/0/${i}`);
            const stateID = initialStateID + i;
            const pubkeyID = initialPubkeyID + i;
            users.push(
                User.new(stateID, pubkeyID, options.domain, wallet.privateKey)
            );
        }
        return new this(users, stateProvider);
    }
Example #22
Source File: fixtures.ts    From vvs-swap-core with GNU General Public License v3.0 6 votes vote down vote up
export async function pairFixture([wallet]: Wallet[], provider: Web3Provider): Promise<PairFixture> {
  const { factory } = await factoryFixture([wallet], provider)

  const tokenA = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)
  const tokenB = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)

  await factory.createPair(tokenA.address, tokenB.address, overrides)
  const pairAddress = await factory.getPair(tokenA.address, tokenB.address)
  const pair = new Contract(pairAddress, JSON.stringify(VVSPair.abi), provider).connect(wallet)

  const token0Address = (await pair.token0()).address
  const token0 = tokenA.address === token0Address ? tokenA : tokenB
  const token1 = tokenA.address === token0Address ? tokenB : tokenA

  return { factory, token0, token1, pair }
}
Example #23
Source File: sniper.ts    From pool-sniper with The Unlicense 5 votes vote down vote up
// Sniping wallet
  wallet: Wallet;
Example #24
Source File: fixtures.ts    From apeswap-swap-core with GNU General Public License v3.0 5 votes vote down vote up
export async function factoryFixture([wallet]: Wallet[], _: Web3Provider): Promise<FactoryFixture> {
  const factory = await deployContract(wallet, ApeFactory, [wallet.address], overrides)
  return { factory }
}
Example #25
Source File: polls.ts    From panvala with Apache License 2.0 5 votes vote down vote up
export async function signResponse(wallet: Wallet, response: IDBPollResponse): Promise<string> {
  const message = generateMessage(response);
  // console.log(`signing message '${message}'`);
  return wallet.signMessage(message);
}
Example #26
Source File: Arbitrageur.ts    From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// default 0.1%
    private readonly arbitrageur: Wallet
Example #27
Source File: encoder.test.ts    From useDApp with MIT License 5 votes vote down vote up
describe('Multicall v2 encoder', () => {
  const address = Wallet.createRandom().address

  const calls = [
    ...[...Array(10)].map(() => ethersAbi.encodeFunctionData('getCurrentBlockGasLimit')),
    ...[...Array(10)].map((_, i) => ethersAbi.encodeFunctionData('getBlockHash', [i])),
  ]

  it('Properly encodes', () => {
    const calldata = ethersAbi.encodeFunctionData('tryAggregate', [true, calls.map((calldata) => [address, calldata])])

    const manual = encodeTryAggregate(
      true,
      calls.map((calldata) => [address, calldata])
    )

    expect(manual).to.eq(calldata)
  })

  it('bench ethers', () => {
    const callsLong = [...Array(20)].flatMap(() => calls)
    formatBench(
      bench(() => {
        ethersAbi.encodeFunctionData('tryAggregate', [true, callsLong.map((calldata) => [address, calldata])])
      })
    )
  })

  it('bench manual', () => {
    const callsLong = [...Array(20)].flatMap(() => calls)
    formatBench(
      bench(() => {
        encodeTryAggregate(
          true,
          callsLong.map((calldata) => [address, calldata])
        )
      })
    )
  })
})
Example #28
Source File: wallet.ts    From noether with Apache License 2.0 5 votes vote down vote up
loadFromSeed = async (seed: string): Promise<Wallet> => {
    return new Wallet(HDNode.fromSeed(`0x${seed}`));
}
Example #29
Source File: manager.ts    From celo-web-wallet with MIT License 5 votes vote down vote up
export function createRandomAccount() {
  const entropy = utils.randomBytes(32)
  const mnemonic = utils.entropyToMnemonic(entropy)
  const derivationPath = CELO_DERIVATION_PATH + '/0'
  return Wallet.fromMnemonic(mnemonic, derivationPath)
}