Skip to content

Commit

Permalink
Merge branch 'main' into contract-asso
Browse files Browse the repository at this point in the history
  • Loading branch information
philipsu522 authored May 17, 2024
2 parents 71aff59 + 16a2b18 commit 8ac1efa
Show file tree
Hide file tree
Showing 12 changed files with 64 additions and 39 deletions.
31 changes: 19 additions & 12 deletions contracts/src/CW721ERC721Pointer.sol
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
pragma solidity ^0.8.12;

import "@openzeppelin/contracts/token/common/ERC2981.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
Expand Down Expand Up @@ -46,18 +46,26 @@ contract CW721ERC721Pointer is ERC721,ERC2981 {
}
uint256 numTokens = 0;
string memory startAfter;
string memory ownerAddr = _formatPayload("owner", _doubleQuotes(AddrPrecompile.getSeiAddr(owner)));
string memory req = _curlyBrace(_formatPayload("tokens", _curlyBrace(ownerAddr)));
string memory qb = string.concat(
string.concat("\"limit\":1000,\"owner\":\"", AddrPrecompile.getSeiAddr(owner)),
"\""
);
bytes32 terminator = keccak256("{\"tokens\":[]}");

bytes[] memory tokens;
uint256 tokensLength;
string memory req = string.concat(string.concat("{\"tokens\":{", qb), "}}");
bytes memory response = WasmdPrecompile.query(Cw721Address, bytes(req));
bytes[] memory tokens = JsonPrecompile.extractAsBytesList(response, "tokens");
uint256 tokensLength = tokens.length;
while (tokensLength > 0) {
numTokens += tokensLength;
startAfter = _formatPayload("start_after", string(tokens[tokensLength-1]));
req = _curlyBrace(_formatPayload("tokens", _curlyBrace(_join(ownerAddr, startAfter, ","))));
response = WasmdPrecompile.query(Cw721Address, bytes(req));
while (keccak256(response) != terminator) {
tokens = JsonPrecompile.extractAsBytesList(response, "tokens");
tokensLength = tokens.length;
numTokens += tokensLength;
startAfter = string.concat(",\"start_after\":", string(tokens[tokensLength-1]));
req = string.concat(
string.concat("{\"tokens\":{", string.concat(qb, startAfter)),
"}}"
);
response = WasmdPrecompile.query(Cw721Address, bytes(req));
}
return numTokens;
}
Expand Down Expand Up @@ -128,8 +136,7 @@ contract CW721ERC721Pointer is ERC721,ERC2981 {

// 721-Enumerable
function totalSupply() public view virtual returns (uint256) {
string memory req = _curlyBrace(_formatPayload("num_tokens", "{}"));
bytes memory response = WasmdPrecompile.query(Cw721Address, bytes(req));
bytes memory response = WasmdPrecompile.query(Cw721Address, bytes("{\"num_tokens\":{}}"));
return JsonPrecompile.extractAsUint256(response, "count");
}

Expand Down
20 changes: 17 additions & 3 deletions contracts/test/CW721ERC721PointerTest.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -106,17 +106,17 @@ contract CW721ERC721PointerTest is Test {
function testBalanceOf() public {
vm.mockCall(
WASMD_PRECOMPILE_ADDRESS,
abi.encodeWithSignature("query(string,bytes)", MockCWContractAddress, bytes("{\"tokens\":{\"owner\":\"sei19zhelek4q5lt4zam8mcarmgv92vzgqd3ux32jw\"}}")),
abi.encodeWithSignature("query(string,bytes)", MockCWContractAddress, bytes("{\"tokens\":{\"limit\":1000,\"owner\":\"sei19zhelek4q5lt4zam8mcarmgv92vzgqd3ux32jw\"}}")),
abi.encode("{\"tokens\":[\"a\",\"b\"]}")
);
vm.mockCall(
WASMD_PRECOMPILE_ADDRESS,
abi.encodeWithSignature("query(string,bytes)", MockCWContractAddress, bytes("{\"tokens\":{\"owner\":\"sei19zhelek4q5lt4zam8mcarmgv92vzgqd3ux32jw\",\"start_after\":\"b\"}}")),
abi.encodeWithSignature("query(string,bytes)", MockCWContractAddress, bytes("{\"tokens\":{\"limit\":1000,\"owner\":\"sei19zhelek4q5lt4zam8mcarmgv92vzgqd3ux32jw\",\"start_after\":\"b\"}}")),
abi.encode("{\"tokens\":[\"c\",\"d\"]}")
);
vm.mockCall(
WASMD_PRECOMPILE_ADDRESS,
abi.encodeWithSignature("query(string,bytes)", MockCWContractAddress, bytes("{\"tokens\":{\"owner\":\"sei19zhelek4q5lt4zam8mcarmgv92vzgqd3ux32jw\",\"start_after\":\"d\"}}")),
abi.encodeWithSignature("query(string,bytes)", MockCWContractAddress, bytes("{\"tokens\":{\"limit\":1000,\"owner\":\"sei19zhelek4q5lt4zam8mcarmgv92vzgqd3ux32jw\",\"start_after\":\"d\"}}")),
abi.encode("{\"tokens\":[]}")
);
bytes[] memory resp1 = new bytes[](2);
Expand Down Expand Up @@ -158,6 +158,20 @@ contract CW721ERC721PointerTest is Test {
assertEq(pointer.ownerOf(1), 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266);
}

function testTotalSupply() public {
vm.mockCall(
WASMD_PRECOMPILE_ADDRESS,
abi.encodeWithSignature("query(string,bytes)", MockCWContractAddress, bytes("{\"num_tokens\":{}}")),
abi.encode("{\"count\":100}")
);
vm.mockCall(
JSON_PRECOMPILE_ADDRESS,
abi.encodeWithSignature("extractAsUint256(bytes,string)", bytes("{\"count\":100}"), "count"),
abi.encode(100)
);
assertEq(pointer.totalSupply(), 100);
}

function testGetApproved() public {
vm.mockCall(
WASMD_PRECOMPILE_ADDRESS,
Expand Down
Binary file modified contracts/wasm/cwerc721.wasm
Binary file not shown.
2 changes: 1 addition & 1 deletion example/cosmwasm/cw721/artifacts/checksums.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
dc05f927aaacb4d0f500ef7712607e06a55fa2d812cd21505bd1e98ed942273b cwerc721.wasm
4355b9f7c6a3337ee6994512155435bdfc80bd151a57e78fd50f9d41e62a8aaa cwerc721.wasm
Binary file modified example/cosmwasm/cw721/artifacts/cwerc721.wasm
Binary file not shown.
34 changes: 18 additions & 16 deletions example/cosmwasm/cw721/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,11 @@ pub fn execute_transfer_nft(
recipient: String,
token_id: String,
) -> Result<Response<EvmMsg>, ContractError> {
let mut res = transfer_nft(deps, info, recipient, token_id)?;
res = res.add_attribute("action", "transfer_nft");
let mut res = transfer_nft(deps, &info, &recipient, &token_id)?;
res = res.add_attribute("action", "transfer_nft")
.add_attribute("sender", info.sender)
.add_attribute("recipient", recipient)
.add_attribute("token_id", token_id);
Ok(res)
}

Expand All @@ -76,15 +79,18 @@ pub fn execute_send_nft(
token_id: String,
msg: Binary,
) -> Result<Response<EvmMsg>, ContractError> {
let mut res = transfer_nft(deps, info.clone(), recipient.clone(), token_id.clone())?;
let mut res = transfer_nft(deps, &info, &recipient, &token_id)?;
let send = Cw721ReceiveMsg {
sender: info.sender.to_string(),
token_id: token_id.clone(),
token_id: token_id.to_string(),
msg,
};
res = res
.add_message(send.into_cosmos_msg(recipient.clone())?)
.add_attribute("action", "send_nft");
.add_attribute("action", "send_nft")
.add_attribute("sender", info.sender)
.add_attribute("recipient", recipient)
.add_attribute("token_id", token_id);
Ok(res)
}

Expand Down Expand Up @@ -159,23 +165,19 @@ pub fn execute_extension() -> Result<Response<EvmMsg>, ContractError> {

fn transfer_nft(
deps: DepsMut<EvmQueryWrapper>,
info: MessageInfo,
recipient: String,
token_id: String,
info: &MessageInfo,
recipient: &str,
token_id: &str,
) -> Result<Response<EvmMsg>, ContractError> {
deps.api.addr_validate(&recipient)?;
deps.api.addr_validate(recipient)?;

let erc_addr = ERC721_ADDRESS.load(deps.storage)?;

let querier = EvmQuerier::new(&deps.querier);
let owner = querier.erc721_owner(info.sender.clone().into_string(), erc_addr.clone(), token_id.clone())?.owner;
let payload = querier.erc721_transfer_payload(owner, recipient.clone(), token_id.clone())?;
let owner = querier.erc721_owner(info.sender.to_string(), erc_addr.to_string(), token_id.to_string())?.owner;
let payload = querier.erc721_transfer_payload(owner, recipient.to_string(), token_id.to_string())?;
let msg = EvmMsg::DelegateCallEvm { to: erc_addr, data: payload.encoded_payload };
let res = Response::new()
.add_attribute("sender", info.sender)
.add_attribute("recipient", recipient)
.add_attribute("token_id", token_id)
.add_message(msg);
let res = Response::new().add_message(msg);

Ok(res)
}
Expand Down
2 changes: 1 addition & 1 deletion x/evm/artifacts/cw721/CW721ERC721Pointer.bin

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion x/evm/artifacts/cw721/artifacts.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/ethereum/go-ethereum/accounts/abi"
)

const CurrentVersion uint16 = 3
const CurrentVersion uint16 = 4

//go:embed CW721ERC721Pointer.abi
//go:embed CW721ERC721Pointer.bin
Expand Down
2 changes: 1 addition & 1 deletion x/evm/artifacts/erc721/artifacts.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package erc721

import "embed"

const CurrentVersion uint16 = 4
const CurrentVersion uint16 = 5

//go:embed cwerc721.wasm
var f embed.FS
Expand Down
Binary file modified x/evm/artifacts/erc721/cwerc721.wasm
Binary file not shown.
1 change: 1 addition & 0 deletions x/evm/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val
TxHashHex: deferredInfo.TxHash.Hex(),
TransactionIndex: uint32(deferredInfo.TxIndx),
VmError: deferredInfo.Error,
BlockNumber: uint64(ctx.BlockHeight()),
})
continue
}
Expand Down
9 changes: 5 additions & 4 deletions x/evm/module_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func TestModuleExportGenesis(t *testing.T) {
module := evm.NewAppModule(nil, k)
jsonMsg := module.ExportGenesis(ctx, types.ModuleCdc)
jsonStr := string(jsonMsg)
assert.Equal(t, "{\"params\":{\"priority_normalizer\":\"1.000000000000000000\",\"base_fee_per_gas\":\"0.000000000000000000\",\"minimum_fee_per_gas\":\"1000000000.000000000000000000\",\"whitelisted_cw_code_hashes_for_delegate_call\":[]},\"address_associations\":[{\"sei_address\":\"sei17xpfvakm2amg962yls6f84z3kell8c5la4jkdu\",\"eth_address\":\"0x27F7B8B8B5A4e71E8E9aA671f4e4031E3773303F\"}],\"codes\":[],\"states\":[],\"nonces\":[],\"serialized\":[{\"prefix\":\"Fg==\",\"key\":\"AwAB\",\"value\":\"AAAAAAAAAAM=\"},{\"prefix\":\"Fg==\",\"key\":\"BAAE\",\"value\":\"AAAAAAAAAAQ=\"}]}", jsonStr)
assert.Equal(t, "{\"params\":{\"priority_normalizer\":\"1.000000000000000000\",\"base_fee_per_gas\":\"0.000000000000000000\",\"minimum_fee_per_gas\":\"1000000000.000000000000000000\",\"whitelisted_cw_code_hashes_for_delegate_call\":[]},\"address_associations\":[{\"sei_address\":\"sei17xpfvakm2amg962yls6f84z3kell8c5la4jkdu\",\"eth_address\":\"0x27F7B8B8B5A4e71E8E9aA671f4e4031E3773303F\"}],\"codes\":[],\"states\":[],\"nonces\":[],\"serialized\":[{\"prefix\":\"Fg==\",\"key\":\"AwAB\",\"value\":\"AAAAAAAAAAM=\"},{\"prefix\":\"Fg==\",\"key\":\"BAAF\",\"value\":\"AAAAAAAAAAQ=\"}]}", jsonStr)
}

func TestConsensusVersion(t *testing.T) {
Expand Down Expand Up @@ -74,15 +74,15 @@ func TestABCI(t *testing.T) {
surplus, err := s.Finalize()
require.Nil(t, err)
require.Equal(t, sdk.ZeroInt(), surplus)
k.AppendToEvmTxDeferredInfo(ctx.WithTxIndex(1), ethtypes.Bloom{}, common.Hash{}, surplus)
k.AppendToEvmTxDeferredInfo(ctx.WithTxIndex(1), ethtypes.Bloom{}, common.Hash{4}, surplus)
// 3rd tx
s = state.NewDBImpl(ctx.WithTxIndex(3), k, false)
s.SubBalance(evmAddr2, big.NewInt(5000000000000), tracing.BalanceChangeUnspecified)
s.AddBalance(evmAddr1, big.NewInt(5000000000000), tracing.BalanceChangeUnspecified)
surplus, err = s.Finalize()
require.Nil(t, err)
require.Equal(t, sdk.ZeroInt(), surplus)
k.AppendToEvmTxDeferredInfo(ctx.WithTxIndex(3), ethtypes.Bloom{}, common.Hash{}, surplus)
k.AppendToEvmTxDeferredInfo(ctx.WithTxIndex(3), ethtypes.Bloom{}, common.Hash{3}, surplus)
k.SetTxResults([]*abci.ExecTxResult{{Code: 0}, {Code: 0}, {Code: 0}, {Code: 0}})
m.EndBlock(ctx, abci.RequestEndBlock{})
require.Equal(t, uint64(0), k.BankKeeper().GetBalance(ctx, k.AccountKeeper().GetModuleAddress(types.ModuleName), "usei").Amount.Uint64())
Expand All @@ -97,7 +97,7 @@ func TestABCI(t *testing.T) {
surplus, err = s.Finalize()
require.Nil(t, err)
require.Equal(t, sdk.NewInt(1000000000000), surplus)
k.AppendToEvmTxDeferredInfo(ctx.WithTxIndex(2), ethtypes.Bloom{}, common.Hash{}, surplus)
k.AppendToEvmTxDeferredInfo(ctx.WithTxIndex(2), ethtypes.Bloom{}, common.Hash{2}, surplus)
k.SetTxResults([]*abci.ExecTxResult{{Code: 0}, {Code: 0}, {Code: 0}})
m.EndBlock(ctx, abci.RequestEndBlock{})
require.Equal(t, uint64(1), k.BankKeeper().GetBalance(ctx, k.AccountKeeper().GetModuleAddress(types.ModuleName), "usei").Amount.Uint64())
Expand All @@ -110,6 +110,7 @@ func TestABCI(t *testing.T) {
m.EndBlock(ctx, abci.RequestEndBlock{})
receipt, err := k.GetReceipt(ctx, common.Hash{1})
require.Nil(t, err)
require.Equal(t, receipt.BlockNumber, uint64(ctx.BlockHeight()))
require.Equal(t, receipt.VmError, "test error")

// fourth block with locked tokens in coinbase address
Expand Down

0 comments on commit 8ac1efa

Please sign in to comment.