Skip to content

Commit

Permalink
fix: contract error decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
davidyuk committed Apr 22, 2021
1 parent b949270 commit d56931a
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 61 deletions.
51 changes: 17 additions & 34 deletions src/ae/contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,30 +28,21 @@

import Ae from './'
import * as R from 'ramda'
import { isBase64 } from '../utils/string'
import ContractCompilerAPI from '../contract/compiler'
import ContractBase from '../contract'
import getContractInstance from '../contract/aci'
import NodePool from '../node-pool'
import { AMOUNT, DEPOSIT, DRY_RUN_ACCOUNT, GAS, MIN_GAS_PRICE } from '../tx/builder/schema'
import { decode, produceNameId } from '../tx/builder/helpers'
import TxObject from '../tx/tx-object'
import { decodeBase64Check } from '../utils/crypto'

async function sendAndProcess (tx, options) {
async function _sendAndProcess (tx, source, name, options) {
const txData = await this.send(tx, options)

if (options.waitMined === false) {
return { hash: txData.hash, rawTx: txData.rawTx }
}

const result = await this.getTxInfo(txData.hash)

if (result.returnType !== 'ok') {
await this._handleCallError(result, txData.rawTx)
}

return { hash: txData.hash, tx: TxObject({ tx: txData.rawTx }), result, txData, rawTx: txData.rawTx }
const result = { hash: txData.hash, tx: TxObject({ tx: txData.rawTx }), txData, rawTx: txData.rawTx }
if (options.waitMined === false) return result
const txInfo = await this.getTxInfo(txData.hash)
await this._handleCallError(source, name, txInfo)
return { ...result, result: txInfo }
}

/**
Expand All @@ -60,24 +51,17 @@ async function sendAndProcess (tx, options) {
* @private
* @alias module:@aeternity/aepp-sdk/es/ae/contract
* @category async
* @param {String} source contract source code
* @param {String} name name of called method
* @param {Object} result call result object
* @param {String} rawTx Raw transaction
* @throws Error Decoded error
* @return {Promise<void>}
*/
async function _handleCallError (result, rawTx) {
let error = Buffer.from(result.returnValue).toString()
error = isBase64(error.slice(3))
? decodeBase64Check(error.slice(3)).toString()
: await this.contractDecodeDataAPI('string', error)
throw Object.assign(
new Error(`Invocation failed${error ? `: "${error}"` : ''}`), {
...result,
tx: TxObject({ tx: rawTx }),
error,
rawTx
}
)
async function _handleCallError (source, name, result) {
if (result.returnType === 'ok') return
const error = await this.contractDecodeCallResultAPI(source, name, result.returnValue, result.returnType)
const message = error[{ revert: 'abort' }[result.returnType] || result.returnType][0]
throw new Error(`Invocation failed${message ? `: "${message}"` : ''}`)
}

/**
Expand Down Expand Up @@ -162,10 +146,8 @@ async function contractCallStatic (source, address, name, args = [], options = {

const { callObj, ...dryRunOther } = await this.txDryRun(tx, callerId, options)

await this._handleCallError(source, name, callObj)
const { returnType, returnValue } = callObj
if (returnType !== 'ok') {
await this._handleCallError(callObj, tx)
}
return {
...dryRunOther,
tx: TxObject({ tx }),
Expand Down Expand Up @@ -202,7 +184,7 @@ async function contractCall (source, address, name, argsOrCallData = [], options
callData: Array.isArray(argsOrCallData) ? await this.contractEncodeCall(source, name, argsOrCallData, opt) : argsOrCallData
}))

const { hash, rawTx, result, txData } = await sendAndProcess.call(this, tx, opt)
const { hash, rawTx, result, txData } = await this._sendAndProcess(tx, source, name, opt)
return {
hash,
rawTx,
Expand Down Expand Up @@ -246,7 +228,7 @@ async function contractDeploy (code, source, initState = [], options = {}) {
ownerId
}))

const { hash, rawTx, result, txData } = await sendAndProcess.call(this, tx, opt)
const { hash, rawTx, result, txData } = await this._sendAndProcess(tx, source, 'init', opt)
return Object.freeze({
result,
owner: ownerId,
Expand Down Expand Up @@ -452,6 +434,7 @@ export const ContractAPI = Ae.compose(ContractBase, {
contractEncodeCall,
contractDecodeData,
_handleCallError,
_sendAndProcess,
// Delegation for contract
// AENS
delegateSignatureCommon,
Expand Down
72 changes: 45 additions & 27 deletions test/integration/contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/
import Compiler from '../../src/contract/compiler'
import { describe, it, before } from 'mocha'
import { expect } from 'chai'
import { BaseAe, getSdk, compilerUrl, publicKey } from './'
import { decode } from '../../src/tx/builder/helpers'
import { DRY_RUN_ACCOUNT } from '../../src/tx/builder/schema'
Expand All @@ -30,11 +31,16 @@ contract Identity =
entrypoint main(x : int) = x
`

const errorContract = `
contract Identity =
payable stateful entrypoint main(x : address) = Chain.spend(x, 1000000000)
const contractWithBrokenDeploy = `
contract Foo =
entrypoint init() = require(false, "CustomErrorMessage")
`

payable stateful entrypoint foo() =
const contractWithBrokenMethods = `
contract Foo =
payable stateful entrypoint failWithoutMessage(x : address) = Chain.spend(x, 1000000000)
payable stateful entrypoint failWithMessage() =
require(false, "CustomErrorMessage")
`

Expand Down Expand Up @@ -369,19 +375,31 @@ describe('Contract', function () {
res.result.should.have.property('gasUsed')
res.result.should.have.property('returnType')
})
it('Test handleError(Parse and check contract execution error)', async () => {
const code = await contract.contractCompile(errorContract)
const deployed = await code.deploy()
try {
await deployed.call('main', [await contract.address()])
} catch (e) {
e.message.should.be.equal('Invocation failed')
}
try {
await deployed.call('foo')
} catch (e) {
e.message.should.be.equal('Invocation failed: "ICustomErrorMessage"')
}

describe('_handleCallError', () => {
it('throws error on deploy', async () => {
const code = await contract.contractCompile(contractWithBrokenDeploy)
try {
await code.deploy()
} catch (e) {
e.message.should.be.equal('Invocation failed: "CustomErrorMessage"')
}
})

it('throws errors on method call', async () => {
const code = await contract.contractCompile(contractWithBrokenMethods)
const deployed = await code.deploy()
try {
await deployed.call('failWithoutMessage', [await contract.address()])
} catch (e) {
e.message.should.be.equal('Invocation failed')
}
try {
await deployed.call('failWithMessage')
} catch (e) {
e.message.should.be.equal('Invocation failed: "CustomErrorMessage"')
}
})
})

it('Dry-run without accounts', async () => {
Expand All @@ -399,14 +417,14 @@ describe('Contract', function () {
return result.decode().should.eventually.become(42)
})

it('call contract/deploy with `waitMined: false`', async () => {
it('call contract/deploy with waitMined: false', async () => {
const deployed = await bytecode.deploy([], { waitMined: false })
await contract.poll(deployed.transaction, { interval: 50, attempts: 1200 })
Boolean(deployed.result === undefined).should.be.equal(true)
Boolean(deployed.txData === undefined).should.be.equal(true)
expect(deployed.result).to.be.equal(undefined)
deployed.txData.should.not.be.equal(undefined)
const result = await deployed.call('main', ['42'], { waitMined: false, verify: false })
Boolean(result.result === undefined).should.be.equal(true)
Boolean(result.txData === undefined).should.be.equal(true)
expect(result.result).to.be.equal(undefined)
result.txData.should.not.be.equal(undefined)
await contract.poll(result.hash, { interval: 50, attempts: 1200 })
})

Expand Down Expand Up @@ -652,14 +670,14 @@ describe('Contract', function () {
const isCompiled = contractObject.compiled.length && contractObject.compiled.slice(0, 3) === 'cb_'
isCompiled.should.be.equal(true)
})
it('Deploy/Call contract with { waitMined: false }', async () => {
it('Deploy/Call contract with waitMined: false', async () => {
const deployed = await contractObject.methods.init('123', 1, 'hahahaha', { waitMined: false })
await contract.poll(deployed.transaction, { interval: 50, attempts: 1200 })
Boolean(deployed.result === undefined).should.be.equal(true)
Boolean(deployed.txData === undefined).should.be.equal(true)
expect(deployed.result).to.be.equal(undefined)
expect(deployed.txData).to.be.equal(undefined)
const result = await contractObject.methods.intFn.send(2, { waitMined: false })
Boolean(result.result === undefined).should.be.equal(true)
Boolean(result.txData === undefined).should.be.equal(true)
expect(result.result).to.be.equal(undefined)
result.txData.should.not.be.equal(undefined)
await contract.poll(result.hash, { interval: 50, attempts: 1200 })
})
it('Generate ACI object with corresponding bytecode', async () => {
Expand Down

0 comments on commit d56931a

Please sign in to comment.