Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test to showcase that job-creator would profit from liars #442

Merged
merged 28 commits into from
Oct 3, 2024

Conversation

kongzii
Copy link
Contributor

@kongzii kongzii commented Sep 26, 2024

No description provided.

Copy link

coderabbitai bot commented Sep 26, 2024

Walkthrough

The changes introduce a new integration test in the file test_stealing_on_markets.py, which simulates a scenario involving two accounts in a prediction market. Account A creates a market while Account B attempts to sabotage it by purchasing tokens. The test validates the market's integrity through various actions, such as liquidity removal and market resolution, ensuring that the financial outcomes align with expected behaviors for both accounts.

Changes

File Path Change Summary
tests_integration_with_local_chain/markets/omen/test_stealing_on_markets.py New test function added: def test_stealing_on_markets(accounts: list[TestAccount], local_web3: Web3) -> None. Introduces a comprehensive integration test for market interactions between two accounts.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

f"Account A (job creator) ending difference: {ending_balance_A - starting_balance_A}."
)
print(
f"Account B (attacker) ending difference: {ending_balance_B - starting_balance_B}."
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests in CI are failing atm, but locally:

clear && pytest tests_integration_with_local_chain -k test_stealing_on_markets -vvv -s

Screenshot by Dropbox Capture

Screenshot by Dropbox Capture

print(f"{api_keys_A.bet_from_address=}, {api_keys_B.bet_from_address=}")

# Update chain's state with a dummy block.
DebuggingContract().inc(api_keys_A, local_web3)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's this for? Something to do with resetting the now time on the simulated chain?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah exactly, explained in detail here #437 (comment)

I abstracted this away to mint_new_block function to make it clear in the code.

Copy link
Contributor

@evangriffiths evangriffiths left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

Base automatically changed from peter/events to main October 1, 2024 08:59
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (3)
tests_integration_with_local_chain/markets/omen/test_stealing_on_markets.py (3)

95-95: Typo in comment: "accout" should be "account".

There's a typographical error in the comment. Correcting it improves readability.

Apply this diff to correct the typo:

-    # Buy YES tokens from accout B (attacker) -- removing profit from any real agent that'd like to complete the job.
+    # Buy YES tokens from account B (attacker) -- removing profit from any real agent that'd like to complete the job.

113-113: Typo in comment: "loose" should be "lose".

The word "loose" in the comment should be "lose" to convey the correct meaning.

Apply this diff to correct the typo:

-    # Account A detects this and removes remaining liquidity, so the attacker is locked-in and will loose money unless he completes the job.
+    # Account A detects this and removes remaining liquidity, so the attacker is locked-in and will lose money unless he completes the job.

207-207: Typo in assertion message: "completors" should be "completers".

The term "completors" is not standard. Replacing it with "completers" improves clarity.

This is already corrected in the previous diff.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1aa20d4 and 959e531.

📒 Files selected for processing (1)
  • tests_integration_with_local_chain/markets/omen/test_stealing_on_markets.py (1 hunks)
🧰 Additional context used
🪛 Ruff
tests_integration_with_local_chain/markets/omen/test_stealing_on_markets.py

105-105: Local variable balance_after_buying_A is assigned to but never used

Remove assignment to unused variable balance_after_buying_A

(F841)


115-115: Local variable balance_after_removing_funding_B is assigned to but never used

Remove assignment to unused variable balance_after_removing_funding_B

(F841)


126-126: Local variable e_buying is assigned to but never used

Remove assignment to unused variable e_buying

(F841)


136-136: Local variable e_selling is assigned to but never used

Remove assignment to unused variable e_selling

(F841)

Comment on lines +205 to +207
assert (
ending_balance_B < starting_balance_A
), "Assumption was that B will loose the money he gambled by trying to steal from real job completors."
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix assertion to compare B's ending balance with B's starting balance.

The assertion compares ending_balance_B with starting_balance_A, which is likely incorrect. It should compare ending_balance_B with starting_balance_B to verify that B has lost money.

Apply this diff to correct the assertion and fix the typo in the assertion message:

-    assert (
-        ending_balance_B < starting_balance_A
-    ), "Assumption was that B will loose the money he gambled by trying to steal from real job completors."
+    assert (
+        ending_balance_B < starting_balance_B
+    ), "Assumption was that B will lose the money he gambled by trying to steal from real job completers."
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
assert (
ending_balance_B < starting_balance_A
), "Assumption was that B will loose the money he gambled by trying to steal from real job completors."
assert (
ending_balance_B < starting_balance_B
), "Assumption was that B will lose the money he gambled by trying to steal from real job completers."

), "Balance after removing the liquidity should be higher than after market creation (because some liquidity can be withdrawn right away), but lower than before market creation (because some liquidity is now locked for the attacker's bet)"

# Buying or selling tokens after the liquidity is removed will fail.
with pytest.raises(Exception) as e_buying:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Unused exception variable e_buying.

The variable e_buying is assigned the exception but not used. If you don't need to inspect the exception, you can omit the as clause.

Apply this diff to remove the unused variable:

-    with pytest.raises(Exception) as e_buying:
+    with pytest.raises(Exception):
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
with pytest.raises(Exception) as e_buying:
with pytest.raises(Exception):
🧰 Tools
🪛 Ruff

126-126: Local variable e_buying is assigned to but never used

Remove assignment to unused variable e_buying

(F841)

Comment on lines 105 to 108
balance_after_buying_A, balance_after_buying_B = (
get_balances(api_keys_A.bet_from_address, local_web3).total,
get_balances(api_keys_B.bet_from_address, local_web3).total,
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove unused variable balance_after_buying_A.

The variable balance_after_buying_A is assigned but never used. Removing it cleans up the code and avoids confusion.

Apply this diff to remove the unused variable:

-    balance_after_buying_A, balance_after_buying_B = (
-        get_balances(api_keys_A.bet_from_address, local_web3).total,
-        get_balances(api_keys_B.bet_from_address, local_web3).total,
-    )
+    balance_after_buying_B = get_balances(api_keys_B.bet_from_address, local_web3).total
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
balance_after_buying_A, balance_after_buying_B = (
get_balances(api_keys_A.bet_from_address, local_web3).total,
get_balances(api_keys_B.bet_from_address, local_web3).total,
)
balance_after_buying_B = get_balances(api_keys_B.bet_from_address, local_web3).total
🧰 Tools
🪛 Ruff

105-105: Local variable balance_after_buying_A is assigned to but never used

Remove assignment to unused variable balance_after_buying_A

(F841)

web3=local_web3,
)
sell_yes_for_b = xdai_type(1)
with pytest.raises(Exception) as e_selling:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Unused exception variable e_selling.

Similarly, e_selling is assigned but not used. You can remove it if it's not needed.

Apply this diff to remove the unused variable:

-    with pytest.raises(Exception) as e_selling:
+    with pytest.raises(Exception):
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
with pytest.raises(Exception) as e_selling:
with pytest.raises(Exception):
🧰 Tools
🪛 Ruff

136-136: Local variable e_selling is assigned to but never used

Remove assignment to unused variable e_selling

(F841)

Comment on lines 115 to 118
balance_after_removing_funding_A, balance_after_removing_funding_B = (
get_balances(api_keys_A.bet_from_address, local_web3).total,
get_balances(api_keys_B.bet_from_address, local_web3).total,
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove unused variable balance_after_removing_funding_B.

The variable balance_after_removing_funding_B is assigned but never used. Removing it tidies up the code.

Apply this diff to remove the unused variable:

-    balance_after_removing_funding_A, balance_after_removing_funding_B = (
-        get_balances(api_keys_A.bet_from_address, local_web3).total,
-        get_balances(api_keys_B.bet_from_address, local_web3).total,
-    )
+    balance_after_removing_funding_A = get_balances(api_keys_A.bet_from_address, local_web3).total
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
balance_after_removing_funding_A, balance_after_removing_funding_B = (
get_balances(api_keys_A.bet_from_address, local_web3).total,
get_balances(api_keys_B.bet_from_address, local_web3).total,
)
balance_after_removing_funding_A = get_balances(api_keys_A.bet_from_address, local_web3).total
🧰 Tools
🪛 Ruff

115-115: Local variable balance_after_removing_funding_B is assigned to but never used

Remove assignment to unused variable balance_after_removing_funding_B

(F841)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (4)
tests_integration_with_local_chain/markets/omen/test_stealing_on_markets.py (4)

95-95: Fix typo in comment: 'accout B' should be 'account B'

There's a typo in the comment at line 95: 'accout B' should be 'account B'.

Apply this diff to correct the typo:

-    # Buy YES tokens from accout B (attacker) -- removing profit from any real agent that'd like to complete the job.
+    # Buy YES tokens from account B (attacker) -- removing profit from any real agent that'd like to complete the job.

108-108: Correct typo in assertion message

The assertion message at line 108 contains a typo: 'should have be lowered' should be 'should have been lowered'.

Apply this diff to fix the typo:

-        ), "Balance of B should have be lowered from betting"
+        ), "Balance of B should have been lowered from betting"

110-110: Correct typo in comment: 'loose' should be 'lose'

The word 'loose' in the comment at line 110 should be 'lose'.

Apply this diff to correct the spelling:

-    # Account A detects this and removes remaining liquidity, so the attacker is locked-in and will loose money unless he completes the job.
+    # Account A detects this and removes remaining liquidity, so the attacker is locked-in and will lose money unless he completes the job.

172-172: Fix typo in comment: 'manualy' should be 'manually'

There's a typo in the comment at line 172: 'manualy' should be 'manually'.

Apply this diff to correct the typo:

-    # Note: Usually we just take all positions from subgraph and redeem them, here we manualy redeem the ones we should have now.
+    # Note: Usually we just take all positions from subgraph and redeem them, here we manually redeem the ones we should have now.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 959e531 and 1c7161d.

📒 Files selected for processing (1)
  • tests_integration_with_local_chain/markets/omen/test_stealing_on_markets.py (1 hunks)
🧰 Additional context used
🪛 Ruff
tests_integration_with_local_chain/markets/omen/test_stealing_on_markets.py

122-122: pytest.raises(Exception) should be considered evil

(B017)


132-132: pytest.raises(Exception) should be considered evil

(B017)

), "Balance after failed trading should be the same as after buying of tokens in the beginning, because nothing should have happened."

# Wait for market's closing time
time.sleep(close_in * 1.1)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider mocking time to avoid using time.sleep in tests

Using time.sleep in tests can lead to longer test execution times and potential flakiness. Consider mocking the time or adjusting the contract state to avoid waiting in real time during tests.

Also applies to: 163-163

Comment on lines +36 to +210
omen_remove_fund_market_tx(api_keys_A, agent_market, shares=None, web3=local_web3)
balance_after_removing_funding_A = get_balances(
api_keys_A.bet_from_address, local_web3
).total
assert (
balance_after_market_creation_A
< balance_after_removing_funding_A
< starting_balance_A
), "Balance after removing the liquidity should be higher than after market creation (because some liquidity can be withdrawn right away), but lower than before market creation (because some liquidity is now locked for the attacker's bet)"

# Buying or selling tokens after the liquidity is removed will fail.
with pytest.raises(Exception):
binary_omen_buy_outcome_tx(
api_keys_B,
buy_yes_for_b,
agent_market,
binary_outcome=True,
auto_deposit=True,
web3=local_web3,
)
sell_yes_for_b = xdai_type(1)
with pytest.raises(Exception):
binary_omen_sell_outcome_tx(
api_keys_B,
sell_yes_for_b,
agent_market,
binary_outcome=True,
auto_withdraw=True,
web3=local_web3,
)
balance_after_failed_trading_B = get_balances(
api_keys_B.bet_from_address, local_web3
).total
assert (
balance_after_failed_trading_B == balance_after_buying_B
), "Balance after failed trading should be the same as after buying of tokens in the beginning, because nothing should have happened."

# Wait for market's closing time
time.sleep(close_in * 1.1)
# Do a dummy block again, so the time in the contract is updated and it knows it's opened already.
mint_new_block(api_keys_A, local_web3)

# Submit answer on reality.
omen_submit_answer_market_tx(
api_keys_A,
omen_market,
Resolution.NO,
bond=xdai_type(0.001),
web3=local_web3,
)

# Wait for the finalization.
time.sleep(finalization_wait_time_seconds * 1.1)
# Update the time in the chain again.
mint_new_block(api_keys_A, local_web3)

# Resolve the market.
omen_resolve_market_tx(api_keys_A, omen_market, local_web3)

# Redeem positions from both accounts.
# Note: Usually we just take all positions from subgraph and redeem them, here we manualy redeem the ones we should have now.
conditional_token_contract = OmenConditionalTokenContract()
condition_event = check_not_none(
created_market.condition_event,
"Should not be None here as this was a freshly created market.",
)
conditional_token_contract.redeemPositions(
api_keys=api_keys_A,
collateral_token_address=agent_market.collateral_token_contract_address_checksummed,
condition_id=condition_event.conditionId,
index_sets=omen_market.condition.index_sets,
web3=local_web3,
)
conditional_token_contract.redeemPositions(
api_keys=api_keys_B,
collateral_token_address=agent_market.collateral_token_contract_address_checksummed,
condition_id=condition_event.conditionId,
index_sets=omen_market.condition.index_sets,
web3=local_web3,
)

# Check who is the winner in the end.
ending_balance_A, ending_balance_B = (
get_balances(api_keys_A.bet_from_address, local_web3).total,
get_balances(api_keys_B.bet_from_address, local_web3).total,
)

assert (
ending_balance_A > starting_balance_A
), "Assumption was that A will receive B's money."
assert (
ending_balance_B < starting_balance_A
), "Assumption was that B will loose the money he gambled by trying to steal from real job completors."

print(
f"Account A (job creator) ending difference: {ending_balance_A - starting_balance_A}."
)
print(
f"Account B (attacker) ending difference: {ending_balance_B - starting_balance_B}."
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor test into smaller functions for better readability

The test function test_stealing_on_markets is quite long, which can make it harder to read and maintain. Consider refactoring it into smaller helper functions to improve readability and maintainability.

🧰 Tools
🪛 Ruff

122-122: pytest.raises(Exception) should be considered evil

(B017)


132-132: pytest.raises(Exception) should be considered evil

(B017)

web3=local_web3,
)
sell_yes_for_b = xdai_type(1)
with pytest.raises(Exception):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Specify the expected exception type in pytest.raises

Using pytest.raises(Exception) is too general and might catch unexpected exceptions. Please specify the exact exception type that is expected.

Apply this diff:

-    with pytest.raises(Exception):
+    with pytest.raises(ExpectedExceptionType):

Replace ExpectedExceptionType with the appropriate exception.

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 Ruff

132-132: pytest.raises(Exception) should be considered evil

(B017)

), "Balance after removing the liquidity should be higher than after market creation (because some liquidity can be withdrawn right away), but lower than before market creation (because some liquidity is now locked for the attacker's bet)"

# Buying or selling tokens after the liquidity is removed will fail.
with pytest.raises(Exception):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Specify the expected exception type in pytest.raises

Using pytest.raises(Exception) is too broad and may catch unintended exceptions. It's recommended to specify the exact exception type that is expected to be raised.

Apply this diff to specify the expected exception type:

-    with pytest.raises(Exception):
+    with pytest.raises(ExpectedExceptionType):

Replace ExpectedExceptionType with the specific exception that should be raised in this context.

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 Ruff

122-122: pytest.raises(Exception) should be considered evil

(B017)

@evangriffiths evangriffiths self-requested a review October 1, 2024 13:45
@kongzii kongzii merged commit f09b05f into main Oct 3, 2024
14 checks passed
@kongzii kongzii deleted the peter/stealing branch October 3, 2024 17:13
@coderabbitai coderabbitai bot mentioned this pull request Oct 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants