How to use the ethers/utils.bigNumberify function in ethers

To help you get started, we’ve selected a few ethers examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github magmo / apps / packages / wallet / src / redux / protocols / new-ledger-funding / player-a / __tests__ / scenarios.ts View on Github external
} from '../../../../../domain/commitments/__tests__';
import { success } from '../../../indirect-defunding/states';
import { NEW_LEDGER_FUNDING_PROTOCOL_LOCATOR } from '../../reducer';

// -----------
// Commitments
// -----------
const processId = 'processId';
const protocolLocator = NEW_LEDGER_FUNDING_PROTOCOL_LOCATOR;

const twoThree = [
  { address: asAddress, wei: bigNumberify(2).toHexString() },
  { address: bsAddress, wei: bigNumberify(3).toHexString() },
];

const fiveToApp = [{ address: channelId, wei: bigNumberify(5).toHexString() }];

const app0 = appCommitment({ turnNum: 0, balances: twoThree });
const app1 = appCommitment({ turnNum: 1, balances: twoThree });
const app2 = appCommitment({ turnNum: 2, balances: twoThree });
const app3 = appCommitment({ turnNum: 3, balances: twoThree });

const ledger0 = ledgerCommitment({ turnNum: 0, balances: twoThree });
const ledger1 = ledgerCommitment({ turnNum: 1, balances: twoThree });
const ledger2 = ledgerCommitment({ turnNum: 2, balances: twoThree });
const ledger3 = ledgerCommitment({ turnNum: 3, balances: twoThree });
const ledger4 = ledgerCommitment({ turnNum: 4, balances: twoThree, proposedBalances: fiveToApp });
const ledger5 = ledgerCommitment({ turnNum: 5, balances: fiveToApp });

// Channels

const props = { channelId, ledgerId, processId };
github magmo / apps / packages / rps / src / redux / game / reducer.ts View on Github external
messageState: {
        walletOutbox: { type: 'RESPOND_TO_CHALLENGE', data: propose },
      },
    };
  } else {
    // We received a challenge so we need to take the commitment that the opponent sent us
    // This will be on the actionToRetry that we haven't handled yet
    if (messageState.actionToRetry) {
      const opponentCommitment = messageState.actionToRetry.commitment;

      if (opponentCommitment.positionType !== PositionType.Proposed) {
        return { gameState, messageState };
      }
      const { preCommit } = opponentCommitment;
      const { allocation: allocation, roundBuyIn } = gameState;
      const aBal = bigNumberify(allocation[0])
        .sub(bigNumberify(roundBuyIn))
        .toHexString();
      const bBal = bigNumberify(allocation[1])
        .add(bigNumberify(roundBuyIn))
        .toHexString();
      const newAllocation = [aBal, bBal] as [string, string];

      const newGameStateB = states.waitForRevealB({
        ...gameState,
        preCommit,
        myWeapon: action.weapon,
        player: Player.PlayerB,
      });
      const challengeCommitment = rpsCommitmentHelper.accept({
        ...gameState,
        preCommit,
github magmo / apps / packages / rps / src / components / OpenGameCard.tsx View on Github external
render() {
    // Generate a random number from 0 to MaxInt
    const randomChannelNonce = Math.floor(Math.random() * 2147483647) + 1;
    const { openGame, joinOpenGame } = this.props;
    const joinThisGame = () =>
      joinOpenGame(openGame.name, openGame.address, randomChannelNonce, openGame.stake);

    const stake = openGame.stake;
    const buyin = bigNumberify(openGame.stake)
      .mul(5)
      .toHexString();
    return (
      <div>
        <div>
          <div>vs</div> <div>{openGame.name}</div>
        </div>
        <div>
          <div>
            <div>Game Buy In:</div>
            <div>{web3Utils.fromWei(buyin, 'ether')}</div>
            <div>ETH</div>
          </div>
          <svg>
            <line y2="14" x2="0" y1="0" x1="0"></line>
          </svg></div></div>
github magmo / apps / packages / wallet / src / contract-tests / test-utils.ts View on Github external
createRespondWithMoveTransaction,
} from '../utils/transaction-generator';
import { signCommitment } from '../domain';
import testGameArtifact from '../../build/contracts/TestGame.json';
import { bigNumberify } from 'ethers/utils';
import { channelID, Channel } from 'fmg-core/lib/channel';
import { ADJUDICATOR_ADDRESS } from '../constants';
import { ADDRESS_ZERO } from 'fmg-core';
export function getLibraryAddress(networkId) {
  return testGameArtifact.networks[networkId].address;
}
export const fiveFive = [bigNumberify(5).toHexString(), bigNumberify(5).toHexString()] as [
  string,
  string
];
export const fourSix = [bigNumberify(4).toHexString(), bigNumberify(6).toHexString()] as [
  string,
  string
];

export const defaultDepositAmount = fiveFive[0];

export async function getChannelId(provider, channelNonce, participantA, participantB) {
  const network = await provider.getNetwork();
  const networkId = network.chainId;
  const libraryAddress = getLibraryAddress(networkId);
  return channelID({
    channelType: libraryAddress,
    nonce: channelNonce,
    participants: [participantA.address, participantB.address],
  });
}
github magmo / apps / packages / rps / src / core / test-scenarios.ts View on Github external
import { Weapon } from './rps-commitment';
import { bigNumberify } from 'ethers/utils';
import { Channel } from 'fmg-core';

export const libraryAddress = '0x' + '1'.repeat(40);
const channelNonce = 4;
const asPrivateKey = '0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d';
const asAddress = '0x5409ED021D9299bf6814279A6A1411A7e866A631';
const bsPrivateKey = '0x5d862464fe9303452126c8bc94274b8c5f9874cbd219789b3eb2128075a76f72';
const bsAddress = '0x6Ecbe1DB9EF729CBe972C83Fb886247691Fb6beb';
const participants: [string, string] = [asAddress, bsAddress];
const roundBuyIn = bigNumberify(1).toHexString();
const fiveFive = [bigNumberify(5).toHexString(), bigNumberify(5).toHexString()] as [string, string];
const sixFour = [bigNumberify(6).toHexString(), bigNumberify(4).toHexString()] as [string, string];
const fourSix = [bigNumberify(4).toHexString(), bigNumberify(6).toHexString()] as [string, string];
const nineOne = [bigNumberify(9).toHexString(), bigNumberify(1).toHexString()] as [string, string];
const eightTwo = [bigNumberify(8).toHexString(), bigNumberify(2).toHexString()] as [string, string];
const tenZero = [bigNumberify(10).toHexString(), bigNumberify(0).toHexString()] as [string, string];
const aWeapon = Weapon.Rock;
const salt = randomHex(64);
const preCommit = commitmentHelper.hashCommitment(aWeapon, salt);
const bWeapon = Weapon.Scissors;

const channel: Channel = { channelType: libraryAddress, nonce: channelNonce, participants };

const base = {
  channel,
  destination: participants,
  commitmentCount: 0,
};

const baseWithBuyIn = {
github ConnextProject / indra / modules / node / src / channel / channel.service.spec.ts View on Github external
it("should find payment profiles for a channel", async () => {
    const tokenAddress = mkAddress("0xeee");

    const channel = await createTestChannel(channelRepository);

    let profile = new PaymentProfile();
    profile.amountToCollateralize = bigNumberify(2000);
    profile.minimumMaintainedCollateral = bigNumberify(600);
    profile.assetId = AddressZero;
    await channelRepository.addPaymentProfileToChannel(channel.userPublicIdentifier, profile);

    profile = new PaymentProfile();
    profile.amountToCollateralize = bigNumberify(3000);
    profile.minimumMaintainedCollateral = bigNumberify(1000);
    profile.assetId = tokenAddress;
    await channelRepository.addPaymentProfileToChannel(channel.userPublicIdentifier, profile);

    profile = await channelRepository.getPaymentProfileForChannelAndToken(
      channel.userPublicIdentifier,
    );

    expect(profile.amountToCollateralize).toStrictEqual(bigNumberify(2000));
    expect(profile.minimumMaintainedCollateral).toStrictEqual(bigNumberify(600));
github ConnextProject / indra / modules / client / src / connext.ts View on Github external
public matchTx = (
    givenTransaction: Transaction | undefined,
    expected: CFCoreTypes.MinimalTransaction,
  ): boolean => {
    return (
      givenTransaction &&
      givenTransaction.to === expected.to &&
      bigNumberify(givenTransaction.value).eq(expected.value) &&
      givenTransaction.data === expected.data
    );
  };
github AdExNetwork / adex-platform / src / services / smart-contracts / actions / identity.js View on Github external
export async function getIdentityTxnsTotalFees(txnsByFeeToken) {
	const feeTokenWhitelist = selectFeeTokenWhitelist()
	const bigZero = bigNumberify('0')
	const feesData = Object.values(txnsByFeeToken)
		.reduce((all, byFeeToken) => all.concat(byFeeToken), [])
		.reduce(
			(result, tx) => {
				const txFeeAmount = bigNumberify(tx.feeAmount)
				result.total = result.total.add(txFeeAmount)

				result.byToken[tx.feeTokenAddr] = (
					result.byToken[tx.feeTokenAddr] || bigZero
				).add(txFeeAmount)

				return result
			},
			{ total: bigZero, byToken: {} }
		)
github JoinColony / purser / modules / node_modules / @colony / purser-software / staticMethods.js View on Github external
value,
    inputData,
  } = transactionObjectValidator(transactionObject);
  try {
    const signedTransaction: string = await callback(
      Object.assign(
        {},
        {
          /*
           * Ethers needs it's own "proprietary" version of bignumber to work.
           */
          gasPrice: bigNumberify(gasPrice.toString()),
          /*
           * Ethers needs it's own "proprietary" version of bignumber to work.
           */
          gasLimit: bigNumberify(gasLimit.toString()),
          chainId,
          nonce,
          /*
           * Ethers needs it's own "proprietary" version of bignumber to work.
           */
          value: bigNumberify(value.toString()),
          data: hexSequenceNormalizer(inputData),
        },
        /*
         * Only send (and normalize) the destination address if one was
         * provided in the initial transaction object.
         */
        to ? { to: addressNormalizer(to) } : {},
      ),
    );
    return hexSequenceNormalizer(signedTransaction);
github magmo / apps / packages / rps / src / redux / game / reducer.ts View on Github external
function insufficientFunds(allocation: string[], roundBuyIn: string): boolean {
  const aBal = bigNumberify(allocation[0]);
  const bBal = bigNumberify(allocation[1]);
  const buyIn = bigNumberify(roundBuyIn);

  return aBal.lt(buyIn) || bBal.lt(buyIn);
}