Skip to content

Commit

Permalink
updated for listening for events
Browse files Browse the repository at this point in the history
  • Loading branch information
PatrickAlphaC committed Mar 14, 2022
1 parent a765b40 commit 54e8c7c
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 13 deletions.
7 changes: 5 additions & 2 deletions contracts/AdvancedCollectible.sol
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ contract AdvancedCollectible is ERC721, VRFConsumerBase {
mapping(bytes32 => string) public requestIdToTokenURI;
mapping(uint256 => Breed) public tokenIdToBreed;
mapping(bytes32 => uint256) public requestIdToTokenId;
event requestedCollectible(bytes32 indexed requestId);
event RequestedCollectible(bytes32 indexed requestId);
// New event from the video!
event ReturnedCollectible(bytes32 indexed requestId, uint256 randomNumber);


bytes32 internal keyHash;
Expand All @@ -32,7 +34,7 @@ contract AdvancedCollectible is ERC721, VRFConsumerBase {
bytes32 requestId = requestRandomness(keyHash, fee);
requestIdToSender[requestId] = msg.sender;
requestIdToTokenURI[requestId] = tokenURI;
emit requestedCollectible(requestId);
emit RequestedCollectible(requestId);
}

function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override {
Expand All @@ -45,6 +47,7 @@ contract AdvancedCollectible is ERC721, VRFConsumerBase {
tokenIdToBreed[newItemId] = breed;
requestIdToTokenId[requestId] = newItemId;
tokenCounter = tokenCounter + 1;
emit ReturnedCollectible(requestId, randomNumber);
}

function setTokenURI(uint256 tokenId, string memory _tokenURI) public {
Expand Down
9 changes: 6 additions & 3 deletions scripts/advanced_collectible/create_collectible.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/python3
from brownie import AdvancedCollectible, accounts, config
from scripts.helpful_scripts import get_breed, fund_with_link
from scripts.helpful_scripts import get_breed, fund_with_link, listen_for_event
import time


Expand All @@ -12,8 +12,11 @@ def main():
print("Waiting on second transaction...")
# wait for the 2nd transaction
transaction.wait(1)
time.sleep(35)
requestId = transaction.events["requestedCollectible"]["requestId"]
# time.sleep(35)
listen_for_event(
advanced_collectible, "ReturnedCollectible", timeout=200, poll_interval=10
)
requestId = transaction.events["RequestedCollectible"]["requestId"]
token_id = advanced_collectible.requestIdToTokenId(requestId)
breed = get_breed(advanced_collectible.tokenIdToBreed(token_id))
print("Dog breed of tokenId {} is {}".format(token_id, breed))
51 changes: 48 additions & 3 deletions scripts/helpful_scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,14 @@
MockOracle,
VRFCoordinatorMock,
Contract,
web3,
chain,
)
import os
import time

# Set a default gas price
from brownie.network import priority_fee

OPENSEA_FORMAT = "https://testnets.opensea.io/assets/{}/{}"
NON_FORKED_LOCAL_BLOCKCHAIN_ENVIRONMENTS = ["hardhat", "development", "ganache"]
Expand Down Expand Up @@ -76,12 +82,16 @@ def get_contract(contract_name):
)
return contract


def get_publish_source():
if network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS or not os.getenv("ETHERSCAN_TOKEN"):
if network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS or not os.getenv(
"ETHERSCAN_TOKEN"
):
return False
else:
else:
return True


def get_breed(breed_number):
switch = {0: "PUG", 1: "SHIBA_INU", 2: "ST_BERNARD"}
return switch[breed_number]
Expand Down Expand Up @@ -112,6 +122,8 @@ def deploy_mocks(decimals=18, initial_value=2000):
"""
Use this script if you want to deploy mocks to a testnet
"""
# Set a default gas price
priority_fee("1 gwei")
print(f"The active network is {network.show_active()}")
print("Deploying Mocks...")
account = get_account()
Expand All @@ -124,11 +136,44 @@ def deploy_mocks(decimals=18, initial_value=2000):
print(f"Deployed to {mock_price_feed.address}")
print("Deploying Mock VRFCoordinator...")
mock_vrf_coordinator = VRFCoordinatorMock.deploy(
link_token.address, {"from": account}
link_token.address, {"from": account, "gas_price": chain.base_fee}
)
print(f"Deployed to {mock_vrf_coordinator.address}")

print("Deploying Mock Oracle...")
mock_oracle = MockOracle.deploy(link_token.address, {"from": account})
print(f"Deployed to {mock_oracle.address}")
print("Mocks Deployed!")


def listen_for_event(brownie_contract, event, timeout=200, poll_interval=2):
"""Listen for an event to be fired from a contract.
We are waiting for the event to return, so this function is blocking.
Args:
brownie_contract ([brownie.network.contract.ProjectContract]):
A brownie contract of some kind.
event ([string]): The event you'd like to listen for.
timeout (int, optional): The max amount in seconds you'd like to
wait for that event to fire. Defaults to 200 seconds.
poll_interval ([int]): How often to call your node to check for events.
Defaults to 2 seconds.
"""
web3_contract = web3.eth.contract(
address=brownie_contract.address, abi=brownie_contract.abi
)
start_time = time.time()
current_time = time.time()
event_filter = web3_contract.events[event].createFilter(fromBlock="latest")
while current_time - start_time < timeout:
for event_response in event_filter.get_new_entries():
if event in event_response.event:
print("Found event!")
return event_response
time.sleep(poll_interval)
current_time = time.time()
print("Timeout reached, no event found.")
return {"event": None}
6 changes: 5 additions & 1 deletion tests/integration/test_advanced_int.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
get_account,
get_contract,
LOCAL_BLOCKCHAIN_ENVIRONMENTS,
listen_for_event,
)
import time

Expand All @@ -26,6 +27,9 @@ def test_can_create_advanced_collectible_integration(
)
# Act
advanced_collectible.createCollectible("None", {"from": get_account()})
time.sleep(75)
# time.sleep(75)
listen_for_event(
advanced_collectible, "ReturnedCollectible", timeout=200, poll_interval=10
)
# Assert
assert advanced_collectible.tokenCounter() > 0
2 changes: 1 addition & 1 deletion tests/unit/test_advanced_collectible.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def test_can_create_advanced_collectible(
transaction_receipt = advanced_collectible.createCollectible(
"None", {"from": get_account()}
)
requestId = transaction_receipt.events["requestedCollectible"]["requestId"]
requestId = transaction_receipt.events["RequestedCollectible"]["requestId"]
assert isinstance(transaction_receipt.txid, str)
get_contract("vrf_coordinator").callBackWithRandomness(
requestId, 777, advanced_collectible.address, {"from": get_account()}
Expand Down
10 changes: 7 additions & 3 deletions tests/unit/test_simple_collectible.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import pytest
from brownie import network, SimpleCollectible, convert
from brownie import network, SimpleCollectible, convert, chain
from scripts.helpful_scripts import get_account


def test_can_create_simple_collectible():
if network.show_active() not in ["development"] or "fork" in network.show_active():
pytest.skip("Only for local testing")
simple_collectible = SimpleCollectible.deploy({"from": get_account()})
simple_collectible.createCollectible("None")
simple_collectible = SimpleCollectible.deploy(
{"from": get_account(), "gas_price": chain.base_fee}
)
simple_collectible.createCollectible(
"None", {"from": get_account(), "gas_price": chain.base_fee}
)
assert simple_collectible.ownerOf(0) == get_account()

0 comments on commit 54e8c7c

Please sign in to comment.