```exchange.IO("decode", ...)```函数返回解码后的数据。 当```dataFormat```参数指定的数据只有一个时返回一个字符串。 当```dataFormat```参数指定的数据有多个时返回一个数组。
array、string
exchange.IO(k, dataFormat, data)
```k```参数用于设置```exchange.IO()```函数的功能,设置为```"decode"```表示该函数用于数据解码。
k
true
string
```dataFormat```参数用于指定解码数据的类型、顺序。
dataFormat
true
string
```data```参数用于设置所要解码的数据。
data
true
string
```javascript
function main() {
var types = "tuple(a uint256,b uint8,c address),bytes"
var ret = exchange.IO("encode", types, {
a: 30,
b: 20,
c: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
}, "0011")
Log("encode: ", ret)
var rawData = exchange.IO("decode", types, ret)
Log("decode:", rawData)
}
```javascript
function main() {
// register SwapRouter02 abi
var walletAddress = "0x398a93ca23CBdd2642a07445bCD2b8435e0a373f"
var routerAddress = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"
var abi = `[{"inputs":[{"components":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMaximum","type":"uint256"}],"internalType":"struct IV3SwapRouter.ExactOutputParams","name":"params","type":"tuple"}],"name":"exactOutput","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"payable","type":"function"}]`
exchange.IO("abi", routerAddress, abi) // abi只使用了局部的exactOutput方法的内容,完整的abi可以在网上搜索
// encode path
var fee = exchange.IO("encodePacked", "uint24", 3000)
var tokenInAddress = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
var tokenOutAddress = "0xdac17f958d2ee523a2206206994597c13d831ec7"
var path = tokenInAddress.slice(2).toLowerCase()
path += fee + tokenOutAddress.slice(2).toLowerCase()
Log("path:", path)
var dataTuple = {
"path" : path,
"recipient" : walletAddress,
"amountOut" : 1000,
"amountInMaximum" : 1,
}
// encode SwapRouter02 exactOutput
var rawData = exchange.IO("encode", routerAddress, "exactOutput", dataTuple)
Log("method hash:", rawData.slice(0, 8)) // 09b81346
Log("params hash:", rawData.slice(8))
// decode exactOutput params
var decodeRaw = exchange.IO("decode", "tuple(path bytes,recipient address,amountOut uint256,amountInMaximum uint256)", rawData.slice(8))
Log("decodeRaw:", decodeRaw)
}
以下例子首先在path
参数处理时进行了encodePacked
操作,因为之后需要编码的exactOutput
方法调用需要path
作为参数。 然后encode
路由合约的exactOutput
方法,该方法只有一个参数,参数类型是tuple
类型。 exactOutput
这个方法名编码后即:0x09b81346
,使用exchange.IO("decode", ...)
方法解码得出decodeRaw
,与变量dataTuple
一致。
对于数据的处理,exchange.IO()
函数不仅支持编码(encode),也支持解码(decode)。