Fix #628 & #629 & #621: Store event log index for all records (#630)

* Store eventIndex.

* Changed in veDelegation. Removed import of String.

* linter.

* Removed tx hash.

* Revert some tweaks.

* added logIndex.

* converted to big int.

* 0 -> BigInt.zero().

* Added eventIndex to template and OPC.

* updated tweak

* updated tweak2

* Added eventIndex in tests.

* revert.

* Added eventIndex for TokenCreated and NFTCreated events. Increase time sleep for graphql request.

* Changed position of eventIndex in entity.

* Added eventIndex for order events and for dt events. Added new test commands in package.json.

* Added eventIndex for NFT Update events.

* Added eventIndex for dispenser.

* Modified dispenser tests.

* Reverted sleep secs. Updated tests.

* Updated dispenser tests. Added eventIndex for FRE.

* Added eventIndex in df rewards.

* Updated Ve with eventIndex.

* Updating order id with event index.

* Updated @ocean/lib with multichain version.

* Updated to number type.

* Updated tests for order.

* some changes.

* Fix dt tests. Added logs for provider fee. Need fix for Simple publish and consume tests.

* Problem raised by retrieving order event index in provider fee event handler.

* Added function for searching the right order.

* Debug order with provider fee.

* Removed console logs.

* Added debug logs.

* Hardcoded eventIndex just for testing.

* Paste logs from graph node.

* added extra sleep in test.

* fixed command.

* Added comments. Modified util function for Order Reuse.

* Added more logs and other tweaks.

* fixed command for docker logs.

* Added more logs.

* Converted to lowercase.

* Removed condition just for test.

* Added more logs. Order is not null.

* Call getOrder.

* Added verification back.

* converted to hex and add toString.

* Pass toString as param.

* Added ethereumjs util.

* replaced with ==.

* Refactored logic.

* Print event index.

* added more logs of event index.

* Modified tweaks and asserts.

* Added log for reuse order.

* updates.

* Reverted changes.

* Added check for eventIndex == 0.

* Enhanced the code. Replaced while with for.

* Added more logs for reuse test.

* added another condition.

* Added logs in tests. Removed redundant condition.

* Added more logs to test.

* Fixed typo.

* still debugging

* Refactored code.

* Getting closer.

* Fix tests for orders part. Removed logs.

* Removed more logs.

* Fix DT tests related to order.

* Implemented Publishing Market Fee event handler. Added test.

* Added consume market fee handler. Test consume market fee handler.

* Fixed tests for fees. Added TODOs.

* Generated ID with eventIndex in ficed rate. Added assert errors messages.

* Added FRE tests to workflow.

* Generated dispenser transaction with event index.

* Fixed dispenser tests.

* Add event index for NftUpdate entity ID.

* Changed IDs for VeDelegation and VeAllocationUpdate.

* Added full test suite to workflow.

* Fixed nft transfer ID.

* print blocks.

* test just dt and ending test to see the last block.

* Added df test.

* Added dispenser test.

* Added FRE test.

* Added NFT test.

* Added simple publish consume test.

* Added simple subgraph test.

* Added users test.

* Added ve test.

* Increased sleep time.

* commented delegation test.

* respect lint

* Fixed ending tests. Removed commented code. Brought back test suite.

* Print values from failing tests. Updated mappings.

* Rollback changes in veDelegation and veUtils. Added more prints for debug in tests.

* Removed veDelegation creation record.

* Rollback to the approach for veDelegation like it is in main.

* Removed prints. Match changes with main.

* Removed -1 from last block.

* Added prints for eventIndex. Fixed some suggestions.

* Fixed veDelegation.

* Removed prints.
This commit is contained in:
Maria Carmina 2023-05-13 15:00:52 +03:00 committed by GitHub
parent c42cd1c283
commit e1df119197
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 647 additions and 170 deletions

View File

@ -74,3 +74,6 @@ jobs:
env:
ADDRESS_FILE: /home/runner/.ocean/ocean-contracts/artifacts/address.json
BARGE_FOLDER: /home/runner/.ocean/
- name: docker logs
run: docker logs ocean_graph-node_1
if: ${{ failure() }}

3
package-lock.json generated
View File

@ -11,7 +11,8 @@
"dependencies": {
"@oceanprotocol/contracts": "^1.1.12",
"@oceanprotocol/lib": "^2.7.0",
"cross-fetch": "^3.1.4"
"cross-fetch": "^3.1.4",
"ethereumjs-util": "^7.1.5"
},
"devDependencies": {
"@graphprotocol/graph-cli": "^0.38.0",

View File

@ -33,6 +33,8 @@
"test-df": "TS_NODE_PROJECT='test/integration/tsconfig.json' mocha --config=test/integration/.mocharc.json --node-env=test --exit 'test/integration/DFRewards.test.ts'",
"test-dt": "TS_NODE_PROJECT='test/integration/tsconfig.json' mocha --config=test/integration/.mocharc.json --node-env=test --exit 'test/integration/Datatoken.test.ts'",
"test-zend": "TS_NODE_PROJECT='test/integration/tsconfig.json' mocha --config=test/integration/.mocharc.json --node-env=test --exit 'test/integration/ZEnding.test.ts'",
"test-publish-consume": "TS_NODE_PROJECT='test/integration/tsconfig.json' mocha --config=test/integration/.mocharc.json --node-env=test --exit 'test/integration/SimplePublishConsume.test.ts'",
"test-nft": "TS_NODE_PROJECT='test/integration/tsconfig.json' mocha --config=test/integration/.mocharc.json --node-env=test --exit 'test/integration/Nft.test.ts'",
"lint": "eslint --ignore-path .gitignore --ext .js --ext .ts --ext .tsx .",
"lint:fix": "eslint --ignore-path .gitignore --ext .js,.ts,.tsx . --fix",
"format": "prettier --ignore-path .gitignore './**/*.{css,yml,js,ts,tsx,json,yaml}' --write",
@ -72,7 +74,8 @@
"dependencies": {
"@oceanprotocol/contracts": "^1.1.12",
"@oceanprotocol/lib": "^2.7.0",
"cross-fetch": "^3.1.4"
"cross-fetch": "^3.1.4",
"ethereumjs-util": "^7.1.5"
},
"repository": {
"type": "git",

View File

@ -52,7 +52,7 @@ type Token @entity {
"datatoken creation transaction id"
tx: String!
eventIndex: Int!
"block number when it was created"
block: Int!
@ -105,6 +105,7 @@ type Nft @entity{
createdTimestamp: Int!
"nft creation transaction id"
tx: String!
eventIndex: Int!
"block number when it was created"
block: Int
@ -132,6 +133,7 @@ type OrderReuse @entity {
caller: String!
createdTimestamp: Int!
tx: String!
eventIndex: Int!
block: Int!
providerFee: String
providerFeeValidUntil: BigInt
@ -141,7 +143,7 @@ type OrderReuse @entity {
}
type Order @entity {
"transaction hash - token address - from address"
"transaction hash - token address - from address - eventIndex"
id: ID!
datatoken: Token!
@ -167,6 +169,7 @@ type Order @entity {
createdTimestamp: Int!
tx: String!
eventIndex: Int!
block: Int!
lastPriceToken: Token
@ -220,6 +223,7 @@ type FixedRateExchange @entity {
createdTimestamp: Int!
tx: String!
eventIndex: Int!
block: Int!
"address of the market where the datatoken was created. This address collects market fees."
@ -246,6 +250,7 @@ type FixedRateExchangeUpdate @entity {
block: Int!
createdTimestamp: Int!
tx: String!
eventIndex: Int!
}
type FixedRateExchangeSwap @entity {
@ -257,6 +262,7 @@ type FixedRateExchangeSwap @entity {
block: Int!
createdTimestamp: Int!
tx: String!
eventIndex: Int!
oceanFeeAmount: BigDecimal!
marketFeeAmount: BigDecimal!
consumeMarketFeeAmount: BigDecimal!
@ -285,6 +291,7 @@ type Dispenser @entity {
block: Int!
createdTimestamp: Int!
tx: String!
eventIndex: Int!
dispenses: [DispenserTransaction!] @derivedFrom(field: "dispenser")
}
@ -298,6 +305,7 @@ type DispenserTransaction @entity {
block: Int!
createdTimestamp: Int!
tx: String!
eventIndex: Int!
}
"utility type"
@ -385,6 +393,7 @@ type NftUpdate @entity {
block: Int!
timestamp: Int!
tx: String!
eventIndex: Int!
}
type Template @entity{
@ -406,6 +415,7 @@ type VeAllocateUser @entity{
firstContact: Int!
lastContact: Int!
tx: String!
eventIndex: Int!
veOcean: VeOCEAN!
}
@ -422,6 +432,7 @@ type VeAllocateId @entity{
firstContact: Int!
lastContact: Int!
tx: String!
eventIndex: Int!
}
# we need to track allocation of user to id
@ -441,6 +452,7 @@ type VeAllocation @entity {
firstContact: Int!
lastContact: Int!
tx: String!
eventIndex: Int!
}
enum veAllocationUpdateType {
@ -449,7 +461,7 @@ enum veAllocationUpdateType {
}
type VeAllocationUpdate @entity {
"{tx}-{VeAllocation id}"
"{tx}-{VeAllocation id}-{eventIndex}"
id: ID!
veAllocation: VeAllocation!
@ -459,10 +471,11 @@ type VeAllocationUpdate @entity {
block: Int!
timestamp: Int!
tx: String!
eventIndex: Int!
}
type VeDelegation @entity {
"id = VeDelegation contract + tokenId"
"id = VeDelegation contract + tokenId"
id: ID!
delegator: VeOCEAN!
receiver: VeOCEAN!
@ -480,6 +493,7 @@ type VeDelegationUpdate @entity {
block: Int!
timestamp: Int!
tx: String!
eventIndex: Int!
sender: String!
amount: BigDecimal!
cancelTime: BigInt!
@ -521,6 +535,7 @@ type VeDeposit @entity {
timestamp: BigInt!
block: Int!
tx: String!
eventIndex: Int!
veOcean: VeOCEAN!
totalOceanLocked:BigDecimal!
}
@ -546,6 +561,7 @@ type VeFeeDistributorCheckPoint @entity {
timestamp: BigInt!
block: Int!
tx: String!
eventIndex: Int!
}
type VeClaim @entity {
@ -560,6 +576,7 @@ type VeClaim @entity {
timestamp: BigInt!
block: Int!
tx: String!
eventIndex: Int!
veOcean: VeOCEAN!
VeFeeDistributor: VeFeeDistributor!
}
@ -588,6 +605,7 @@ type DFHistory @entity {
timestamp: BigInt!
block: Int!
tx: String!
eventIndex: Int!
}
@ -606,6 +624,7 @@ type NftTransferHistory @entity {
oldOwner: User!
newOwner: User!
txId: String
eventIndex: Int!
timestamp: Int!
block: Int!
}

View File

@ -26,6 +26,7 @@ export function handleAllocated(event: Allocated): void {
history.type = 'Allocated'
history.timestamp = event.block.timestamp
history.tx = event.transaction.hash.toHex()
history.eventIndex = event.logIndex.toI32()
history.block = event.block.number.toI32()
history.save()
@ -55,6 +56,7 @@ export function handleClaimed(event: Claimed): void {
history.type = 'Claimed'
history.timestamp = event.block.timestamp
history.tx = event.transaction.hash.toHex()
history.eventIndex = event.logIndex.toI32()
history.block = event.block.number.toI32()
history.save()

View File

@ -43,6 +43,7 @@ export function handleNewDispenser(event: DispenserCreated): void {
dispenser.allowedSwapper = event.params.allowedSwapper.toHex()
dispenser.createdTimestamp = event.block.timestamp.toI32()
dispenser.tx = event.transaction.hash.toHex()
dispenser.eventIndex = event.logIndex.toI32()
dispenser.block = event.block.number.toI32()
dispenser.save()
@ -57,6 +58,7 @@ export function handleActivate(event: DispenserActivated): void {
)
const dispenser = getDispenser(dispenserID)
dispenser.active = true
dispenser.eventIndex = event.logIndex.toI32()
dispenser.save()
}
@ -67,6 +69,7 @@ export function handleDeactivate(event: DispenserDeactivated): void {
)
const dispenser = getDispenser(dispenserID)
dispenser.active = false
dispenser.eventIndex = event.logIndex.toI32()
dispenser.save()
}
@ -76,6 +79,7 @@ export function handleAllowedSwapperChanged(
const dispenserID = getDispenserGraphID(event.address, event.params.datatoken)
const dispenser = getDispenser(dispenserID)
dispenser.allowedSwapper = event.params.newAllowedSwapper.toHex()
dispenser.eventIndex = event.logIndex.toI32()
dispenser.save()
}
@ -84,10 +88,8 @@ export function handleTokensDispensed(event: TokensDispensed): void {
event.address,
event.params.datatokenAddress
)
const id = event.transaction.hash
.toHexString()
.concat('-')
.concat(dispenserID)
const eventIndex: number = event.logIndex.toI32()
const id = `${event.transaction.hash.toHexString()}-${dispenserID}-${eventIndex}`
const dispenserTransaction = new DispenserTransaction(id)
const dispenser = getDispenser(dispenserID)
@ -98,6 +100,7 @@ export function handleTokensDispensed(event: TokensDispensed): void {
dispenserTransaction.createdTimestamp = event.block.timestamp.toI32()
dispenserTransaction.tx = event.transaction.hash.toHex()
dispenserTransaction.eventIndex = event.logIndex.toI32()
dispenserTransaction.block = event.block.number.toI32()
const token = getToken(event.params.datatokenAddress, true)
dispenserTransaction.amount = weiToDecimal(
@ -111,5 +114,6 @@ export function handleOwnerWinthdraw(event: OwnerWithdrawed): void {
const dispenserID = getDispenserGraphID(event.address, event.params.datatoken)
const dispenser = getDispenser(dispenserID)
dispenser.balance = decimal.ZERO
dispenser.eventIndex = event.logIndex.toI32()
dispenser.save()
}

View File

@ -1,11 +1,12 @@
import { Order, Nft, OrderReuse } from '../@types/schema'
import { BigInt, BigDecimal, Address } from '@graphprotocol/graph-ts'
import { BigInt, BigDecimal, Address, log } from '@graphprotocol/graph-ts'
import {
NewPaymentCollector,
OrderStarted,
PublishMarketFee,
PublishMarketFeeChanged,
ConsumeMarketFee,
AddedMinter,
AddedPaymentManager,
RemovedMinter,
@ -20,14 +21,19 @@ import { weiToDecimal } from './utils/generic'
import { addOrder } from './utils/globalUtils'
import { getToken, getUSDValue } from './utils/tokenUtils'
import { getUser } from './utils/userUtils'
import { getOrderId } from './utils/orderUtils'
import {
getOrderId,
searchOrderForEvent,
searchOrderReusedForEvent
} from './utils/orderUtils'
export function handleOrderStarted(event: OrderStarted): void {
const order = new Order(
getOrderId(
event.transaction.hash.toHex(),
event.address.toHex(),
event.transaction.from.toHex()
event.transaction.from.toHex(),
event.logIndex.toI32()
)
)
@ -59,11 +65,9 @@ export function handleOrderStarted(event: OrderStarted): void {
const publishMarket = getUser(event.params.publishMarketAddress.toHex())
order.publishingMarket = publishMarket.id
// const consumeMarket = getUser(event.params..toHex())
// order.consumerMarket = consumeMarket.id
order.createdTimestamp = event.block.timestamp.toI32()
order.tx = event.transaction.hash.toHex()
order.eventIndex = event.logIndex.toI32()
order.block = event.block.number.toI32()
const tokenId = token.lastPriceToken
if (tokenId) {
@ -103,32 +107,56 @@ export function handleOrderStarted(event: OrderStarted): void {
}
export function handlerOrderReused(event: OrderReused): void {
const orderId = getOrderId(
const order = searchOrderForEvent(
event.params.orderTxId.toHexString(),
event.address.toHex(),
event.params.caller.toHex()
event.params.caller.toHex(),
event.logIndex.toI32()
)
const order = Order.load(orderId)
if (!order) return
const eventIndex: number = event.logIndex.toI32()
const reuseOrder = new OrderReuse(event.transaction.hash.toHex())
const reuseOrder = new OrderReuse(
`${event.transaction.hash.toHex()}-${eventIndex}`
)
if (event.transaction.gasPrice)
reuseOrder.gasPrice = event.transaction.gasPrice
else reuseOrder.gasPrice = BigInt.zero()
if (event.receipt !== null && event.receipt!.gasUsed) {
reuseOrder.gasUsed = event.receipt!.gasUsed.toBigDecimal()
} else reuseOrder.gasUsed = BigDecimal.zero()
reuseOrder.order = orderId
reuseOrder.order = order.id
reuseOrder.caller = event.params.caller.toHexString()
reuseOrder.createdTimestamp = event.params.timestamp.toI32()
reuseOrder.tx = event.transaction.hash.toHex()
reuseOrder.eventIndex = event.logIndex.toI32()
reuseOrder.block = event.params.number.toI32()
reuseOrder.save()
}
export function handlePublishMarketFee(event: PublishMarketFee): void {}
export function handlePublishMarketFee(event: PublishMarketFee): void {
const order = searchOrderForEvent(
event.transaction.hash.toHex(),
event.address.toHex(),
event.transaction.from.toHex(),
event.logIndex.toI32()
)
if (!order) return
const publishMarket = getUser(event.params.PublishMarketFeeAddress.toHex())
order.publishingMarket = publishMarket.id
const publishMarketToken = getToken(event.params.PublishMarketFeeToken, true)
order.publishingMarketToken = publishMarketToken.id
order.publishingMarketAmmount = weiToDecimal(
event.params.PublishMarketFeeAmount.toBigDecimal(),
publishMarketToken.decimals
)
order.save()
}
export function handlePublishMarketFeeChanged(
event: PublishMarketFeeChanged
): void {
@ -149,10 +177,33 @@ export function handlePublishMarketFeeChanged(
event.params.PublishMarketFeeAmount.toBigDecimal(),
decimals
)
token.eventIndex = event.logIndex.toI32()
token.save()
// TODO - shold we have a history
}
export function handleConsumeMarketFee(event: ConsumeMarketFee): void {
const order = searchOrderForEvent(
event.transaction.hash.toHex(),
event.address.toHex(),
event.transaction.from.toHex(),
event.logIndex.toI32()
)
if (!order) return
const consumeMarket = getUser(event.params.consumeMarketFeeAddress.toHex())
order.consumerMarket = consumeMarket.id
const consumeMarketToken = getToken(event.params.consumeMarketFeeToken, false)
order.consumerMarketToken = consumeMarketToken.id
order.consumerMarketAmmount = weiToDecimal(
event.params.consumeMarketFeeAmount.toBigDecimal(),
consumeMarketToken.decimals
)
order.save()
}
// roles
// roles
export function handleAddedMinter(event: AddedMinter): void {
@ -163,6 +214,7 @@ export function handleAddedMinter(event: AddedMinter): void {
if (!existingRoles.includes(event.params.user.toHexString()))
existingRoles.push(event.params.user.toHexString())
token.minter = existingRoles
token.eventIndex = event.logIndex.toI32()
token.save()
}
@ -179,6 +231,7 @@ export function handleRemovedMinter(event: RemovedMinter): void {
if (role !== event.params.user.toHexString()) newList.push(role)
}
token.minter = newList
token.eventIndex = event.logIndex.toI32()
token.save()
}
@ -190,6 +243,7 @@ export function handleAddedPaymentManager(event: AddedPaymentManager): void {
if (!existingRoles.includes(event.params.user.toHexString()))
existingRoles.push(event.params.user.toHexString())
token.paymentManager = existingRoles
token.eventIndex = event.logIndex.toI32()
token.save()
}
export function handleRemovedPaymentManager(
@ -207,6 +261,7 @@ export function handleRemovedPaymentManager(
if (role !== event.params.user.toHexString()) newList.push(role)
}
token.paymentManager = newList
token.eventIndex = event.logIndex.toI32()
token.save()
}
export function handleCleanedPermissions(event: CleanedPermissions): void {
@ -217,12 +272,14 @@ export function handleCleanedPermissions(event: CleanedPermissions): void {
const nft = Nft.load(token.nft as string)
if (nft) token.paymentCollector = nft.owner
else token.paymentCollector = '0x0000000000000000000000000000000000000000'
token.eventIndex = event.logIndex.toI32()
token.save()
}
export function handleNewPaymentCollector(event: NewPaymentCollector): void {
const token = getToken(event.address, true)
token.paymentCollector = event.params._newPaymentCollector.toHexString()
token.eventIndex = event.logIndex.toI32()
token.save()
}
@ -235,12 +292,12 @@ export function handleProviderFee(event: ProviderFee): void {
event.params.validUntil
}"}`
const orderId = getOrderId(
const order = searchOrderForEvent(
event.transaction.hash.toHex(),
event.address.toHex(),
event.transaction.from.toHex()
event.transaction.from.toHex(),
event.logIndex.toI32()
)
const order = Order.load(orderId)
if (order) {
order.providerFee = providerFee
@ -248,27 +305,15 @@ export function handleProviderFee(event: ProviderFee): void {
order.save()
return
}
let orderReuse = OrderReuse.load(event.transaction.hash.toHex())
const orderReuse = searchOrderReusedForEvent(
event.transaction.hash.toHex(),
event.address.toHex(),
event.logIndex.toI32()
)
if (orderReuse) {
log.info('order reuse id in provider fee handler: {}', [orderReuse.id])
orderReuse.providerFee = providerFee
orderReuse.providerFeeValidUntil = event.params.validUntil
orderReuse.save()
} else {
orderReuse = new OrderReuse(event.transaction.hash.toHex())
orderReuse.providerFee = providerFee
orderReuse.providerFeeValidUntil = event.params.validUntil
orderReuse.order = orderId
orderReuse.createdTimestamp = event.block.timestamp.toI32()
orderReuse.tx = event.transaction.hash.toHex()
orderReuse.block = event.block.number.toI32()
orderReuse.caller = event.transaction.from.toHex()
if (event.transaction.gasPrice)
orderReuse.gasPrice = event.transaction.gasPrice
else orderReuse.gasPrice = BigInt.zero()
if (event.receipt !== null && event.receipt!.gasUsed) {
orderReuse.gasUsed = event.receipt!.gasUsed.toBigDecimal()
} else orderReuse.gasUsed = BigDecimal.zero()
orderReuse.save()
}
}

View File

@ -25,6 +25,7 @@ export function handleNftCreated(event: NFTCreated): void {
nft.createdTimestamp = event.block.timestamp.toI32()
nft.tx = event.transaction.hash.toHex()
nft.block = event.block.number.toI32()
nft.eventIndex = event.logIndex.toI32()
nft.transferable = event.params.transferable
nft.save()
@ -39,6 +40,7 @@ export function handleNewToken(event: TokenCreated): void {
token.createdTimestamp = event.block.timestamp.toI32()
token.tx = event.transaction.hash.toHex()
token.block = event.block.number.toI32()
token.eventIndex = event.logIndex.toI32()
token.nft = event.params.creator.toHexString()

View File

@ -50,6 +50,7 @@ export function handleExchangeCreated(event: ExchangeCreated): void {
)
fixedRateExchange.createdTimestamp = event.block.timestamp.toI32()
fixedRateExchange.tx = event.transaction.hash.toHex()
fixedRateExchange.eventIndex = event.logIndex.toI32()
fixedRateExchange.block = event.block.number.toI32()
fixedRateExchange.save()
@ -63,12 +64,14 @@ export function handleRateChange(event: ExchangeRateChanged): void {
event.address
)
const fixedRateExchange = getFixedRateExchange(fixedRateId)
const eventIndex: number = event.logIndex.toI32()
const newExchangeUpdate = new FixedRateExchangeUpdate(
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId)
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId, eventIndex)
)
newExchangeUpdate.oldPrice = fixedRateExchange.price
newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32()
newExchangeUpdate.tx = event.transaction.hash.toHex()
newExchangeUpdate.eventIndex = event.logIndex.toI32()
newExchangeUpdate.block = event.block.number.toI32()
newExchangeUpdate.exchangeId = fixedRateId
@ -89,6 +92,7 @@ export function handleMintStateChanged(event: ExchangeMintStateChanged): void {
)
const fixedRateExchange = getFixedRateExchange(fixedRateId)
fixedRateExchange.withMint = event.params.withMint
fixedRateExchange.eventIndex = event.logIndex.toI32()
fixedRateExchange.save()
}
@ -98,14 +102,16 @@ export function handleActivated(event: ExchangeActivated): void {
event.address
)
const fixedRateExchange = getFixedRateExchange(fixedRateId)
const eventIndex: number = event.logIndex.toI32()
const newExchangeUpdate = new FixedRateExchangeUpdate(
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId)
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId, eventIndex)
)
newExchangeUpdate.exchangeId = fixedRateId
newExchangeUpdate.oldActive = fixedRateExchange.active
newExchangeUpdate.newActive = true
newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32()
newExchangeUpdate.tx = event.transaction.hash.toHex()
newExchangeUpdate.eventIndex = event.logIndex.toI32()
newExchangeUpdate.block = event.block.number.toI32()
fixedRateExchange.active = true
@ -120,8 +126,9 @@ export function handleDeactivated(event: ExchangeDeactivated): void {
event.address
)
const fixedRateExchange = getFixedRateExchange(fixedRateId)
const eventIndex: number = event.logIndex.toI32()
const newExchangeUpdate = new FixedRateExchangeUpdate(
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId)
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId, eventIndex)
)
newExchangeUpdate.oldActive = fixedRateExchange.active
newExchangeUpdate.newActive = false
@ -129,6 +136,7 @@ export function handleDeactivated(event: ExchangeDeactivated): void {
newExchangeUpdate.exchangeId = fixedRateId
newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32()
newExchangeUpdate.tx = event.transaction.hash.toHex()
newExchangeUpdate.eventIndex = event.logIndex.toI32()
newExchangeUpdate.block = event.block.number.toI32()
fixedRateExchange.active = false
@ -144,11 +152,13 @@ export function handleAllowedSwapperChanged(
event.address
)
const fixedRateExchange = getFixedRateExchange(fixedRateId)
const eventIndex: number = event.logIndex.toI32()
const newExchangeUpdate = new FixedRateExchangeUpdate(
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId)
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId, eventIndex)
)
newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32()
newExchangeUpdate.tx = event.transaction.hash.toHex()
newExchangeUpdate.eventIndex = event.logIndex.toI32()
newExchangeUpdate.block = event.block.number.toI32()
newExchangeUpdate.oldAllowedSwapper = fixedRateExchange.allowedSwapper
newExchangeUpdate.exchangeId = fixedRateId
@ -165,12 +175,13 @@ export function handleSwap(event: Swapped): void {
event.address
)
const fixedRateExchange = getFixedRateExchange(fixedRateId)
const eventIndex: number = event.logIndex.toI32()
const swap = new FixedRateExchangeSwap(
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId)
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId, eventIndex)
)
swap.createdTimestamp = event.block.timestamp.toI32()
swap.tx = event.transaction.hash.toHex()
swap.eventIndex = event.logIndex.toI32()
swap.block = event.block.number.toI32()
swap.exchangeId = fixedRateId
@ -244,6 +255,7 @@ export function handlePublishMarketFeeChanged(
event.params.swapFee.toBigDecimal(),
BigInt.fromI32(18).toI32()
)
fixedRateExchange.eventIndex = event.logIndex.toI32()
fixedRateExchange.save()
}
}
@ -261,7 +273,7 @@ export function handleTokenCollected(event: TokenCollected): void {
fixedRateExchange.baseTokenBalance.minus(
weiToDecimal(event.params.amount.toBigDecimal(), baseToken.decimals)
)
fixedRateExchange.eventIndex = event.logIndex.toI32()
fixedRateExchange.save()
}
}

View File

@ -20,8 +20,8 @@ import { NftUpdateType } from './utils/constants'
import { getNftToken, getNftTokenWithID } from './utils/tokenUtils'
import { getUser } from './utils/userUtils'
function getId(tx: string, nftAddress: string): string {
return `${tx}-${nftAddress}`
function getId(tx: string, nftAddress: string, eventIndex: number): string {
return `${tx}-${nftAddress}-${eventIndex}`
}
export function handleMetadataCreated(event: MetadataCreated): void {
@ -33,8 +33,9 @@ export function handleMetadataCreated(event: MetadataCreated): void {
nft.providerUrl = event.params.decryptorUrl.toString()
nft.hasMetadata = true
const eventIndex: number = event.logIndex.toI32()
const nftUpdate = new NftUpdate(
getId(event.transaction.hash.toHex(), nftAddress)
getId(event.transaction.hash.toHex(), nftAddress, eventIndex)
)
nftUpdate.type = NftUpdateType.METADATA_CREATED
@ -47,6 +48,7 @@ export function handleMetadataCreated(event: MetadataCreated): void {
nftUpdate.timestamp = event.block.timestamp.toI32()
nftUpdate.tx = event.transaction.hash.toHex()
nftUpdate.eventIndex = event.logIndex.toI32()
nftUpdate.block = event.block.number.toI32()
nftUpdate.save()
@ -60,8 +62,9 @@ export function handleMetadataUpdated(event: MetadataUpdated): void {
nft.assetState = event.params.state
nft.hasMetadata = true
const eventIndex: number = event.logIndex.toI32()
const nftUpdate = new NftUpdate(
getId(event.transaction.hash.toHex(), nftAddress)
getId(event.transaction.hash.toHex(), nftAddress, eventIndex)
)
nftUpdate.nft = nft.id
@ -71,6 +74,7 @@ export function handleMetadataUpdated(event: MetadataUpdated): void {
nftUpdate.timestamp = event.block.timestamp.toI32()
nftUpdate.tx = event.transaction.hash.toHex()
nftUpdate.eventIndex = event.logIndex.toI32()
nftUpdate.block = event.block.number.toI32()
nftUpdate.save()
@ -83,9 +87,9 @@ export function handleMetadataState(event: MetadataState): void {
if (!nft) return
nft.assetState = event.params.state
const eventIndex: number = event.logIndex.toI32()
const nftUpdate = new NftUpdate(
getId(event.transaction.hash.toHex(), nftAddress)
getId(event.transaction.hash.toHex(), nftAddress, eventIndex)
)
nftUpdate.nft = nft.id
@ -95,6 +99,7 @@ export function handleMetadataState(event: MetadataState): void {
nftUpdate.timestamp = event.block.timestamp.toI32()
nftUpdate.tx = event.transaction.hash.toHex()
nftUpdate.eventIndex = event.logIndex.toI32()
nftUpdate.block = event.block.number.toI32()
nftUpdate.save()
@ -108,9 +113,9 @@ export function handleTokenUriUpdate(event: TokenURIUpdate): void {
if (!nft) return
nft.tokenUri = event.params.tokenURI.toString()
const eventIndex: number = event.logIndex.toI32()
const nftUpdate = new NftUpdate(
getId(event.transaction.hash.toHex(), nftAddress)
getId(event.transaction.hash.toHex(), nftAddress, eventIndex)
)
nftUpdate.nft = nft.id
nftUpdate.type = NftUpdateType.TOKENURI_UPDATED
@ -118,6 +123,7 @@ export function handleTokenUriUpdate(event: TokenURIUpdate): void {
nftUpdate.tokenUri = nft.tokenUri
nftUpdate.timestamp = event.block.timestamp.toI32()
nftUpdate.tx = event.transaction.hash.toHex()
nftUpdate.eventIndex = event.logIndex.toI32()
nftUpdate.block = event.block.number.toI32()
nftUpdate.assetState = nft.assetState
nftUpdate.save()
@ -133,6 +139,7 @@ export function handleAddedManager(event: AddedManager): void {
if (!existingRoles.includes(event.params.user.toHexString()))
existingRoles.push(event.params.user.toHexString())
nft.managerRole = existingRoles
nft.eventIndex = event.logIndex.toI32()
nft.save()
}
export function handleRemovedManager(event: RemovedManager): void {
@ -148,6 +155,7 @@ export function handleRemovedManager(event: RemovedManager): void {
if (role !== event.params.user.toHexString()) newList.push(role)
}
nft.managerRole = newList
nft.eventIndex = event.logIndex.toI32()
nft.save()
}
@ -160,6 +168,7 @@ export function handleAddedTo725StoreList(event: AddedTo725StoreList): void {
if (!existingRoles.includes(event.params.user.toHexString()))
existingRoles.push(event.params.user.toHexString())
nft.storeUpdateRole = existingRoles
nft.eventIndex = event.logIndex.toI32()
nft.save()
}
@ -178,6 +187,7 @@ export function handleRemovedFrom725StoreList(
if (role !== event.params.user.toHexString()) newList.push(role)
}
nft.storeUpdateRole = newList
nft.eventIndex = event.logIndex.toI32()
nft.save()
}
@ -192,6 +202,7 @@ export function handleAddedToCreateERC20List(
if (!existingRoles.includes(event.params.user.toHexString()))
existingRoles.push(event.params.user.toHexString())
nft.erc20DeployerRole = existingRoles
nft.eventIndex = event.logIndex.toI32()
nft.save()
}
@ -210,6 +221,7 @@ export function handleRemovedFromCreateERC20List(
if (role !== event.params.user.toHexString()) newList.push(role)
}
nft.erc20DeployerRole = newList
nft.eventIndex = event.logIndex.toI32()
nft.save()
}
@ -222,6 +234,7 @@ export function handleAddedToMetadataList(event: AddedToMetadataList): void {
if (!existingRoles.includes(event.params.user.toHexString()))
existingRoles.push(event.params.user.toHexString())
nft.metadataRole = existingRoles
nft.eventIndex = event.logIndex.toI32()
nft.save()
}
@ -240,6 +253,7 @@ export function handleRemovedFromMetadataList(
if (role !== event.params.user.toHexString()) newList.push(role)
}
nft.metadataRole = newList
nft.eventIndex = event.logIndex.toI32()
nft.save()
}
@ -250,6 +264,7 @@ export function handleCleanedPermissions(event: CleanedPermissions): void {
nft.erc20DeployerRole = newList
nft.storeUpdateRole = newList
nft.managerRole = newList
nft.eventIndex = event.logIndex.toI32()
nft.save()
}
@ -260,15 +275,16 @@ export function handleNftTransferred(event: Transfer): void {
const newOwner = getUser(event.params.to.toHexString())
nft.owner = newOwner.id
nft.save()
const transferId = `${nft.address}-${event.transaction.hash.toHex()}-${
event.logIndex
}`
const eventIndex: number = event.logIndex.toI32()
const transferId = `${
nft.address
}-${event.transaction.hash.toHex()}-${eventIndex}`
const newTransfer = new NftTransferHistory(transferId)
newTransfer.oldOwner = oldOwner
newTransfer.nft = nft.id
newTransfer.newOwner = newOwner.id
newTransfer.txId = event.transaction.hash.toHex()
newTransfer.eventIndex = event.logIndex.toI32()
newTransfer.timestamp = event.block.timestamp.toI32()
newTransfer.block = event.block.number.toI32()
newTransfer.save()

View File

@ -57,7 +57,8 @@ export function updateFixedRateExchangeSupply(
export function getUpdateOrSwapId(
txAddress: string,
exchangeId: string
exchangeId: string,
eventIndex: number
): string {
return `${txAddress}-${exchangeId}`
return `${txAddress}-${exchangeId}-${eventIndex}`
}

View File

@ -1,11 +1,12 @@
import { Order } from '../../@types/schema'
import { Order, OrderReuse } from '../../@types/schema'
export function getOrderId(
tx: string,
tokenAddress: string,
fromAddress: string
fromAddress: string,
eventIndex: number
): string {
return `${tx}-${tokenAddress}-${fromAddress}`
return `${tx}-${tokenAddress}-${fromAddress}-${eventIndex}`
}
export function createOrder(orderId: string): Order {
@ -16,12 +17,53 @@ export function createOrder(orderId: string): Order {
export function getOrder(
transactionHash: string,
address: string,
transactionFrom: string
transactionFrom: string,
eventIndex: number
): Order {
const orderId = getOrderId(transactionHash, address, transactionFrom)
const orderId = getOrderId(
transactionHash,
address,
transactionFrom,
eventIndex
)
let newOrder = Order.load(orderId)
if (newOrder === null) {
newOrder = createOrder(orderId)
}
return newOrder
}
export function searchOrderForEvent(
transactionHash: string,
address: string,
transactionFrom: string,
eventIndex: number
): Order | null {
for (let i = eventIndex; i >= 0; i--) {
const orderId = getOrderId(transactionHash, address, transactionFrom, i)
const order = Order.load(orderId)
if (order && order.datatoken == address) {
return order
}
}
return null
}
export function searchOrderReusedForEvent(
transactionHash: string,
eventAddress: string,
eventIndex: number
): OrderReuse | null {
for (let i = eventIndex; i >= 0; i--) {
const orderReused = OrderReuse.load(`${transactionHash}-${i}`)
if (!orderReused) {
continue
}
const order = Order.load(orderReused.order)
if (order && order.datatoken == eventAddress) {
return orderReused
}
}
return null
}

View File

@ -30,6 +30,7 @@ export function createToken(address: Address, isDatatoken: boolean): Token {
token.createdTimestamp = 0
token.block = 0
token.tx = ''
token.eventIndex = 0
token.save()
return token
}
@ -60,6 +61,7 @@ export function createNftToken(address: Address): Nft {
token.tx = ''
token.orderCount = BigInt.zero()
token.hasMetadata = false
token.eventIndex = 0
token.save()
addNft()
return token
@ -93,6 +95,7 @@ export function getNftTokenWithID(tokenId: string): Nft {
nftToken.tx = ''
nftToken.orderCount = BigInt.zero()
nftToken.hasMetadata = false
nftToken.eventIndex = 0
nftToken.save()
addNft()
}

View File

@ -38,6 +38,7 @@ export function getveAllocateUser(
allocateUser.firstContact = event.block.timestamp.toI32()
allocateUser.tx = event.transaction.hash.toHex()
allocateUser.eventIndex = event.logIndex.toI32()
allocateUser.block = event.block.number.toI32()
allocateUser.lastContact = 0
const veOcean = getveOCEAN(sender)
@ -60,6 +61,7 @@ export function getveAllocateId(
allocateId.firstContact = event.block.timestamp.toI32()
allocateId.tx = event.transaction.hash.toHex()
allocateId.eventIndex = event.logIndex.toI32()
allocateId.block = event.block.number.toI32()
allocateId.lastContact = 0
allocateId.chainId = BigInt.zero()
@ -87,6 +89,7 @@ export function getveAllocation(
veAllocation.firstContact = event.block.timestamp.toI32()
veAllocation.tx = event.transaction.hash.toHex()
veAllocation.eventIndex = event.logIndex.toI32()
veAllocation.block = event.block.number.toI32()
veAllocation.lastContact = 0
@ -103,16 +106,17 @@ export function writeveAllocationUpdate(
allocationType: string,
amount: BigDecimal
): VeAllocationUpdate {
const tx = event.transaction.hash.toHex()
let allocationUpdate = VeAllocationUpdate.load(tx + '-' + veAllocationId)
const id = `${event.transaction.hash.toHex()}-${veAllocationId}-${event.logIndex.toString()}`
let allocationUpdate = VeAllocationUpdate.load(id)
if (allocationUpdate === null) {
allocationUpdate = new VeAllocationUpdate(tx + '-' + veAllocationId)
allocationUpdate = new VeAllocationUpdate(id)
allocationUpdate.veAllocation = veAllocationId
allocationUpdate.type = allocationType
allocationUpdate.allocatedTotal = amount
allocationUpdate.timestamp = event.block.timestamp.toI32()
allocationUpdate.tx = event.transaction.hash.toHex()
allocationUpdate.eventIndex = event.logIndex.toI32()
allocationUpdate.block = event.block.number.toI32()
allocationUpdate.save()
@ -140,10 +144,8 @@ export function getveDelegation(
}
return veDelegation
}
export function getDeposit(id: string): VeDeposit {
let deposit = VeDeposit.load(id)
if (deposit === null) {
deposit = new VeDeposit(id)
deposit.provider = ''
@ -153,6 +155,7 @@ export function getDeposit(id: string): VeDeposit {
deposit.type = BigInt.zero()
deposit.timestamp = BigInt.zero()
deposit.tx = ''
deposit.eventIndex = 0
deposit.block = 0
// do not save it
// deposit.save()

View File

@ -40,6 +40,7 @@ export function handleDelegation(event: DelegateBoost): void {
veDelegationUpdate.block = event.block.number.toI32()
veDelegationUpdate.timestamp = event.block.timestamp.toI32()
veDelegationUpdate.tx = event.transaction.hash.toHex()
veDelegationUpdate.eventIndex = event.logIndex.toI32()
veDelegationUpdate.amount = veDelegation.amount
veDelegationUpdate.cancelTime = _cancelTime
veDelegationUpdate.expireTime = _expireTime
@ -79,6 +80,7 @@ export function handleExtendBoost(event: ExtendBoost): void {
veDelegationUpdate.block = event.block.number.toI32()
veDelegationUpdate.timestamp = event.block.timestamp.toI32()
veDelegationUpdate.tx = event.transaction.hash.toHex()
veDelegationUpdate.eventIndex = event.logIndex.toI32()
veDelegationUpdate.amount = veDelegation.amount
veDelegationUpdate.cancelTime = _cancelTime
veDelegationUpdate.expireTime = _expireTime
@ -111,6 +113,7 @@ export function handleBurnBoost(event: BurnBoost): void {
veDelegationUpdate.block = event.block.number.toI32()
veDelegationUpdate.timestamp = event.block.timestamp.toI32()
veDelegationUpdate.tx = event.transaction.hash.toHex()
veDelegationUpdate.eventIndex = event.logIndex.toI32()
veDelegationUpdate.amount = veDelegation.amount
veDelegationUpdate.cancelTime = veDelegation.cancelTime
veDelegationUpdate.expireTime = veDelegation.expireTime

View File

@ -27,6 +27,7 @@ export function handleClaimed(event: Claimed): void {
claim.block = event.block.number.toI32()
claim.tx = event.transaction.hash.toHex()
claim.eventIndex = event.logIndex.toI32()
claim.timestamp = event.block.timestamp
claim.save()
}
@ -44,6 +45,7 @@ export function handleCheckpoint(event: CheckpointToken): void {
checkpoint.sender = event.transaction.from.toHexString()
checkpoint.block = event.block.number.toI32()
checkpoint.tx = event.transaction.hash.toHex()
checkpoint.eventIndex = event.logIndex.toI32()
checkpoint.timestamp = event.params.time
checkpoint.VeFeeDistributor = distributor.id
checkpoint.save()

View File

@ -68,6 +68,7 @@ export function handleWithdraw(event: Withdraw): void {
deposit.timestamp = ts
deposit.block = event.block.number.toI32()
deposit.tx = event.transaction.hash.toHex()
deposit.eventIndex = event.logIndex.toI32()
deposit.sender = event.transaction.from.toHex()
deposit.veOcean = veOCEAN.id
deposit.totalOceanLocked = totalOceanLocked.plus(deposit.value) // it's already negated above

View File

@ -38,6 +38,8 @@ templates:
handler: handlePublishMarketFee
- event: PublishMarketFeeChanged(address,address,address,uint256)
handler: handlePublishMarketFeeChanged
- event: ConsumeMarketFee(indexed address,indexed address,uint256)
handler: handleConsumeMarketFee
- event: AddedMinter(indexed address,indexed address,uint256,uint256)
handler: handleAddedMinter
- event: AddedPaymentManager(indexed address,indexed address,uint256,uint256)

View File

@ -159,6 +159,7 @@ describe('DFRewards tests', async () => {
}
type
tx
eventIndex
}
}
}`
@ -175,6 +176,7 @@ describe('DFRewards tests', async () => {
)
assert(info[0].history[0].amount === '100')
assert(info[0].history[0].tx === tx.transactionHash.toLowerCase())
assert(info[0].history[0].eventIndex === tx.events.Allocated.logIndex)
assert(info[0].history[0].type === 'Allocated')
})
@ -183,7 +185,7 @@ describe('DFRewards tests', async () => {
user2,
datatokenAddress1
)
await dfRewards.claimRewards(user2, user2, datatokenAddress1)
const tx = await dfRewards.claimRewards(user2, user2, datatokenAddress1)
const user2Balance = await dfRewards.getAvailableRewards(
user2,
@ -219,6 +221,7 @@ describe('DFRewards tests', async () => {
}
type
tx
eventIndex
}
}
}`
@ -235,5 +238,6 @@ describe('DFRewards tests', async () => {
)
assert(info[0].history[0].amount === expectedReward)
assert(info[0].history[0].type === 'Claimed')
assert(info[0].history[0].eventIndex === tx.events.Claimed.logIndex)
})
})

View File

@ -135,7 +135,7 @@ describe('Datatoken tests', async () => {
datatokenAddress = result.events.TokenCreated.returnValues[0].toLowerCase()
// Check values before updating metadata
await sleep(2000)
await sleep(3000)
const initialQuery = {
query: `query {
token(id: "${datatokenAddress}"){
@ -161,6 +161,7 @@ describe('Datatoken tests', async () => {
dispensers {id},
createdTimestamp,
tx,
eventIndex,
block,
lastPriceValue
}}`
@ -214,6 +215,10 @@ describe('Datatoken tests', async () => {
assert(dt.block >= blockNumber, 'incorrect value for: block')
assert(dt.block < blockNumber + 50, 'incorrect value for: block')
assert(dt.lastPriceValue === '0', 'incorrect value for: lastPriceValue')
assert(
dt.eventIndex !== null && dt.eventIndex > 0,
'incorrect value for: eventIndex'
)
})
it('Correct Datatoken fields after updating metadata', async () => {
@ -247,7 +252,7 @@ describe('Datatoken tests', async () => {
)
// Check values before updating metadata
await sleep(2000)
await sleep(3000)
const initialQuery = {
query: `query {
token(id: "${datatokenAddress}"){
@ -273,6 +278,7 @@ describe('Datatoken tests', async () => {
dispensers {id},
createdTimestamp,
tx,
eventIndex,
block,
lastPriceValue
}}`
@ -281,7 +287,7 @@ describe('Datatoken tests', async () => {
method: 'POST',
body: JSON.stringify(initialQuery)
})
await sleep(2000)
await sleep(3000)
const dt = (await initialResponse.json()).data.token
const tx: TransactionReceipt = await web3.eth.getTransactionReceipt(dt.tx)
@ -325,10 +331,41 @@ describe('Datatoken tests', async () => {
assert(dt.block >= blockNumber, 'incorrect value for: block')
assert(dt.block < blockNumber + 50, 'incorrect value for: block')
assert(dt.lastPriceValue === '0', 'incorrect value for: lastPriceValue')
assert(
dt.eventIndex !== null && dt.eventIndex > 0,
'incorrect value for: eventIndex'
)
})
it('Check datatoken orders are updated correctly after publishing & ordering a datatoken', async () => {
// Start with publishing a new datatoken
it('Check datatoken orders are updated correctly after publishing & ordering a datatoken with fees', async () => {
// Publish a datatoken for publishingMarketFeeToken
const nftParams1: NftCreateData = {
name: 'newNFT1',
symbol: 'newTST1',
templateIndex,
tokenURI: '',
transferable: true,
owner: publisher
}
const erc20Params1: DatatokenCreateParams = {
templateIndex,
cap: '100000',
feeAmount: '0',
paymentCollector: ZERO_ADDRESS,
feeToken: ZERO_ADDRESS,
minter: publisher,
mpFeeAddress: ZERO_ADDRESS
}
const result1 = await Factory.createNftWithDatatoken(
publisher,
nftParams1,
erc20Params1
)
await sleep(3000)
const publishingTokenAddress = result1.events.TokenCreated.returnValues[0]
const publishingDatatoken = new Datatoken(web3, 8996)
// Start with publishing the datatoken used for startOrder
const nftParams: NftCreateData = {
name: 'newNFT',
symbol: 'newTST',
@ -340,42 +377,76 @@ describe('Datatoken tests', async () => {
const erc20Params: DatatokenCreateParams = {
templateIndex,
cap: '100000',
feeAmount: '0',
feeAmount: '0.2',
paymentCollector: ZERO_ADDRESS,
feeToken: ZERO_ADDRESS,
feeToken: publishingTokenAddress,
minter: publisher,
mpFeeAddress: ZERO_ADDRESS
mpFeeAddress: publisher
}
const result = await Factory.createNftWithDatatoken(
publisher,
nftParams,
erc20Params
)
await sleep(2000)
await sleep(3000)
const newDtAddress = result.events.TokenCreated.returnValues[0]
const datatoken = new Datatoken(web3, 8996)
await datatoken.approve(
newDtAddress,
publishingTokenAddress,
'100000000000000000000000000',
user1
)
await publishingDatatoken.approve(
publishingTokenAddress,
newDtAddress,
'100000000000000000000000000',
user1
)
await datatoken.mint(newDtAddress, publisher, '100', user1)
await publishingDatatoken.mint(
publishingTokenAddress,
publisher,
'100',
user1
)
const user1balance = await datatoken.balance(newDtAddress, user1)
const user2balance = await datatoken.balance(newDtAddress, user2)
assert(Number(user1balance) === 100, 'Invalid user1 balance')
assert(Number(user2balance) === 0, 'Invalid user2 balance')
const user1balanceOfPublishing = await datatoken.balance(
publishingTokenAddress,
user1
)
const user2balanceOfPublishing = await datatoken.balance(
publishingTokenAddress,
user2
)
assert(Number(user1balanceOfPublishing) === 100, 'Invalid user1 balance')
assert(Number(user2balanceOfPublishing) === 0, 'Invalid user2 balance')
const query = {
query: `query {token(id: "${newDtAddress.toLowerCase()}"){id,orderCount,orders {id, nftOwner{id}, lastPriceToken{id}}}}`
query: `query {token(id: "${newDtAddress.toLowerCase()}"){id,orderCount,orders {id, nftOwner{id}, lastPriceToken{id}, eventIndex}, eventIndex}}`
}
await sleep(2000)
await sleep(3000)
let response = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(query)
})
await sleep(3000)
const initialToken = (await response.json()).data.token
assert(initialToken, 'Invalid initialToken')
assert(initialToken.orderCount === '0', 'Invalid initial orderCount')
assert(initialToken.orders.length === 0, 'Invalid initial orders')
assert(
initialToken.eventIndex !== null && initialToken.eventIndex > 0,
'Invalid eventIndex'
)
const providerData = JSON.stringify({ timeout: 0 })
const providerFeeToken = ZERO_ADDRESS
@ -400,22 +471,31 @@ describe('Datatoken tests', async () => {
providerData: web3.utils.toHex(web3.utils.asciiToHex(providerData)),
validUntil: providerValidUntil
}
const consumeMarketFees = {
consumeMarketFeeAddress: publisher,
consumeMarketFeeToken: publishingTokenAddress,
consumeMarketFeeAmount: '20000'
}
assert(setProviderFee, 'Invalid setProviderFee')
const orderTx = await datatoken.startOrder(
newDtAddress,
user1,
user2,
1,
setProviderFee
setProviderFee,
consumeMarketFees
)
assert(orderTx, 'Invalid orderTx')
const orderId = `${orderTx.transactionHash.toLowerCase()}-${newDtAddress.toLowerCase()}-${user1.toLowerCase()}`
const orderId = `${orderTx.transactionHash.toLowerCase()}-${newDtAddress.toLowerCase()}-${user1.toLowerCase()}-${orderTx.events.OrderStarted.logIndex.toFixed(
1
)}`
await sleep(2000)
await sleep(3000)
response = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(query)
})
await sleep(3000)
const token = (await response.json()).data.token
@ -424,5 +504,48 @@ describe('Datatoken tests', async () => {
assert(token.orders[0].id === orderId)
assert(token.orders[0].lastPriceToken.id === ZERO_ADDRESS)
assert(token.orders[0].nftOwner.id === publisher, 'invalid nftOwner')
assert(token.orders[0].eventIndex === 0, 'invalid order eventIndex')
assert(token.eventIndex !== null, 'Invalid eventIndex')
assert(
token.eventIndex !== token.orders[0].eventIndex,
'Invalid log indeces'
)
const orderQuery = {
query: `query {order(id:"${orderId}"){id, publishingMarket{id}, publishingMarketToken{id}, publishingMarketAmmount, consumerMarket{id}, consumerMarketToken{id}, consumerMarketAmmount, eventIndex}}`
}
await sleep(3000)
const orderResponse = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(orderQuery)
})
await sleep(3000)
const queryResult = await orderResponse.json()
const order = queryResult.data.order
assert(
order.publishingMarket.id === erc20Params.mpFeeAddress.toLowerCase(),
'incorrect publish market fee address'
)
assert(
order.publishingMarketToken.id === erc20Params.feeToken.toLowerCase(),
'incorrect publish market fee token'
)
assert(
order.publishingMarketAmmount === erc20Params.feeAmount,
'incorrect publish market fee amount'
)
assert(
order.consumerMarket.id ===
consumeMarketFees.consumeMarketFeeAddress.toLowerCase(),
'incorrect consume market fee address'
)
assert(
order.consumerMarketToken.id ===
consumeMarketFees.consumeMarketFeeToken.toLowerCase(),
'incorrect consume market fee token'
)
assert(
order.consumerMarketAmmount === '0.00000000000002',
'incorrect consume market fee amount'
)
})
})

View File

@ -138,6 +138,7 @@ describe('Dispenser tests', async () => {
transferable,
createdTimestamp,
tx,
eventIndex,
block,
orderCount}}`
}
@ -172,6 +173,10 @@ describe('Dispenser tests', async () => {
assert(nft.block >= blockNumber, 'incorrect value for: block')
assert(nft.block < blockNumber + 50, 'incorrect value for: block')
assert(nft.orderCount === '0', 'incorrect value for: orderCount')
assert(
nft.eventIndex !== null && nft.eventIndex > 0,
'Invalid eventIndex for NFT creation'
)
})
it('Test all DT Fields after deploying', async () => {
@ -201,6 +206,7 @@ describe('Dispenser tests', async () => {
dispensers {id},
createdTimestamp,
tx,
eventIndex,
block,
lastPriceValue
}}`
@ -254,6 +260,10 @@ describe('Dispenser tests', async () => {
assert(dt.block >= blockNumber, 'incorrect value for: block')
assert(dt.block < blockNumber + 50, 'incorrect value for: block')
assert(dt.lastPriceValue === '0', 'incorrect value for: lastPriceValue')
assert(
dt.eventIndex !== null && dt.eventIndex > 0,
'incorrect value for: eventIndex'
)
})
it('Make user1 minter', async () => {
@ -262,15 +272,16 @@ describe('Dispenser tests', async () => {
assert((await datatoken.getPermissions(dtAddress, user1)).minter === true)
await sleep(sleepMs)
const minterQuery = {
query: `query {token(id: "${dtAddress}"){minter{id}}}`
query: `query {token(id: "${dtAddress}"){minter{id}, eventIndex}}`
}
const minterResponse = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(minterQuery)
})
const minter = (await minterResponse.json()).data.token.minter
assert(minter[1] === user1, 'incorrect value for: minter')
const dt = (await minterResponse.json()).data.token
assert(dt.minter[1] === user1, 'incorrect value for: minter')
assert(dt.eventIndex !== null, 'incorrect value for: eventIndex')
})
it('Create dispenser', async () => {
@ -310,6 +321,7 @@ describe('Dispenser tests', async () => {
block
createdTimestamp
tx
eventIndex
dispenses {
id
}
@ -336,13 +348,17 @@ describe('Dispenser tests', async () => {
assert(response.createdTimestamp >= time, 'incorrect: createdTimestamp')
assert(response.createdTimestamp < time + 15, 'incorrect: createdTimestamp')
assert(response.tx === tx.transactionHash, 'incorrect value for: tx')
assert(
response.eventIndex !== null && response.eventIndex > 0,
'incorrect value for: eventIndex'
)
assert(response.dispenses.length === 0, 'incorrect value for: dispenses')
assert(response.__typename === 'Dispenser', 'incorrect value: __typename')
})
it('Deactivates dispenser', async () => {
const deactiveQuery = {
query: `query {dispenser(id: "${dispenserId}"){active}}`
query: `query {dispenser(id: "${dispenserId}"){active, eventIndex}}`
}
const initialResponse = await fetch(subgraphUrl, {
@ -353,7 +369,7 @@ describe('Dispenser tests', async () => {
assert(initialActive === true, 'incorrect value for: initialActive')
// Deactivate exchange
await dispenser.deactivate(dtAddress, publisher)
const tx = await dispenser.deactivate(dtAddress, publisher)
const status = await dispenser.status(dtAddress)
assert(status.active === false, 'Dispenser is still active')
await sleep(sleepMs)
@ -362,23 +378,29 @@ describe('Dispenser tests', async () => {
method: 'POST',
body: JSON.stringify(deactiveQuery)
})
const updatedActive = (await updatedResponse.json()).data.dispenser.active
assert(updatedActive === false, 'incorrect value for: updatedActive')
const updatedActive = (await updatedResponse.json()).data.dispenser
assert(updatedActive.active === false, 'incorrect value for: updatedActive')
assert(updatedActive.eventIndex !== null, 'incorrect value for: eventIndex')
assert(
updatedActive.eventIndex === tx.events.DispenserDeactivated.logIndex,
'incorrect value for: eventIndex'
)
})
it('Activates exchange', async () => {
it('Activates dispenser', async () => {
const activeQuery = {
query: `query {dispenser(id: "${dispenserId}"){active}}`
query: `query {dispenser(id: "${dispenserId}"){active, eventIndex}}`
}
const initialResponse = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(activeQuery)
})
const initialActive = (await initialResponse.json()).data.dispenser.active
assert(initialActive === false, 'incorrect value for: initialActive')
const initialActive = (await initialResponse.json()).data.dispenser
assert(initialActive.active === false, 'incorrect value for: initialActive')
assert(initialActive.eventIndex !== null, 'incorrect value for: eventIndex')
// Activate exchange
await dispenser.activate(dtAddress, '100', '100', publisher)
// Activate dispenser
const tx = await dispenser.activate(dtAddress, '100', '100', publisher)
await sleep(sleepMs)
// Check the updated value for active
@ -386,8 +408,13 @@ describe('Dispenser tests', async () => {
method: 'POST',
body: JSON.stringify(activeQuery)
})
const updatedActive = (await updatedResponse.json()).data.dispenser.active
assert(updatedActive === true, 'incorrect value for: updatedActive')
const updatedActive = (await updatedResponse.json()).data.dispenser
assert(updatedActive.active === true, 'incorrect value for: updatedActive')
assert(updatedActive.eventIndex !== null, 'incorrect value for: eventIndex')
assert(
updatedActive.eventIndex === tx.events.DispenserActivated.logIndex,
'incorrect value for: eventIndex'
)
})
it('User2 gets datatokens from the dispenser', async () => {
@ -402,6 +429,7 @@ describe('Dispenser tests', async () => {
block
createdTimestamp
tx
eventIndex
__typename
}}}`
}
@ -410,6 +438,7 @@ describe('Dispenser tests', async () => {
method: 'POST',
body: JSON.stringify(dispenseQuery)
})
await sleep(sleepMs)
const before = (await response1.json()).data.dispenser.dispenses
assert(before.length === 0, 'incorrect value for: dispenses')
@ -423,7 +452,13 @@ describe('Dispenser tests', async () => {
})
const dispense = (await response2.json()).data.dispenser.dispenses[0]
assert(dispense.id === `${tx.transactionHash}-${dispenserId}`, 'wrong id')
assert(
dispense.id ===
`${
tx.transactionHash
}-${dispenserId}-${tx.events.TokensDispensed.logIndex.toFixed(1)}`,
'wrong id'
)
assert(dispense.dispenser.id === dispenserId, 'incorrect value for: user')
assert(dispense.user.id === user2, 'incorrect value for: user')
assert(dispense.amount === amount, 'incorrect value for: user')
@ -431,6 +466,7 @@ describe('Dispenser tests', async () => {
assert(dispense.createdTimestamp >= time, 'incorrect: createdTimestamp')
assert(dispense.createdTimestamp < time + 15, 'incorrect: createdTimestamp')
assert(dispense.tx === tx.transactionHash, 'incorrect value for: tx')
assert(dispense.eventIndex !== null, 'incorrect value for: eventIndex')
assert(dispense.__typename === 'DispenserTransaction', 'wrong __typename')
})
@ -440,21 +476,21 @@ describe('Dispenser tests', async () => {
// Check balance after owner withdraw
const balanceQuery = {
query: `query {dispenser(id: "${dispenserId}"){balance}}`
query: `query {dispenser(id: "${dispenserId}"){balance, eventIndex}}`
}
const response = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(balanceQuery)
})
const balance = (await response.json()).data.dispenser.balance
assert(balance === '0', 'incorrect value for: balance')
const balance = (await response.json()).data.dispenser
assert(balance.balance === '0', 'incorrect value for: balance')
assert(balance.eventIndex !== null, 'incorrect value for: eventIndex')
})
it('Updates allowed swapper', async () => {
const swapperQuery = {
query: `query {dispenser(id: "${dispenserId}"){allowedSwapper}}`
query: `query {dispenser(id: "${dispenserId}"){allowedSwapper, eventIndex}}`
}
// Check initial allowedSwapper
const swapperResponse1 = await fetch(subgraphUrl, {
@ -468,7 +504,7 @@ describe('Dispenser tests', async () => {
'incorrect value for: allowedSwapper'
)
await dispenser.setAllowedSwapper(dtAddress, publisher, user1)
const tx = await dispenser.setAllowedSwapper(dtAddress, publisher, user1)
await sleep(sleepMs)
const swapperResponse2 = await fetch(subgraphUrl, {
@ -476,8 +512,16 @@ describe('Dispenser tests', async () => {
body: JSON.stringify(swapperQuery)
})
const allowedSwapper2 = (await swapperResponse2.json()).data.dispenser
.allowedSwapper
assert(allowedSwapper2 === user1, 'incorrect value for: allowedSwapper 2')
assert(
allowedSwapper2.allowedSwapper === user1,
'incorrect value for: allowedSwapper 2'
)
assert(
allowedSwapper2.eventIndex !== null &&
allowedSwapper2.eventIndex ===
tx.events.DispenserAllowedSwapperChanged.logIndex,
'incorrect value for: eventIndex'
)
})
})

View File

@ -151,6 +151,7 @@ describe('Fixed Rate Exchange tests', async () => {
transferable,
createdTimestamp,
tx,
eventIndex,
block,
orderCount}}`
}
@ -191,6 +192,10 @@ describe('Fixed Rate Exchange tests', async () => {
assert(nft.block >= blockNumber, 'incorrect value for: block')
assert(nft.block < blockNumber + 50, 'incorrect value for: block')
assert(nft.orderCount === '0', 'incorrect value for: orderCount')
assert(
nft.eventIndex !== null && nft.eventIndex > 0,
'incorrect value for: eventIndex'
)
})
it('Test DT Fields after deploying Fixed rate exchange', async () => {
@ -220,6 +225,7 @@ describe('Fixed Rate Exchange tests', async () => {
dispensers {id},
createdTimestamp,
tx,
eventIndex,
block,
lastPriceToken,
lastPriceValue
@ -274,6 +280,10 @@ describe('Fixed Rate Exchange tests', async () => {
assert(dt.block >= blockNumber, 'incorrect value for: block')
assert(dt.block < blockNumber + 50, 'incorrect value for: block')
assert(dt.lastPriceValue === '0', 'incorrect value for: lastPriceValue')
assert(
dt.eventIndex !== null && dt.eventIndex > 0,
'incorrect value for: eventIndex'
)
})
it('Test fixedRateExchanges Fields', async () => {
@ -310,6 +320,7 @@ describe('Fixed Rate Exchange tests', async () => {
}
createdTimestamp
tx
eventIndex
block
publishMarketFeeAddress
publishMarketSwapFee
@ -385,6 +396,10 @@ describe('Fixed Rate Exchange tests', async () => {
)
assert(fixedTx.from === publisher, 'incorrect value for: tx')
assert(fixedTx.to === factoryAddress, 'incorrect value for: tx')
assert(
fixed.eventIndex !== null && fixed.eventIndex > 0,
'incorrect value for: eventIndex'
)
})
it('Updates Fixed Rate Price', async () => {
@ -398,6 +413,7 @@ describe('Fixed Rate Exchange tests', async () => {
}
oldPrice
newPrice
eventIndex
}
}}`
}
@ -422,7 +438,7 @@ describe('Fixed Rate Exchange tests', async () => {
// Update price
const newPrice = '999'
await fixedRate.setRate(publisher, exchangeId, newPrice)
const tx = await fixedRate.setRate(publisher, exchangeId, newPrice)
await sleep(sleepMs)
// Check price after first update
@ -441,10 +457,14 @@ describe('Fixed Rate Exchange tests', async () => {
)
assert(updates2.oldPrice === price1, 'incorrect value: 2nd oldPrice')
assert(updates2.newPrice === newPrice, 'incorrect value: 2nd newPrice')
assert(
updates2.eventIndex === tx.events.ExchangeRateChanged.logIndex,
'incorrect value: 2nd eventIndex'
)
// Update price a 2nd time
const newPrice2 = '1' // '5.123'
await fixedRate.setRate(publisher, exchangeId, newPrice2)
const tx2 = await fixedRate.setRate(publisher, exchangeId, newPrice2)
await sleep(sleepMs)
// Check price after 2nd update
@ -464,10 +484,14 @@ describe('Fixed Rate Exchange tests', async () => {
)
assert(updates3.oldPrice === newPrice, 'incorrect value: 3rd oldPrice')
assert(updates3.newPrice === newPrice2, 'incorrect value: 3rd newPrice')
assert(
updates3.eventIndex === tx2.events.ExchangeRateChanged.logIndex,
'incorrect value: 3nd eventIndex'
)
})
it('Deactivates exchange', async () => {
const deactiveQuery = {
query: `query {fixedRateExchange(id: "${fixedRateId}"){active}}`
query: `query {fixedRateExchange(id: "${fixedRateId}"){active, eventIndex}}`
}
const initialResponse = await fetch(subgraphUrl, {
@ -488,13 +512,17 @@ describe('Fixed Rate Exchange tests', async () => {
body: JSON.stringify(deactiveQuery)
})
const updatedActive = (await updatedResponse.json()).data.fixedRateExchange
.active
assert(updatedActive === false, 'incorrect value for: updatedActive')
assert(updatedActive.active === false, 'incorrect value for: updatedActive')
assert(
updatedActive.eventIndex !== null && updatedActive.eventIndex > 0,
'incorrect value: eventIndex'
)
})
it('Activates exchange', async () => {
const activeQuery = {
query: `query {fixedRateExchange(id: "${fixedRateId}"){active}}`
query: `query {fixedRateExchange(id: "${fixedRateId}"){active, eventIndex}}`
}
const initialResponse = await fetch(subgraphUrl, {
method: 'POST',
@ -514,13 +542,16 @@ describe('Fixed Rate Exchange tests', async () => {
body: JSON.stringify(activeQuery)
})
const updatedActive = (await updatedResponse.json()).data.fixedRateExchange
.active
assert(updatedActive === true, 'incorrect value for: updatedActive')
assert(updatedActive.active === true, 'incorrect value for: updatedActive')
assert(
updatedActive.eventIndex !== null && updatedActive.eventIndex > 0,
'incorrect value: eventIndex'
)
})
it('Activate Minting', async () => {
const mintingQuery = {
query: `query {fixedRateExchange(id: "${fixedRateId}"){withMint}}`
query: `query {fixedRateExchange(id: "${fixedRateId}"){withMint, eventIndex}}`
}
const initialResponse = await fetch(subgraphUrl, {
method: 'POST',
@ -531,7 +562,7 @@ describe('Fixed Rate Exchange tests', async () => {
assert(initialMint === null, 'incorrect value for: initialMint')
// Activate minting
await fixedRate.activateMint(publisher, exchangeId)
const tx = await fixedRate.activateMint(publisher, exchangeId)
await sleep(sleepMs)
// Check the updated value for active
@ -541,13 +572,16 @@ describe('Fixed Rate Exchange tests', async () => {
})
const updatedMint = (await updatedResponse.json()).data.fixedRateExchange
.withMint
assert(updatedMint === true, 'incorrect value for: updatedMint')
assert(updatedMint.withMint === true, 'incorrect value for: updatedMint')
assert(
updatedMint.eventIndex === tx.events.ExchangeMintStateChanged.logIndex,
'incorrect value for: eventIndex'
)
})
it('Deactivate Minting', async () => {
const mintingQuery = {
query: `query {fixedRateExchange(id: "${fixedRateId}"){withMint}}`
query: `query {fixedRateExchange(id: "${fixedRateId}"){withMint, eventIndex}}`
}
const initialResponse = await fetch(subgraphUrl, {
method: 'POST',
@ -558,7 +592,7 @@ describe('Fixed Rate Exchange tests', async () => {
assert(initialMint === true, 'incorrect value for: initialMint')
// Activate minting
await fixedRate.deactivateMint(publisher, exchangeId)
const tx = await fixedRate.deactivateMint(publisher, exchangeId)
await sleep(sleepMs)
// Check the updated value for active
@ -568,8 +602,11 @@ describe('Fixed Rate Exchange tests', async () => {
})
const updatedMint = (await updatedResponse.json()).data.fixedRateExchange
.withMint
assert(updatedMint === false, 'incorrect value for: updatedMint')
assert(updatedMint.withMint === false, 'incorrect value for: updatedMint')
assert(
updatedMint.eventIndex === tx.events.ExchangeMintStateChanged.logIndex,
'incorrect value for: eventIndex'
)
})
it('User1 buys a datatoken', async () => {
@ -584,6 +621,7 @@ describe('Fixed Rate Exchange tests', async () => {
block
createdTimestamp
tx
eventIndex
oceanFeeAmount
marketFeeAmount
consumeMarketFeeAmount
@ -654,7 +692,11 @@ describe('Fixed Rate Exchange tests', async () => {
const swappedAmount = web3.utils.fromWei(
new BN(tx.returnValues.baseTokenSwappedAmount)
)
assert(swaps.id === `${tx.transactionHash}-${fixedRateId}`, 'incorrect: id')
assert(
swaps.id ===
`${tx.transactionHash}-${fixedRateId}-${tx.logIndex.toFixed(1)}`,
'incorrect: id'
)
assert(swaps.exchangeId.id === fixedRateId, 'incorrect: exchangeId')
assert(swaps.by.id === user1, 'incorrect value for: id')
assert(swaps.baseTokenAmount === swappedAmount, 'incorrect baseTokenAmount')
@ -669,6 +711,7 @@ describe('Fixed Rate Exchange tests', async () => {
'wrong consumeMarketFeeAmount'
)
assert(swaps.tx === tx.transactionHash, 'incorrect value for: tx')
assert(swaps.eventIndex === tx.logIndex, 'incorrect value for: eventIndex')
assert(swaps.__typename === 'FixedRateExchangeSwap', 'incorrect __typename')
})
it('User1 sells a datatoken', async () => {
@ -691,6 +734,7 @@ describe('Fixed Rate Exchange tests', async () => {
block
createdTimestamp
tx
eventIndex
oceanFeeAmount
__typename
}
@ -705,7 +749,11 @@ describe('Fixed Rate Exchange tests', async () => {
const swappedAmount = web3.utils.fromWei(
new BN(tx.returnValues.baseTokenSwappedAmount)
)
assert(swaps.id === `${tx.transactionHash}-${fixedRateId}`, 'incorrect: id')
assert(
swaps.id ===
`${tx.transactionHash}-${fixedRateId}-${tx.logIndex.toFixed(1)}`,
'incorrect: id'
)
assert(swaps.exchangeId.id === fixedRateId, 'incorrect: exchangeId')
assert(swaps.by.id === user1, 'incorrect value for: id')
assert(swaps.baseTokenAmount === swappedAmount, 'incorrect baseTokenAmount')
@ -715,12 +763,13 @@ describe('Fixed Rate Exchange tests', async () => {
assert(swaps.createdTimestamp < time + 25, 'incorrect: createdTimestamp 2')
assert(swaps.oceanFeeAmount === oceanFeeAmount, 'incorrect: oceanFeeAmount')
assert(swaps.tx === tx.transactionHash, 'incorrect value for: tx')
assert(swaps.eventIndex === tx.logIndex, 'incorrect value for: eventIndex')
assert(swaps.__typename === 'FixedRateExchangeSwap', 'incorrect __typename')
})
it('Updates allowed swapper', async () => {
const swapperQuery = {
query: `query {fixedRateExchange(id: "${fixedRateId}"){allowedSwapper}}`
query: `query {fixedRateExchange(id: "${fixedRateId}"){allowedSwapper, eventIndex}}`
}
// Check initial allowedSwapper
const swapperResponse1 = await fetch(subgraphUrl, {
@ -734,7 +783,7 @@ describe('Fixed Rate Exchange tests', async () => {
'incorrect value for: allowedSwapper'
)
await fixedRate.setAllowedSwapper(publisher, exchangeId, user1)
const tx = await fixedRate.setAllowedSwapper(publisher, exchangeId, user1)
await sleep(sleepMs)
const swapperResponse2 = await fetch(subgraphUrl, {
@ -742,8 +791,16 @@ describe('Fixed Rate Exchange tests', async () => {
body: JSON.stringify(swapperQuery)
})
const allowedSwapper2 = (await swapperResponse2.json()).data
.fixedRateExchange.allowedSwapper
.fixedRateExchange
assert(allowedSwapper2 === user1, 'incorrect value for: allowedSwapper 2')
assert(
allowedSwapper2.allowedSwapper === user1,
'incorrect value for: allowedSwapper 2'
)
assert(
allowedSwapper2.eventIndex ===
tx.events.ExchangeAllowedSwapperChanged.logIndex,
'incorrect value for: eventIndex'
)
})
})

View File

@ -121,7 +121,7 @@ describe('NFT tests', async () => {
datatokenAddress = result.events.TokenCreated.returnValues[0]
// Check values before updating metadata
await sleep(2000)
await sleep(3000)
nftAddress = erc721Address.toLowerCase()
const initialQuery = {
query: `query {
@ -143,6 +143,7 @@ describe('NFT tests', async () => {
transferable,
createdTimestamp,
tx,
eventIndex,
block,
orderCount}}`
}
@ -150,7 +151,7 @@ describe('NFT tests', async () => {
method: 'POST',
body: JSON.stringify(initialQuery)
})
await sleep(2000)
await sleep(3000)
const nft = (await initialResponse.json()).data.nft
const tx: TransactionReceipt = await web3.eth.getTransactionReceipt(nft.tx)
assert(nft.id === nftAddress, 'incorrect value for: id')
@ -182,6 +183,10 @@ describe('NFT tests', async () => {
assert(nft.block >= blockNumber, 'incorrect value for: block')
assert(nft.block < blockNumber + 50, 'incorrect value for: block')
assert(nft.orderCount === '0', 'incorrect value for: orderCount')
assert(
nft.eventIndex !== null && nft.eventIndex > 0,
'Invalid eventIndex for NFT creation'
)
})
it('Update metadata', async () => {
@ -215,7 +220,7 @@ describe('NFT tests', async () => {
)
// graph tests here
await sleep(2000)
await sleep(3000)
const query = {
query: `query {
nft(id:"${nftAddress}"){
@ -236,6 +241,7 @@ describe('NFT tests', async () => {
transferable,
createdTimestamp,
tx,
eventIndex,
block,
orderCount}}`
}
@ -243,6 +249,7 @@ describe('NFT tests', async () => {
method: 'POST',
body: JSON.stringify(query)
})
await sleep(3000)
const updatedNft = (await response.json()).data.nft
const tx: TransactionReceipt = await web3.eth.getTransactionReceipt(
updatedNft.tx
@ -288,6 +295,10 @@ describe('NFT tests', async () => {
assert(updatedNft.block >= blockNumber, 'incorrect value for: block')
assert(updatedNft.block < blockNumber + 50, 'incorrect value for: block')
assert(updatedNft.orderCount === '0', 'incorrect value for: orderCount')
assert(
updatedNft.eventIndex !== null && updatedNft.eventIndex > 0,
'Invalid eventIndex for NFT update'
)
})
it('Set a key/value in erc725 store', async () => {
@ -301,6 +312,7 @@ describe('NFT tests', async () => {
key
value
}
eventIndex
}
}`
}
@ -310,5 +322,9 @@ describe('NFT tests', async () => {
})
const updatedNft = (await response.json()).data.nft
assert(updatedNft.nftData.key !== null, 'incorrect value for key')
assert(
updatedNft.eventIndex !== null && updatedNft.eventIndex > 0,
'Invalid eventIndex for NFT update'
)
})
})

View File

@ -152,18 +152,24 @@ describe('Simple Publish & consume test', async () => {
)
// graph tests here
await sleep(2000)
await sleep(3000)
const graphNftToken = erc721Address.toLowerCase()
const query = {
query: `query {
nft(id:"${graphNftToken}"){symbol,id}}`
nft(id:"${graphNftToken}"){symbol,id,eventIndex}}`
}
const response = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(query)
})
await sleep(3000)
const queryResult = await response.json()
assert(queryResult.data.nft.id === graphNftToken)
assert(
queryResult.data.nft.eventIndex !== null &&
queryResult.data.nft.eventIndex > 0,
'Invalid eventIndex for NFT creation'
)
})
it('should publish and transfer an NFT', async () => {
const nftParams: NftCreateData = {
@ -188,27 +194,34 @@ describe('Simple Publish & consume test', async () => {
nftParams,
erc20Params
)
await sleep(2000)
await sleep(3000)
const erc721Address = result.events.NFTCreated.returnValues[0]
const datatokenAddress = result.events.TokenCreated.returnValues[0]
const graphNftToken = erc721Address.toLowerCase()
const queryOriginalOwner = {
query: `query {
nft(id:"${graphNftToken}"){symbol,id,owner{id}}}`
nft(id:"${graphNftToken}"){symbol,id,owner{id},eventIndex}}`
}
const initialResponse = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(queryOriginalOwner)
})
await sleep(3000)
const initialResult = await initialResponse.json()
// Checking original owner account has been set correctly
assert(
initialResult.data.nft.owner.id.toLowerCase() ===
publisherAccount.toLowerCase()
)
const chain = await web3.eth.getChainId()
assert(
initialResult.data.nft.eventIndex !== null &&
initialResult.data.nft.eventIndex > 0,
'Invalid eventIndex for NFT creation'
)
// create the files encrypted string
const chain = await web3.eth.getChainId()
let providerResponse = await ProviderInstance.encrypt(
assetUrl,
chain,
@ -235,21 +248,27 @@ describe('Simple Publish & consume test', async () => {
encryptedResponse,
'0x' + metadataHash
)
await sleep(2000)
await sleep(3000)
// Transfer the NFT
await nft.transferNft(graphNftToken, publisherAccount, newOwnerAccount)
await sleep(2000)
await sleep(3000)
const query2 = {
query: `query {
nft(id:"${graphNftToken}"){symbol,id,owner{id}, transferable}}`
nft(id:"${graphNftToken}"){symbol,id,owner{id}, transferable, eventIndex}}`
}
const response = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(query2)
})
await sleep(3000)
const queryResult = await response.json()
assert(queryResult.data.nft.owner.id === newOwnerAccount)
assert(
queryResult.data.nft.eventIndex !== null &&
queryResult.data.nft.eventIndex > 0,
'Invalid eventIndex for NFT creation'
)
})
it('should save provider fees after startOrder is called', async () => {
@ -287,18 +306,20 @@ describe('Simple Publish & consume test', async () => {
1,
setProviderFee
)
const orderId = `${orderTx.transactionHash.toLowerCase()}-${datatokenAddress.toLowerCase()}-${user1.toLowerCase()}`
await sleep(3000)
const orderId = `${orderTx.transactionHash.toLowerCase()}-${datatokenAddress.toLowerCase()}-${user1.toLowerCase()}-${orderTx.events.OrderStarted.logIndex.toFixed(
1
)}`
const query = {
query: `query {order(id:"${orderId}"){id, providerFee, lastPriceToken{id}}}`
query: `query {order(id:"${orderId}"){id, providerFee, lastPriceToken{id}, eventIndex}}`
}
await sleep(2000)
await sleep(3000)
const response = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(query)
})
await sleep(3000)
const queryResult = await response.json()
const providerFeeJSON = JSON.parse(queryResult.data.order.providerFee)
@ -321,6 +342,10 @@ describe('Simple Publish & consume test', async () => {
setProviderFee.providerFeeToken.toLowerCase(),
'Wrong providerFeeToken set'
)
assert(
queryResult.data.order.eventIndex !== null,
'Invalid eventIndex for order'
)
})
it('should save provider fees after calling reuseOrder on a using a previous txId', async () => {
@ -361,16 +386,19 @@ describe('Simple Publish & consume test', async () => {
assert(orderTx.transactionHash, 'Failed to start order')
// Check initial provider fee has been set correctly
const orderId = `${orderTx.transactionHash.toLowerCase()}-${datatokenAddress.toLowerCase()}-${user4.toLowerCase()}`
const orderId = `${orderTx.transactionHash.toLowerCase()}-${datatokenAddress.toLowerCase()}-${user4.toLowerCase()}-${orderTx.events.OrderStarted.logIndex.toFixed(
1
)}`
const initialQuery = {
query: `query {order(id:"${orderId}"){id, providerFee, lastPriceToken{id}}}`
query: `query {order(id:"${orderId}"){id, providerFee, lastPriceToken{id}, eventIndex}}`
}
await sleep(2000)
await sleep(3000)
const initialResponse = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(initialQuery)
})
await sleep(3000)
const initialQueryResult = await initialResponse.json()
const initialProviderFeeJSON = JSON.parse(
initialQueryResult.data.order.providerFee
@ -393,6 +421,10 @@ describe('Simple Publish & consume test', async () => {
setInitialProviderFee.providerFeeToken.toLowerCase(),
'Wrong initial providerFeeToken set'
)
assert(
initialQueryResult.data.order.eventIndex !== null,
'Invalid eventIndex for order'
)
providerFeeAmount = '990000'
providerValidUntil = '10000'
@ -421,7 +453,7 @@ describe('Simple Publish & consume test', async () => {
const reusedOrder = await datatoken.reuseOrder(
datatokenAddress,
user2,
user4,
orderTx.transactionHash,
setNewProviderFee
)
@ -433,7 +465,11 @@ describe('Simple Publish & consume test', async () => {
// Check the new provider fee has been set in OrderReuse
const reuseQuery = {
query: `query {orderReuse(id:"${reusedOrder.transactionHash}"){id, providerFee}}`
query: `query {orderReuse(id:"${
reusedOrder.transactionHash
}-${reusedOrder.events.OrderReused.logIndex.toFixed(
1
)}"){id, providerFee, eventIndex}}`
}
await sleep(2000)
@ -463,5 +499,17 @@ describe('Simple Publish & consume test', async () => {
setNewProviderFee.providerFeeToken.toLowerCase(),
'New providerFeeToken set in reuse order is wrong'
)
assert(
reuseQueryResult.data.orderReuse.eventIndex !== null,
'Invalid eventIndex for reuse order'
)
assert(
reuseQueryResult.data.orderReuse.eventIndex === 0,
'Invalid reuse order event index'
)
assert(
initialQueryResult.data.order.eventIndex === 0,
'Invalid start order event index'
)
})
})

View File

@ -69,18 +69,23 @@ describe('Tests coverage without provider/aquarius', async () => {
const erc721Address = result.events.NFTCreated.returnValues[0]
// graph tests here
await sleep(2000)
await sleep(3000)
const graphNftToken = erc721Address.toLowerCase()
const query = {
query: `query {
nft(id:"${graphNftToken}"){symbol,id}}`
nft(id:"${graphNftToken}"){symbol,id,eventIndex}}`
}
const response = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(query)
})
await sleep(3000)
const queryResult = await response.json()
assert(queryResult.data.nft.id === graphNftToken)
assert(
queryResult.data.nft.eventIndex !== null &&
queryResult.data.nft.eventIndex > 0
)
})
it('should publish and transfer an NFT', async () => {
@ -106,7 +111,7 @@ describe('Tests coverage without provider/aquarius', async () => {
nftParams,
erc20Params
)
await sleep(2000)
await sleep(3000)
const erc721Address = result.events.NFTCreated.returnValues[0]
const nftAddress = erc721Address.toLowerCase()
@ -117,7 +122,7 @@ describe('Tests coverage without provider/aquarius', async () => {
newOwnerAccount
)
await sleep(2000)
await sleep(3000)
const query2 = {
query: `query {
nft(id:"${nftAddress}"){
@ -125,23 +130,30 @@ describe('Tests coverage without provider/aquarius', async () => {
id,
owner{id},
transferable,
transferHistory(orderBy: timestamp, orderDirection: desc){id,nft,oldOwner,newOwner,txId,timestamp,block}
transferHistory(orderBy: timestamp, orderDirection: desc){id,nft,oldOwner,newOwner,txId,eventIndex,timestamp,block}
}}`
}
const response = await fetch(subgraphUrl, {
method: 'POST',
body: JSON.stringify(query2)
})
await sleep(3000)
const queryResult = await response.json()
const transferHistory = queryResult.data.nft.transferHistory[0]
assert(queryResult.data.nft.owner.id === newOwnerAccount)
assert(
transferHistory.id ===
`${nftAddress}-${tx.transactionHash}-${tx.events.Transfer.logIndex}`,
`${nftAddress}-${
tx.transactionHash
}-${tx.events.Transfer.logIndex.toFixed(1)}`,
'Invalid transferHistory Id'
)
assert(transferHistory.txId === tx.transactionHash, 'invalid txId')
assert(
transferHistory.eventIndex === tx.events.Transfer.logIndex,
'invalid eventIndex'
)
assert(transferHistory.timestamp)
assert(transferHistory.timestamp >= time - 500, 'incorrect value timestamp')

View File

@ -324,7 +324,7 @@ describe('veOcean tests', async () => {
})
it('Alice should allocate 10% to NFT1', async () => {
await veAllocate.setAllocation(Alice, '1000', nft1, chainId)
const tx = await veAllocate.setAllocation(Alice, '1000', nft1, chainId)
const newTotalAllocation = await veAllocate.getTotalAllocation(Alice)
await sleep(2000)
let initialQuery = {
@ -332,6 +332,7 @@ describe('veOcean tests', async () => {
veAllocateUsers(id:"${Alice.toLowerCase()}"){
id,
allocatedTotal
eventIndex
}
}`
}
@ -347,13 +348,15 @@ describe('veOcean tests', async () => {
' to equal subgraph value ' +
info[0].allocatedTotal
)
assert(info[0].eventIndex === tx.events.AllocationSet.logIndex)
initialQuery = {
query: `query {
veAllocations(
where: {allocationUser:"${Alice.toLowerCase()}", chainId:"${chainId}", nftAddress:"${nft1.toLowerCase()}"}
){
id,
allocated
allocated,
eventIndex
}
}`
}
@ -367,10 +370,11 @@ describe('veOcean tests', async () => {
'Expected totalAllocation 1000 to equal subgraph value ' +
info[0].allocatedTotal
)
assert(info[0].eventIndex === tx.events.AllocationSet.logIndex)
})
it('Alice should allocate 10% to NFT2 and 20% to NFT3', async () => {
await veAllocate.setBatchAllocation(
const tx = await veAllocate.setBatchAllocation(
Alice,
['1000', '2000'],
[nft2, nft3],
@ -383,7 +387,8 @@ describe('veOcean tests', async () => {
query: `query {
veAllocateUsers(id:"${Alice.toLowerCase()}"){
id,
allocatedTotal
allocatedTotal,
eventIndex
}
}`
}
@ -399,13 +404,15 @@ describe('veOcean tests', async () => {
' to equal subgraph value ' +
info[0].allocatedTotal
)
assert(info[0].eventIndex === tx.events.AllocationSetMultiple.logIndex)
initialQuery = {
query: `query {
veAllocations(
where: {allocationUser:"${Alice.toLowerCase()}", chainId:"${chainId}", nftAddress:"${nft2.toLowerCase()}"}
){
id,
allocated
allocated,
eventIndex
}
}`
}
@ -419,6 +426,7 @@ describe('veOcean tests', async () => {
'Expected totalAllocation 1000 to equal subgraph value ' +
info[0].allocatedTotal
)
assert(info[0].eventIndex === tx.events.AllocationSetMultiple.logIndex)
initialQuery = {
query: `query {
veAllocations(
@ -749,6 +757,7 @@ describe('veOcean tests', async () => {
block
timestamp
tx
eventIndex
sender
amount
cancelTime